Skip to main content

c/
unistd_ext.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// unistd extensions: pipe, dup, dup2, fcntl, access, unlink, etc.
6// ============================================================
7
8#[inline]
9unsafe fn sys_dup(oldfd: i32) -> i64 {
10    <Arch as Syscalls>::syscall1(SYS_DUP, oldfd as i64)
11}
12
13#[inline]unsafe fn sys_dup2(oldfd: i32, newfd: i32) -> i64 {
14    // dup3 with flags=0 is equivalent to dup2
15    sys_dup3(oldfd, newfd, 0)
16}
17
18#[inline]
19unsafe fn sys_access(path: *const u8, mode: i32) -> i64 {
20    <Arch as Syscalls>::syscall4(SYS_FACCESSAT, AT_FDCWD as i64, path as i64, mode as i64, 0)
21}
22
23#[inline]unsafe fn sys_unlink(path: *const u8) -> i64 {
24    sys_unlinkat(AT_FDCWD, path, 0)
25}
26
27#[inline]unsafe fn sys_rmdir(path: *const u8) -> i64 {
28    sys_unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
29}
30
31#[inline]
32unsafe fn sys_chdir(path: *const u8) -> i64 {
33    <Arch as Syscalls>::syscall1(SYS_CHDIR, path as i64)
34}
35
36#[inline]
37unsafe fn sys_getcwd(buf: *mut u8, size: usize) -> i64 {
38    <Arch as Syscalls>::syscall2(SYS_GETCWD, buf as i64, size as i64)
39}
40
41#[inline]
42unsafe fn sys_sethostname(name: *const u8, len: usize) -> i64 {
43    <Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)
44}
45
46#[inline]
47unsafe fn sys_gethostname(buf: *mut u8, len: usize) -> i64 {
48    #[repr(C)]
49    struct UtsName {
50        sysname: [u8; 65],
51        nodename: [u8; 65],
52        release: [u8; 65],
53        version: [u8; 65],
54        machine: [u8; 65],
55        domainname: [u8; 65],
56    }
57    let mut uts: UtsName = core::mem::zeroed();
58    let result = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
59    if result < 0 {
60        return result;
61    }
62    let nlen = strlen(uts.nodename.as_ptr() as *const c_char);
63    let copylen = if nlen < len { nlen } else { if len > 0 { len - 1 } else { 0 } };
64    core::ptr::copy_nonoverlapping(uts.nodename.as_ptr(), buf, copylen);
65    if len > 0 { *buf.add(copylen) = 0; }
66    0
67}
68
69unsafe fn sys_truncate(path: *const u8, length: i64) -> i64 {
70    <Arch as Syscalls>::syscall2(SYS_TRUNCATE, path as i64, length as i64)
71}
72
73unsafe fn sys_ftruncate(fd: i32, length: i64) -> i64 {
74    <Arch as Syscalls>::syscall2(SYS_FTRUNCATE, fd as i64, length as i64)
75}
76
77unsafe fn sys_nanosleep(req: *const timespec, rem: *mut timespec) -> i64 {
78    <Arch as Syscalls>::syscall2(SYS_NANOSLEEP, req as i64, rem as i64)
79}
80
81const ITIMER_REAL: i32 = 0;
82
83#[repr(C)]
84struct itimerval {
85    it_interval: timeval,
86    it_value: timeval,
87}
88
89unsafe fn sys_alarm(seconds: c_uint) -> i64 {
90    let mut new: itimerval = core::mem::zeroed();
91    new.it_value.tv_sec = seconds as c_long;
92    let mut old: itimerval = core::mem::zeroed();
93    let r = <Arch as Syscalls>::syscall3(
94        SYS_SETITIMER,
95        ITIMER_REAL as i64,
96        &new as *const _ as i64,
97        &mut old as *mut _ as i64,
98    );
99    if r < 0 {
100        return r;
101    }
102    old.it_value.tv_sec as i64 + (old.it_value.tv_usec != 0) as i64
103}
104
105unsafe fn sys_pause() -> i64 {
106    #[cfg(target_arch = "x86_64")]
107    { <Arch as Syscalls>::syscall0(SYS_PAUSE) }
108    #[cfg(target_arch = "aarch64")]
109    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
110    #[cfg(target_arch = "riscv64")]
111    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
112    #[cfg(target_arch = "powerpc64")]
113    { <Arch as Syscalls>::syscall0(SYS_PAUSE) }
114    #[cfg(target_arch = "loongarch64")]
115    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
116}
117
118unsafe fn sys_fsync(fd: i32) -> i64 {
119    <Arch as Syscalls>::syscall1(SYS_FSYNC, fd as i64)
120}
121
122unsafe fn sys_fdatasync(fd: i32) -> i64 {
123    <Arch as Syscalls>::syscall1(SYS_FDATASYNC, fd as i64)
124}
125
126unsafe fn sys_sync() {
127    let _ = <Arch as Syscalls>::syscall0(SYS_SYNC);
128}
129
130unsafe fn sys_symlink(target: *const u8, linkpath: *const u8) -> i64 {
131    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, AT_FDCWD as i64, linkpath as i64)
132}
133
134unsafe fn sys_symlinkat(target: *const u8, newdirfd: i32, linkpath: *const u8) -> i64 {
135    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)
136}
137
138unsafe fn sys_readlinkat(dirfd: i32, path: *const u8, buf: *mut u8, bufsiz: usize) -> i64 {
139    <Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, path as i64, buf as i64, bufsiz as i64)
140}
141
142unsafe fn sys_linkat(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: i32) -> i64 {
143    <Arch as Syscalls>::syscall5(SYS_LINKAT, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
144}
145
146unsafe fn sys_fchmod(fd: i32, mode: u32) -> i64 {
147    <Arch as Syscalls>::syscall2(SYS_FCHMOD, fd as i64, mode as i64)
148}
149
150unsafe fn sys_fchmodat(dirfd: i32, path: *const u8, mode: u32, flags: i32) -> i64 {
151    <Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, path as i64, mode as i64, flags as i64)
152}
153
154unsafe fn sys_umask(mask: u32) -> u32 {
155    <Arch as Syscalls>::syscall1(SYS_UMASK, mask as i64) as u32
156}
157
158unsafe fn sys_getgroups(size: i32, list: *mut c_uint) -> i64 {
159    <Arch as Syscalls>::syscall2(SYS_GETGROUPS, size as i64, list as i64)
160}
161
162unsafe fn sys_setuid(uid: c_uint) -> i64 {
163    <Arch as Syscalls>::syscall1(SYS_SETUID, uid as i64)
164}
165
166unsafe fn sys_setgid(gid: c_uint) -> i64 {
167    <Arch as Syscalls>::syscall1(SYS_SETGID, gid as i64)
168}
169
170unsafe fn sys_setsid() -> i64 {
171    <Arch as Syscalls>::syscall0(SYS_SETSID)
172}
173
174unsafe fn sys_setpgid(pid: c_int, pgid: c_int) -> i64 {
175    <Arch as Syscalls>::syscall2(SYS_SETPGID, pid as i64, pgid as i64)
176}
177
178unsafe fn sys_getpgid(pid: c_int) -> i64 {
179    <Arch as Syscalls>::syscall1(SYS_GETPGID, pid as i64)
180}
181
182unsafe fn sys_getsid(pid: c_int) -> i64 {
183    <Arch as Syscalls>::syscall1(SYS_GETSID, pid as i64)
184}
185
186unsafe fn sys_mkdirat(dirfd: i32, path: *const u8, mode: u32) -> i64 {
187    <Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, path as i64, mode as i64)
188}
189
190// Public C ABI wrappers for unistd
191
192#[no_mangle]
193pub unsafe extern "C" fn pipe(fds: *mut c_int) -> c_int {
194    let r = sys_pipe2(fds, 0);
195    syscall_ret(r) as c_int
196}
197
198#[no_mangle]
199pub unsafe extern "C" fn pipe2(fds: *mut c_int, flags: c_int) -> c_int {
200    let r = sys_pipe2(fds, flags);
201    syscall_ret(r) as c_int
202}
203
204#[no_mangle]
205pub unsafe extern "C" fn dup(oldfd: c_int) -> c_int {
206    let r = sys_dup(oldfd);
207    syscall_ret(r) as c_int
208}
209
210#[no_mangle]
211pub unsafe extern "C" fn dup2(oldfd: c_int, newfd: c_int) -> c_int {
212    if oldfd == newfd {
213        // dup3 rejects equal descriptors with EINVAL; dup2 must validate the
214        // descriptor and return newfd unchanged.
215        let r = sys_fcntl(oldfd, 1 /* F_GETFD */, 0);
216        if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
217        return newfd;
218    }
219    let r = sys_dup2(oldfd, newfd);
220    syscall_ret(r) as c_int
221}
222
223#[no_mangle]
224pub unsafe extern "C" fn dup3(oldfd: c_int, newfd: c_int, flags: c_int) -> c_int {
225    let r = sys_dup3(oldfd, newfd, flags);
226    syscall_ret(r) as c_int
227}
228
229#[no_mangle]
230pub unsafe extern "C" fn fcntl(fd: c_int, cmd: c_int, mut args: ...) -> c_int {
231    // Commands without an argument. Everything else (including seals,
232    // pipe sizes, ownership and locks) takes the third argument.
233    let no_arg = matches!(cmd, F_GETFD | F_GETFL | F_GETOWN | F_GETSIG
234        | F_GETLEASE | F_GETPIPE_SZ | F_GET_SEALS);
235    let r = if no_arg {
236        sys_fcntl(fd, cmd, 0)
237    } else {
238        let arg = args.next_arg::<c_long>();
239        sys_fcntl(fd, cmd, arg)
240    };
241    syscall_ret(r) as c_int
242}
243
244#[no_mangle]
245pub unsafe extern "C" fn access(path: *const c_char, mode: c_int) -> c_int {
246    let r = sys_access(path as *const u8, mode);
247    syscall_ret(r) as c_int
248}
249
250#[no_mangle]
251pub unsafe extern "C" fn unlink(path: *const c_char) -> c_int {
252    let r = sys_unlink(path as *const u8);
253    syscall_ret(r) as c_int
254}
255
256#[no_mangle]
257pub unsafe extern "C" fn rmdir(path: *const c_char) -> c_int {
258    let r = sys_rmdir(path as *const u8);
259    syscall_ret(r) as c_int
260}
261
262#[no_mangle]
263pub unsafe extern "C" fn chdir(path: *const c_char) -> c_int {
264    let r = sys_chdir(path as *const u8);
265    syscall_ret(r) as c_int
266}
267
268#[no_mangle]
269pub unsafe extern "C" fn getcwd(buf: *mut c_char, size: usize) -> *mut c_char {
270    if buf.is_null() {
271        // allocate
272        let alloc_size = if size == 0 { 256 } else { size };
273        let p = malloc(alloc_size) as *mut c_char;
274        if p.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
275        let r = sys_getcwd(p as *mut u8, alloc_size);
276        if r < 0 { free(p as *mut c_void); ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
277        // The kernel returns "(unreachable)..." when cwd is outside the
278        // current root; POSIX getcwd must fail with ENOENT in that case.
279        if *p as u8 != b'/' {
280            free(p as *mut c_void);
281            ERRNO!() = ENOENT;
282            return core::ptr::null_mut();
283        }
284        return p;
285    }
286    if size == 0 { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
287    let r = sys_getcwd(buf as *mut u8, size);
288    if r < 0 { ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
289    if *buf as u8 != b'/' {
290        ERRNO!() = ENOENT;
291        return core::ptr::null_mut();
292    }
293    buf
294}
295
296#[no_mangle]
297pub unsafe extern "C" fn gethostname(name: *mut c_char, len: usize) -> c_int {
298    let r = sys_gethostname(name as *mut u8, len);
299    syscall_ret(r) as c_int
300}
301
302// Linux page size.  This is hardcoded to 4096 on every architecture; that
303// is correct for the CI hosts but not for aarch64, powerpc64le, riscv64 or
304// loongarch64 kernels configured with a larger base page size.  See
305// sysconf(_SC_PAGE_SIZE) for the same value.
306#[no_mangle]
307pub extern "C" fn getpagesize() -> c_int {
308    PAGE as c_int
309}
310
311#[no_mangle]
312pub unsafe extern "C" fn truncate(path: *const c_char, length: i64) -> c_int {
313    let r = sys_truncate(path as *const u8, length);
314    syscall_ret(r) as c_int
315}
316
317#[no_mangle]
318pub unsafe extern "C" fn ftruncate(fd: c_int, length: i64) -> c_int {
319    let r = sys_ftruncate(fd, length);
320    syscall_ret(r) as c_int
321}
322
323#[no_mangle]
324pub unsafe extern "C" fn nanosleep(req: *const timespec, rem: *mut timespec) -> c_int {
325    pthread_testcancel();
326    let r = sys_nanosleep(req, rem);
327    pthread_testcancel();
328    syscall_ret(r) as c_int
329}
330
331#[no_mangle]
332pub unsafe extern "C" fn sleep(seconds: c_uint) -> c_uint {
333    let req = timespec { tv_sec: seconds as c_long, tv_nsec: 0 };
334    let mut rem: timespec = core::mem::zeroed();
335    pthread_testcancel();
336    let r = sys_nanosleep(&req, &mut rem);
337    pthread_testcancel();
338    if r < 0 {
339        let e = (-r) as c_int;
340        if e == EINTR { return rem.tv_sec as c_uint; }
341    }
342    0
343}
344
345#[no_mangle]
346pub unsafe extern "C" fn usleep(usec: c_uint) -> c_int {
347    let req = timespec { tv_sec: (usec / 1000000) as c_long, tv_nsec: ((usec % 1000000) * 1000) as c_long };
348    pthread_testcancel();
349    let r = sys_nanosleep(&req, core::ptr::null_mut());
350    pthread_testcancel();
351    syscall_ret(r) as c_int
352}
353
354#[no_mangle]
355pub unsafe extern "C" fn alarm(seconds: c_uint) -> c_uint {
356    // POSIX rounds a nonzero fractional remainder up to one second;
357    // sys_alarm() already performs that rounding.
358    let r = sys_alarm(seconds);
359    if r < 0 { 0 } else { r as c_uint }
360}
361
362#[no_mangle]
363pub unsafe extern "C" fn pause() -> c_int {
364    pthread_testcancel();
365    sys_pause();
366    pthread_testcancel();
367    ERRNO!() = EINTR;
368    -1
369}
370
371#[no_mangle]
372pub unsafe extern "C" fn fsync(fd: c_int) -> c_int {
373    let r = sys_fsync(fd);
374    syscall_ret(r) as c_int
375}
376
377#[no_mangle]
378pub unsafe extern "C" fn fdatasync(fd: c_int) -> c_int {
379    let r = sys_fdatasync(fd);
380    syscall_ret(r) as c_int
381}
382
383#[no_mangle]
384pub unsafe extern "C" fn sync() {
385    sys_sync();
386}
387
388#[no_mangle]
389pub unsafe extern "C" fn symlink(target: *const c_char, linkpath: *const c_char) -> c_int {
390    let r = sys_symlinkat(target as *const u8, AT_FDCWD, linkpath as *const u8);
391    syscall_ret(r) as c_int
392}
393
394#[no_mangle]
395pub unsafe extern "C" fn readlink(path: *const c_char, buf: *mut c_char, bufsiz: usize) -> isize {
396    let r = sys_readlinkat(AT_FDCWD, path as *const u8, buf as *mut u8, bufsiz);
397    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
398    r as isize
399}
400
401#[no_mangle]
402pub unsafe extern "C" fn link(oldpath: *const c_char, newpath: *const c_char) -> c_int {
403    let r = sys_linkat(AT_FDCWD, oldpath as *const u8, AT_FDCWD, newpath as *const u8, 0);
404    syscall_ret(r) as c_int
405}
406
407#[no_mangle]
408pub unsafe extern "C" fn chmod(path: *const c_char, mode: c_uint) -> c_int {
409    let r = sys_fchmodat(AT_FDCWD, path as *const u8, mode, 0);
410    syscall_ret(r) as c_int
411}
412
413#[no_mangle]
414pub unsafe extern "C" fn fchmod(fd: c_int, mode: c_uint) -> c_int {
415    let r = sys_fchmod(fd, mode);
416    syscall_ret(r) as c_int
417}
418
419#[no_mangle]
420pub unsafe extern "C" fn umask(mask: c_uint) -> c_uint {
421    sys_umask(mask) as c_uint
422}
423
424#[no_mangle]
425pub unsafe extern "C" fn isatty(fd: c_int) -> c_int {
426    let mut ws: winsize = core::mem::zeroed();
427    if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 { 1 } else { 0 }
428}
429
430#[no_mangle]
431pub unsafe extern "C" fn getlogin() -> *mut c_char {
432    crate::getenv(b"LOGNAME\0".as_ptr() as *const c_char)
433}
434
435#[no_mangle]
436pub unsafe extern "C" fn getgroups(size: c_int, list: *mut c_uint) -> c_int {
437    let r = sys_getgroups(size, list);
438    syscall_ret(r) as c_int
439}
440
441#[no_mangle]
442pub unsafe extern "C" fn setuid(uid: c_uint) -> c_int {
443    let r = sys_setuid(uid);
444    syscall_ret(r) as c_int
445}
446
447#[no_mangle]
448pub unsafe extern "C" fn setgid(gid: c_uint) -> c_int {
449    let r = sys_setgid(gid);
450    syscall_ret(r) as c_int
451}
452
453#[no_mangle]
454pub unsafe extern "C" fn seteuid(euid: c_uint) -> c_int {
455    // Setting only the effective uid must keep the real and saved uids, so a
456    // process can drop privileges and later restore them (setuid would clear
457    // the saved uid for root).
458    setresuid(u32::MAX, euid, u32::MAX)
459}
460
461#[no_mangle]
462pub unsafe extern "C" fn setegid(egid: c_uint) -> c_int {
463    setresgid(u32::MAX, egid, u32::MAX)
464}
465
466#[no_mangle]
467pub unsafe extern "C" fn setreuid(ruid: c_uint, euid: c_uint) -> c_int {
468    let r = <Arch as Syscalls>::syscall2(SYS_SETREUID, ruid as i64, euid as i64);
469    syscall_ret(r) as c_int
470}
471
472
473
474#[no_mangle]
475pub unsafe extern "C" fn setsid() -> c_int {
476    let r = sys_setsid();
477    syscall_ret(r) as c_int
478}
479
480#[no_mangle]
481pub unsafe extern "C" fn setpgid(pid: c_int, pgid: c_int) -> c_int {
482    let r = sys_setpgid(pid, pgid);
483    syscall_ret(r) as c_int
484}
485
486#[no_mangle]
487pub unsafe extern "C" fn getpgid(pid: c_int) -> c_int {
488    let r = sys_getpgid(pid);
489    syscall_ret(r) as c_int
490}
491
492#[no_mangle]
493pub unsafe extern "C" fn getsid(pid: c_int) -> c_int {
494    let r = sys_getsid(pid);
495    syscall_ret(r) as c_int
496}
497
498#[no_mangle]
499pub unsafe extern "C" fn getpgrp() -> c_int {
500    sys_getpgid(0) as c_int
501}
502
503#[no_mangle]
504pub unsafe extern "C" fn setpgrp() -> c_int {
505    setpgid(0, 0)
506}
507
508#[no_mangle]
509unsafe fn mkstemps_impl(template: *mut c_char, suffixlen: i32) -> c_int {
510    mkstemps_flags(template, suffixlen, 0)
511}
512
513unsafe fn mkstemps_flags(template: *mut c_char, suffixlen: i32, flags: i32) -> c_int {
514    if template.is_null() || suffixlen < 0 {
515        ERRNO!() = EINVAL;
516        return -1;
517    }
518    let len = strlen(template as *const c_char);
519    let suffix = suffixlen as usize;
520    if len < 6 + suffix {
521        ERRNO!() = EINVAL;
522        return -1;
523    }
524    let x_start = len - suffix - 6;
525    for i in x_start..x_start + 6 {
526        if *template.add(i) != b'X' as c_char {
527            ERRNO!() = EINVAL;
528            return -1;
529        }
530    }
531    let mut ts: timespec = core::mem::zeroed();
532    let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
533    let mut ctr: u32 = ts.tv_nsec as u32;
534    for _ in 0..100 {
535        ctr = ctr.wrapping_mul(1103515245).wrapping_add(12345);
536        let mut seed = ctr;
537        let hex = b"0123456789abcdef";
538        for i in x_start..x_start + 6 {
539            *template.add(i) = hex[(seed & 0xf) as usize] as c_char;
540            seed >>= 4;
541        }
542        let fd = sys_open(template as *const u8, (O_RDWR | O_CREAT | O_EXCL | flags) as i64, 0o600);
543        if fd >= 0 {
544            return fd as c_int;
545        }
546        let e = (-fd) as c_int;
547        if e != EEXIST {
548            ERRNO!() = e;
549            return -1;
550        }
551    }
552    ERRNO!() = EEXIST;
553    -1
554}
555
556#[no_mangle]
557pub unsafe extern "C" fn mkstemp(template: *mut c_char) -> c_int {
558    mkstemps_impl(template, 0)
559}
560
561#[no_mangle]
562pub unsafe extern "C" fn mkdir(path: *const c_char, mode: c_uint) -> c_int {
563    let r = sys_mkdirat(AT_FDCWD, path as *const u8, mode);
564    syscall_ret(r) as c_int
565}
566