Skip to main content

c/
process.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// syscall wrappers: fstat/newfstatat/getrlimit/setrlimit/utimensat
6// ============================================================
7
8#[inline]
9unsafe fn sys_newfstatat(dirfd: i32, path: *const c_char, buf: *mut u8, flags: i32) -> i64 {
10    <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, dirfd as i64, path as i64, buf as i64, flags as i64)
11}
12
13#[inline]
14unsafe fn sys_fstat(fd: i32, buf: *mut u8) -> i64 {
15    <Arch as Syscalls>::syscall2(SYS_FSTAT, fd as i64, buf as i64)
16}
17
18// Linux removed the legacy getrlimit/setrlimit entry points on some
19// architectures (qemu-ppc64le reports syscall 76 as unknown); prlimit64
20// with pid 0 provides the same semantics.
21#[cfg(any(target_arch = "powerpc64", target_arch = "loongarch64"))]
22#[inline]
23unsafe fn sys_getrlimit(resource: i32, rlim: *mut u8) -> i64 {
24    <Arch as Syscalls>::syscall4(SYS_PRLIMIT64, 0, resource as i64, 0, rlim as i64)
25}
26
27#[cfg(any(target_arch = "powerpc64", target_arch = "loongarch64"))]
28#[inline]
29unsafe fn sys_setrlimit(resource: i32, rlim: *const u8) -> i64 {
30    <Arch as Syscalls>::syscall4(SYS_PRLIMIT64, 0, resource as i64, rlim as i64, 0)
31}
32
33#[cfg(not(any(target_arch = "powerpc64", target_arch = "loongarch64")))]
34#[inline]
35unsafe fn sys_getrlimit(resource: i32, rlim: *mut u8) -> i64 {
36    <Arch as Syscalls>::syscall2(SYS_GETRLIMIT, resource as i64, rlim as i64)
37}
38
39#[cfg(not(any(target_arch = "powerpc64", target_arch = "loongarch64")))]
40#[inline]
41unsafe fn sys_setrlimit(resource: i32, rlim: *const u8) -> i64 {
42    <Arch as Syscalls>::syscall2(SYS_SETRLIMIT, resource as i64, rlim as i64)
43}
44
45#[inline]
46unsafe fn sys_utimensat(dirfd: i32, path: *const c_char, times: *const u8, flags: i32) -> i64 {
47    <Arch as Syscalls>::syscall4(SYS_UTIMENSAT, dirfd as i64, path as i64, times as i64, flags as i64)
48}
49
50// ============================================================
51// unistd.h: process primitives
52// ============================================================
53
54#[inline]
55unsafe fn sys_fork() -> i64 {
56    #[cfg(target_arch = "x86_64")]
57    { <Arch as Syscalls>::syscall0(SYS_FORK) }
58    #[cfg(target_arch = "aarch64")]
59    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
60    #[cfg(target_arch = "riscv64")]
61    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
62    #[cfg(target_arch = "powerpc64")]
63    { <Arch as Syscalls>::syscall0(SYS_FORK) }
64    #[cfg(target_arch = "loongarch64")]
65    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
66}
67
68
69#[inline]
70unsafe fn sys_execve(path: *const c_char, argv: *const *const c_char, envp: *const *const c_char) -> i64 {
71    <Arch as Syscalls>::syscall3(SYS_EXECVE, path as i64, argv as i64, envp as i64)
72}
73
74#[inline]
75unsafe fn sys_wait4(pid: c_int, status: *mut c_int, options: c_int, rusage: *mut c_void) -> i64 {
76    <Arch as Syscalls>::syscall4(SYS_WAIT4, pid as i64, status as i64, options as i64, rusage as i64)
77}
78
79#[inline]
80unsafe fn sys_getppid() -> i64 {
81    <Arch as Syscalls>::syscall0(SYS_GETPPID)
82}
83
84#[inline]
85unsafe fn sys_getuid() -> i64 {
86    <Arch as Syscalls>::syscall0(SYS_GETUID)
87}
88
89#[inline]
90unsafe fn sys_getgid() -> i64 {
91    <Arch as Syscalls>::syscall0(SYS_GETGID)
92}
93
94#[inline]
95unsafe fn sys_geteuid() -> i64 {
96    <Arch as Syscalls>::syscall0(SYS_GETEUID)
97}
98
99#[inline]
100unsafe fn sys_getegid() -> i64 {
101    <Arch as Syscalls>::syscall0(SYS_GETEGID)
102}
103
104#[no_mangle]
105pub unsafe extern "C" fn fork() -> c_int {
106    __fork_handler(-1);
107    let ret = sys_fork();
108    // Run the atfork handlers before publishing errno, exactly like musl's
109    // __syscall_ret: a failing fork must report the kernel's errno even if a
110    // handler changes errno. RLIMIT_NPROC is enforced by the kernel and does
111    // not apply to root, so do not second-guess it here.
112    if ret < 0 {
113        let err = (-ret) as c_int;
114        __fork_handler(0);
115        ERRNO!() = err;
116        return -1;
117    }
118    if ret == 0 {
119        allocator_after_fork();
120        thread_allocator_after_fork();
121        __fork_handler(1);
122    } else {
123        __fork_handler(0);
124    }
125    ret as c_int
126}
127
128#[no_mangle]
129pub unsafe extern "C" fn execve(
130    path: *const c_char,
131    argv: *const *const c_char,
132    envp: *const *const c_char,
133) -> c_int {
134    let r = sys_execve(path, argv, envp);
135    syscall_ret(r) as c_int
136}
137
138#[no_mangle]
139pub unsafe extern "C" fn wait(status: *mut c_int) -> c_int {
140    let r = sys_wait4(-1, status, 0, core::ptr::null_mut());
141    syscall_ret(r) as c_int
142}
143
144#[no_mangle]
145pub unsafe extern "C" fn waitpid(pid: c_int, status: *mut c_int, options: c_int) -> c_int {
146    let r = sys_wait4(pid, status, options, core::ptr::null_mut());
147    syscall_ret(r) as c_int
148}
149
150#[no_mangle]
151pub unsafe extern "C" fn getppid() -> c_int {
152    sys_getppid() as c_int
153}
154
155#[no_mangle]
156pub unsafe extern "C" fn getuid() -> c_uint {
157    sys_getuid() as c_uint
158}
159
160#[no_mangle]
161pub unsafe extern "C" fn getgid() -> c_uint {
162    sys_getgid() as c_uint
163}
164
165#[no_mangle]
166pub unsafe extern "C" fn geteuid() -> c_uint {
167    sys_geteuid() as c_uint
168}
169
170#[no_mangle]
171pub unsafe extern "C" fn getegid() -> c_uint {
172    sys_getegid() as c_uint
173}
174
175#[no_mangle]
176pub unsafe extern "C" fn vfork() -> c_int {
177    // keel uses the portable fork semantics; fork() also runs the atfork
178    // handlers and resets the allocator/thread caches in the child.
179    fork()
180}
181
182#[no_mangle]
183pub unsafe extern "C" fn execl(path: *const c_char, arg: *const c_char, mut args: ...) -> c_int {
184    let mut cap = 16usize;
185    let mut argv = malloc(cap * core::mem::size_of::<*const c_char>()) as *mut *const c_char;
186    if argv.is_null() { ERRNO!() = ENOMEM; return -1; }
187    *argv.add(0) = arg;
188    let mut n: usize = 1;
189    loop {
190        let a: *const c_char = args.next_arg();
191        if a.is_null() { break; }
192        if n + 1 >= cap {
193            cap = match cap.checked_mul(2) { Some(v) => v, None => { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; } };
194            let grown = realloc(argv as *mut c_void, cap * core::mem::size_of::<*const c_char>()) as *mut *const c_char;
195            if grown.is_null() { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; }
196            argv = grown;
197        }
198        *argv.add(n) = a;
199        n += 1;
200    }
201    *argv.add(n) = core::ptr::null();
202    let r = sys_execve(path, argv, __environ as *const *const c_char);
203    free(argv as *mut c_void);
204    syscall_ret(r) as c_int
205}
206
207// ============================================================
208// spawn.h: posix_spawn family
209// ============================================================
210
211// Matches musl's posix_spawn_file_actions_t layout.  Actions are a growable
212// linked list; PATH search uses a stack buffer and an O(n) scan per entry.
213unsafe fn spawn_execvp(file: *const c_char, argv: *const *const c_char, envp: *const *const c_char) -> ! {
214    let flen = strlen(file as *const c_char);
215    let f = file as *const u8;
216    let mut has_slash = false;
217    for i in 0..flen {
218        if *f.add(i) == b'/' { has_slash = true; break; }
219    }
220    if has_slash {
221        sys_execve(file, argv, envp);
222        _exit(127);
223    }
224    let path = getenv(b"PATH\0".as_ptr() as *const c_char);
225    let default_path = b"/usr/local/bin:/usr/bin:/bin\0";
226    let p = if path.is_null() { default_path.as_ptr() } else { path as *const u8 };
227    let plen = strlen(p as *const c_char);
228    let mut buf = [0u8; PATH_MAX_V];
229    let mut i: usize = 0;
230    while i <= plen {
231        let start = i;
232        while i < plen && *p.add(i) != b':' { i += 1; }
233        let dlen = i - start;
234        if dlen > 0 && dlen + 1 + flen < PATH_MAX_V {
235            core::ptr::copy_nonoverlapping(p.add(start), buf.as_mut_ptr(), dlen);
236            *buf.as_mut_ptr().add(dlen) = b'/';
237            core::ptr::copy_nonoverlapping(f, buf.as_mut_ptr().add(dlen + 1), flen + 1);
238            sys_execve(buf.as_ptr() as *const c_char, argv, envp);
239            // execve failed, try next
240        }
241        i += 1; // skip ':'
242    }
243    _exit(127);
244}
245
246#[no_mangle]
247pub unsafe extern "C" fn posix_spawnp(
248    pid: *mut c_int,
249    file: *const c_char,
250    fa: *const posix_spawn_file_actions_t,
251    attrp: *const posix_spawnattr_t,
252    argv: *const *const c_char,
253    envp: *const *const c_char,
254) -> c_int {
255    let child = sys_fork();
256    if child < 0 {
257        ERRNO!() = (-child) as c_int;
258        return -1;
259    }
260    if child == 0 {
261        // child: apply attributes and file actions, then exec
262        spawn_apply_attr(attrp);
263        spawn_apply_actions(fa);
264        let actual_envp = if envp.is_null() { __environ as *const *const c_char } else { envp };
265        spawn_execvp(file, argv, actual_envp);
266    }
267    *pid = child as c_int;
268    0
269}
270
271#[no_mangle]
272pub unsafe extern "C" fn posix_spawn(
273    pid: *mut c_int,
274    path: *const c_char,
275    fa: *const posix_spawn_file_actions_t,
276    attrp: *const posix_spawnattr_t,
277    argv: *const *const c_char,
278    envp: *const *const c_char,
279) -> c_int {
280    // posix_spawnp() skips PATH search when the path contains '/', so it is
281    // also the correct implementation of posix_spawn().
282    posix_spawnp(pid, path, fa, attrp, argv, envp)
283}
284
285// ============================================================
286// sys/stat.h: stat / fstat / utimensat / futimens
287// ============================================================
288
289#[cfg(any(target_arch = "x86_64", target_arch = "powerpc64"))]
290#[repr(C)]
291pub struct Stat {
292    pub st_dev: u64,
293    pub st_ino: u64,
294    pub st_nlink: u64,
295    pub st_mode: u32,
296    pub st_uid: u32,
297    pub st_gid: u32,
298    _pad0: u32,
299    pub st_rdev: u64,
300    pub st_size: i64,
301    pub st_blksize: i64,
302    pub st_blocks: i64,
303    pub st_atim: timespec,
304    pub st_mtim: timespec,
305    pub st_ctim: timespec,
306    _unused: [i64; 3],
307}
308
309#[cfg(any(target_arch = "aarch64", target_arch = "riscv64", target_arch = "loongarch64"))]
310#[repr(C)]
311pub struct Stat {
312    pub st_dev: u64,
313    pub st_ino: u64,
314    pub st_mode: u32,
315    pub st_nlink: u32,
316    pub st_uid: u32,
317    pub st_gid: u32,
318    pub st_rdev: u64,
319    __pad1: u64,
320    pub st_size: i64,
321    pub st_blksize: i32,
322    __pad2: i32,
323    pub st_blocks: i64,
324    pub st_atim: timespec,
325    pub st_mtim: timespec,
326    pub st_ctim: timespec,
327    __unused4: u32,
328    __unused5: u32,
329}
330
331pub const S_IFMT: u32 = 0o170000;
332pub const S_IFDIR: u32 = 0o040000;
333pub const S_IFCHR: u32 = 0o020000;
334pub const S_IFBLK: u32 = 0o060000;
335pub const S_IFREG: u32 = 0o100000;
336pub const S_IFLNK: u32 = 0o120000;
337pub const S_IFIFO: u32 = 0o010000;
338pub const S_IFSOCK: u32 = 0o140000;
339
340pub const AT_FDCWD: i32 = -100;
341
342const AT_SYMLINK_NOFOLLOW: c_int = 0x100;
343const AT_EACCESS: c_int = 0x200;
344const AT_REMOVEDIR: c_int = 0x200;
345
346#[no_mangle]
347pub unsafe extern "C" fn stat(path: *const c_char, buf: *mut Stat) -> c_int {
348    let r = sys_newfstatat(AT_FDCWD, path, buf as *mut u8, 0);
349    syscall_ret(r) as c_int
350}
351
352#[no_mangle]
353pub unsafe extern "C" fn fstat(fd: c_int, buf: *mut Stat) -> c_int {
354    let r = sys_fstat(fd, buf as *mut u8);
355    syscall_ret(r) as c_int
356}
357
358// ============================================================
359// sys/resource.h: getrlimit / setrlimit
360// ============================================================
361
362#[repr(C)]
363pub struct Rlimit {
364    pub rlim_cur: u64,
365    pub rlim_max: u64,
366}
367
368pub const RLIMIT_NOFILE: c_int = 7;
369pub const RLIMIT_STACK: c_int = 3;
370pub const RLIMIT_DATA: c_int = 2;
371pub const RLIMIT_AS: c_int = 9;
372pub const RLIMIT_CPU: c_int = 0;
373pub const RLIMIT_FSIZE: c_int = 1;
374pub const RLIMIT_CORE: c_int = 4;
375pub const RLIMIT_RSS: c_int = 5;
376pub const RLIMIT_NPROC: c_int = 6;
377pub const RLIMIT_MEMLOCK: c_int = 8;
378pub const RLIMIT_LOCKS: c_int = 10;
379pub const RLIMIT_SIGPENDING: c_int = 11;
380pub const RLIMIT_MSGQUEUE: c_int = 12;
381pub const RLIMIT_NICE: c_int = 13;
382pub const RLIMIT_RTPRIO: c_int = 14;
383pub const RLIMIT_RTTIME: c_int = 15;
384pub const RLIM_INFINITY: u64 = !0u64;
385
386#[no_mangle]
387pub unsafe extern "C" fn getrlimit(resource: c_int, rlim: *mut Rlimit) -> c_int {
388    let r = sys_getrlimit(resource, rlim as *mut u8);
389    syscall_ret(r) as c_int
390}
391
392#[no_mangle]
393pub unsafe extern "C" fn setrlimit(resource: c_int, rlim: *const Rlimit) -> c_int {
394    let r = sys_setrlimit(resource, rlim as *const u8);
395    syscall_ret(r) as c_int
396}
397
398// ============================================================
399// utimensat / futimens
400// ============================================================
401
402#[no_mangle]
403pub unsafe extern "C" fn utimensat(dirfd: c_int, path: *const c_char, times: *const timespec, flags: c_int) -> c_int {
404    let r = sys_utimensat(dirfd, path, times as *const u8, flags);
405    syscall_ret(r) as c_int
406}
407
408#[no_mangle]
409pub unsafe extern "C" fn futimens(fd: c_int, times: *const timespec) -> c_int {
410    let r = sys_utimensat(fd, core::ptr::null(), times as *const u8, 0);
411    syscall_ret(r) as c_int
412}
413
414include!("socket.rs");
415include!("shm_sem.rs");