Skip to main content

c/
compat_misc.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// Misc functions
6// ============================================================
7
8#[no_mangle]
9pub unsafe extern "C" fn __assert_fail(expr: *const core::ffi::c_char, file: *const core::ffi::c_char, line: u32, func: *const core::ffi::c_char) {
10    crate::write(2, b"Assertion failed: ".as_ptr() as *const core::ffi::c_void, 18);
11    if !expr.is_null() { crate::write(2, expr as *const core::ffi::c_void, crate::strlen(expr)); }
12    crate::write(2, b" (".as_ptr() as *const core::ffi::c_void, 2);
13    if !file.is_null() { crate::write(2, file as *const core::ffi::c_void, crate::strlen(file)); }
14    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
15    let mut n = line as usize;
16    let mut digits: [u8; 32] = [0; 32];
17    let mut di = 0;
18    if n == 0 { digits[0] = 0; di = 1; }
19    while n > 0 && di < 32 { digits[di] = (n % 10) as u8; n /= 10; di += 1; }
20    while di > 0 { di -= 1; let c = (b'0' + digits[di]) as c_char; crate::write(2, &c as *const c_char as *const core::ffi::c_void, 1); }
21    crate::write(2, b")".as_ptr() as *const core::ffi::c_void, 1);
22    if !func.is_null() { crate::write(2, func as *const core::ffi::c_void, crate::strlen(func)); }
23    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
24    crate::abort()
25}
26
27const QUICK_EXIT_MAX: usize = 32;
28static mut QUICK_EXIT_FNS: [Option<unsafe extern "C" fn()>; QUICK_EXIT_MAX] =
29    [None; QUICK_EXIT_MAX];
30static mut QUICK_EXIT_COUNT: usize = 0;
31
32#[no_mangle]
33pub unsafe extern "C" fn at_quick_exit(func: Option<unsafe extern "C" fn()>) -> i32 {
34    let Some(func) = func else { return -1; };
35    if QUICK_EXIT_COUNT >= QUICK_EXIT_MAX {
36        return -1;
37    }
38    QUICK_EXIT_FNS[QUICK_EXIT_COUNT] = Some(func);
39    QUICK_EXIT_COUNT += 1;
40    0
41}
42
43#[no_mangle]
44pub unsafe extern "C" fn brk(addr: *mut u8) -> i32 {
45    syscall_ret(<Arch as Syscalls>::syscall1(SYS_BRK, addr as i64)) as i32
46}
47
48#[no_mangle]
49pub unsafe extern "C" fn copy_file_range(fd_in: i32, off_in: *mut i64, fd_out: i32, off_out: *mut i64, len: usize, flags: u32) -> isize {
50    syscall_ret(<Arch as Syscalls>::syscall6(SYS_COPY_FILE_RANGE, fd_in as i64, off_in as i64, fd_out as i64, off_out as i64, len as i64, flags as i64)) as isize
51}
52
53#[no_mangle]
54pub unsafe extern "C" fn ctermid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
55    static mut BUF: [core::ffi::c_char; 20] = [0; 20];
56    let dst = if s.is_null() { BUF.as_mut_ptr() } else { s };
57    let src = b"/dev/tty\0".as_ptr() as *const core::ffi::c_char;
58    let mut i = 0;
59    while i < 9 { *dst.add(i) = *src.add(i); i += 1; }
60    dst
61}
62
63#[no_mangle]
64pub unsafe extern "C" fn delete_module(name: *const core::ffi::c_char, flags: u32) -> i32 {
65    syscall_ret(<Arch as Syscalls>::syscall2(SYS_DELETE_MODULE, name as i64, flags as i64)) as i32
66}
67
68
69
70
71
72#[no_mangle]
73pub unsafe extern "C" fn __duplocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
74    loc
75}
76
77#[no_mangle]
78pub unsafe extern "C" fn euidaccess(pathname: *const core::ffi::c_char, mode: i32) -> i32 {
79    faccessat(AT_FDCWD, pathname, mode, AT_EACCESS)
80}
81
82#[no_mangle]
83pub unsafe extern "C" fn fgetln(f: *mut core::ffi::c_void, lenp: *mut usize) -> *mut core::ffi::c_char {
84    static mut BUF: *mut core::ffi::c_char = core::ptr::null_mut();
85    static mut CAP: usize = 0;
86    let n = getline(&raw mut BUF, &raw mut CAP, f as *mut FILE);
87    if n <= 0 {
88        if !lenp.is_null() { *lenp = 0; }
89        return core::ptr::null_mut();
90    }
91    if !lenp.is_null() { *lenp = n as usize; }
92    BUF
93}
94
95#[no_mangle]
96pub unsafe extern "C" fn fgetws(ws: *mut u32, n: i32, f: *mut core::ffi::c_void) -> *mut u32 {
97    let mut i = 0;
98    while i < n - 1 {
99        let c = getwc(f as *mut core::ffi::c_void);
100        if c == 0 { break; }
101        *ws.add(i as usize) = c;
102        i += 1;
103        if c == '\n' as u32 { break; }
104    }
105    *ws.add(i as usize) = 0;
106    if i == 0 { core::ptr::null_mut() } else { ws }
107}
108
109#[no_mangle]
110pub unsafe extern "C" fn fmtmsg(_classification: i64, label: *const core::ffi::c_char, _severity: i32, text: *const core::ffi::c_char, _action: *const core::ffi::c_char, _tag: *const core::ffi::c_char) -> i32 {
111    if !label.is_null() { crate::write(2, label as *const core::ffi::c_void, crate::strlen(label)); }
112    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
113    if !text.is_null() { crate::write(2, text as *const core::ffi::c_void, crate::strlen(text)); }
114    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
115    0
116}
117
118#[no_mangle]
119pub unsafe extern "C" fn ftime(tp: *mut core::ffi::c_void) -> i32 {
120    let mut tv: timeval = core::mem::zeroed();
121    if gettimeofday(&mut tv, core::ptr::null_mut()) == 0 {
122        let tb = tp as *mut Timeb;
123        (*tb).time = tv.tv_sec;
124        (*tb).millitm = (tv.tv_usec / 1000) as u16;
125        (*tb).timezone = 0;
126        (*tb).dstflag = 0;
127        0
128    } else {
129        -1
130    }
131}
132
133#[no_mangle]
134pub unsafe extern "C" fn getdents(fd: i32, dirp: *mut u8, count: usize) -> isize {
135    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, dirp as i64, count as i64)) as isize
136}
137
138#[no_mangle]
139pub unsafe extern "C" fn gethostid() -> i64 {
140    // Read from /proc/sys/kernel/random/boot_id or similar
141    let fd = crate::open(b"/proc/sys/kernel/random/boot_id\0".as_ptr() as *const core::ffi::c_char, 0, 0);
142    if fd < 0 { return 0; }
143    let mut buf: [u8; 64] = [0; 64];
144    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
145    crate::close(fd);
146    if n <= 0 { return 0; }
147    buf[n as usize] = 0;
148    crate::strtol(buf.as_ptr() as *const core::ffi::c_char, core::ptr::null_mut(), 16)
149}
150
151#[repr(C)]
152#[derive(Copy, Clone)]
153struct TermiosBuf {
154    c_iflag: u32,
155    c_oflag: u32,
156    c_cflag: u32,
157    c_lflag: u32,
158    c_line: u8,
159    c_cc: [u8; 32],
160    c_ispeed: u32,
161    c_ospeed: u32,
162}
163
164#[no_mangle]
165pub unsafe extern "C" fn getpass(prompt: *const core::ffi::c_char) -> *mut core::ffi::c_char {
166    static mut BUF: [core::ffi::c_char; 256] = [0; 256];
167    if prompt.is_null() { return core::ptr::null_mut(); }
168    const O_NOCTTY_V: i32 = 0x100;
169    const ECHO_V: u32 = 0o10;
170    const ISIG_V: u32 = 0o1;
171    const ICANON_V: u32 = 0o2;
172    const INLCR_V: u32 = 0o100;
173    const IGNCR_V: u32 = 0o200;
174    const ICRNL_V: u32 = 0o400;
175    const TCSAFLUSH_V: i32 = 2;
176
177    let fd = crate::open(
178        b"/dev/tty\0".as_ptr() as *const core::ffi::c_char,
179        O_RDWR | O_NOCTTY_V | O_CLOEXEC,
180        0,
181    );
182    if fd < 0 { return core::ptr::null_mut(); }
183    let mut t: TermiosBuf = core::mem::zeroed();
184    if tcgetattr(fd, &mut t as *mut TermiosBuf as *mut core::ffi::c_void) < 0 {
185        crate::close(fd);
186        return core::ptr::null_mut();
187    }
188    let old = t;
189    t.c_lflag &= !(ECHO_V | ISIG_V);
190    t.c_lflag |= ICANON_V;
191    t.c_iflag &= !(INLCR_V | IGNCR_V);
192    t.c_iflag |= ICRNL_V;
193    tcsetattr(fd, TCSAFLUSH_V, &t as *const TermiosBuf as *const core::ffi::c_void);
194    tcdrain(fd);
195    dprintf(fd, b"%s\0".as_ptr() as *const core::ffi::c_char, prompt);
196    let n = crate::read(fd, BUF.as_mut_ptr() as *mut core::ffi::c_void, BUF.len() - 1);
197    let ok = n >= 0;
198    if ok {
199        let mut len = n as usize;
200        if (len > 0 && BUF[len - 1] == b'\n' as core::ffi::c_char) || len == BUF.len() - 1 {
201            len -= 1;
202        }
203        BUF[len] = 0;
204    }
205    tcsetattr(fd, TCSAFLUSH_V, &old as *const TermiosBuf as *const core::ffi::c_void);
206    dprintf(fd, b"\n\0".as_ptr() as *const core::ffi::c_char);
207    crate::close(fd);
208    if ok { BUF.as_mut_ptr() } else { core::ptr::null_mut() }
209}
210
211#[no_mangle]
212pub unsafe extern "C" fn getsubopt(optionp: *mut *mut core::ffi::c_char, tokens: *const *const core::ffi::c_char, valuep: *mut *mut core::ffi::c_char) -> i32 {
213    let s = *optionp;
214    if s.is_null() { return -1; }
215    // Find end of suboption
216    let mut end = s;
217    while *end != 0 && *end != ',' as c_char && *end != '=' as c_char { end = end.add(1); }
218    let eq = *end == '=' as c_char;
219    if eq { *end = 0; *valuep = end.add(1); }
220    // Find matching token
221    let mut i = 0;
222    loop {
223        let tok = *tokens.add(i);
224        if tok.is_null() { break; }
225        if crate::strcmp(s as *const u8, tok as *const u8) == 0 {
226            // Skip to next option
227    while *end != 0 && *end != ',' as c_char { end = end.add(1); }
228            if *end == ',' as c_char { end = end.add(1); }
229            *optionp = end;
230            return i as i32;
231        }
232        i += 1;
233    }
234    -1
235}
236
237#[no_mangle]
238pub unsafe extern "C" fn getw(f: *mut core::ffi::c_void) -> i32 {
239    let c0 = getc(f as *mut FILE);
240    if c0 < 0 { return -1; }
241    let c1 = getc(f as *mut FILE);
242    if c1 < 0 { return -1; }
243    let c2 = getc(f as *mut FILE);
244    if c2 < 0 { return -1; }
245    let c3 = getc(f as *mut FILE);
246    if c3 < 0 { return -1; }
247    (c0 | (c1 << 8) | (c2 << 16) | (c3 << 24)) as i32
248}
249
250#[no_mangle]
251pub unsafe extern "C" fn getwc(f: *mut core::ffi::c_void) -> u32 {
252    getc(f as *mut FILE) as u32
253}
254
255#[no_mangle]
256pub unsafe extern "C" fn init_module(module_image: *mut u8, len: usize, param_values: *const core::ffi::c_char) -> i32 {
257    syscall_ret(<Arch as Syscalls>::syscall3(SYS_INIT_MODULE, module_image as i64, len as i64, param_values as i64)) as i32
258}
259
260
261
262#[no_mangle]
263pub unsafe extern "C" fn issetugid() -> i32 {
264    let ruid = crate::getuid();
265    let euid = crate::geteuid();
266    let rgid = crate::getgid();
267    let egid = crate::getegid();
268    (ruid != euid || rgid != egid) as i32
269}
270
271// ============================================================
272// poll functions
273// ============================================================
274
275#[repr(C)]
276struct PollTimespec {
277    tv_sec: i64,
278    tv_nsec: i64,
279}
280
281#[no_mangle]
282pub unsafe extern "C" fn poll(fds: *mut core::ffi::c_void, nfds: u32, timeout: i32) -> i32 {
283    #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64"))]
284    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_POLL, fds as i64, nfds as i64, timeout as i64)) as i32 }
285    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64", target_arch = "loongarch64"))]
286    {
287        // poll(2) does not exist on these architectures.  ppoll(2) takes a
288        // struct timespec, not a millisecond count; passing the integer
289        // directly made poll(..., 0) wait forever.
290        let mut ts = PollTimespec { tv_sec: 0, tv_nsec: 0 };
291        let ts_ptr = if timeout < 0 {
292            core::ptr::null()
293        } else {
294            ts.tv_sec = (timeout / 1000) as i64;
295            ts.tv_nsec = ((timeout % 1000) as i64) * 1_000_000;
296            &ts as *const PollTimespec as *const core::ffi::c_void
297        };
298        syscall_ret(<Arch as Syscalls>::syscall5(
299            SYS_PPOLL,
300            fds as i64,
301            nfds as i64,
302            ts_ptr as i64,
303            0,
304            8,
305        )) as i32
306    }
307}
308
309#[no_mangle]
310pub unsafe extern "C" fn ppoll(fds: *mut core::ffi::c_void, nfds: u32, timeout: *const core::ffi::c_void, sigmask: *const u64) -> i32 {
311    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PPOLL, fds as i64, nfds as i64, timeout as i64, sigmask as i64, 8)) as i32
312}
313
314#[repr(C)]
315struct PselectSigmask {
316    ss: *const u64,
317    ss_len: usize,
318}
319
320#[no_mangle]
321pub unsafe extern "C" fn pselect(nfds: i32, readfds: *mut u8, writefds: *mut u8, exceptfds: *mut u8, timeout: *const core::ffi::c_void, sigmask: *const u64) -> i32 {
322    // pselect6 takes a { sigset_t *, size_t } pair, not the sigset pointer.
323    // GNU make blocks SIGCHLD and depends on this temporary mask, so passing
324    // the pointer directly deadlocks parallel builds.
325    let arg = PselectSigmask {
326        ss: sigmask,
327        ss_len: core::mem::size_of::<SigSetT>(),
328    };
329    let arg_ptr = if sigmask.is_null() {
330        0
331    } else {
332        &arg as *const PselectSigmask as i64
333    };
334    syscall_ret(<Arch as Syscalls>::syscall6(SYS_PSELECT6, nfds as i64, readfds as i64, writefds as i64, exceptfds as i64, timeout as i64, arg_ptr)) as i32
335}
336
337// ============================================================
338// realpath function
339// ============================================================
340
341// ============================================================
342// quick_exit function
343// ============================================================
344
345#[no_mangle]
346pub unsafe extern "C" fn quick_exit(status: i32) -> ! {
347    // Run handlers in reverse registration order, like atexit.
348    while QUICK_EXIT_COUNT > 0 {
349        QUICK_EXIT_COUNT -= 1;
350        if let Some(func) = QUICK_EXIT_FNS[QUICK_EXIT_COUNT] {
351            func();
352        }
353    }
354    crate::_exit(status)
355}
356
357// ============================================================
358// stat functions
359// ============================================================
360
361#[no_mangle]
362pub unsafe extern "C" fn lstat(path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
363    let r = <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, buf as i64, AT_SYMLINK_NOFOLLOW as i64);
364    syscall_ret(r) as c_int
365}
366
367#[no_mangle]
368pub unsafe extern "C" fn __xstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
369    crate::stat(path, buf as *mut Stat)
370}
371
372#[no_mangle]
373pub unsafe extern "C" fn __lxstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
374    crate::lstat(path, buf)
375}
376
377#[no_mangle]
378pub unsafe extern "C" fn __fxstat(_ver: i32, fd: i32, buf: *mut core::ffi::c_void) -> i32 {
379    crate::fstat(fd, buf as *mut Stat)
380}
381
382#[no_mangle]
383pub unsafe extern "C" fn __fxstatat(_ver: i32, dirfd: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void, flags: i32) -> i32 {
384    crate::fstatat(dirfd, path, buf as *mut Stat, flags)
385}
386
387// ============================================================
388// mempcpy function
389// ============================================================
390
391#[no_mangle]
392pub unsafe extern "C" fn mempcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8 {
393    core::ptr::copy_nonoverlapping(src, dest, n);
394    dest.add(n)
395}
396
397// ============================================================
398// mktemp functions
399// ============================================================
400
401#[no_mangle]
402pub unsafe extern "C" fn mkostemp(template: *mut core::ffi::c_char, flags: i32) -> i32 {
403    mkstemps_flags(template, 0, flags)
404}
405
406#[no_mangle]
407pub unsafe extern "C" fn mkstemps(template: *mut core::ffi::c_char, suffixlen: i32) -> i32 {
408    mkstemps_impl(template, suffixlen)
409}
410
411// ============================================================
412// system functions
413// ============================================================
414
415const PTRACE_PEEKTEXT: i32 = 1;
416const PTRACE_PEEKDATA: i32 = 2;
417const PTRACE_PEEKUSER: i32 = 3;
418
419#[no_mangle]
420pub unsafe extern "C" fn ptrace(request: i32, mut args: ...) -> i64 {
421    let pid = args.next_arg::<c_long>();
422    let addr = args.next_arg::<c_long>();
423    let data = args.next_arg::<c_long>();
424    // PEEKTEXT/PEEKDATA/PEEKUSER write the result through the data pointer
425    // (the kernel returns EFAULT for a NULL pointer), so supply a local slot.
426    if (PTRACE_PEEKTEXT..=PTRACE_PEEKUSER).contains(&request) {
427        let mut result: c_long = 0;
428        let r = <Arch as Syscalls>::syscall4(
429            SYS_PTRACE,
430            request as i64,
431            pid,
432            addr,
433            &mut result as *mut c_long as i64,
434        );
435        if r < 0 {
436            ERRNO!() = (-r) as c_int;
437            return -1;
438        }
439        return result;
440    }
441    syscall_ret(<Arch as Syscalls>::syscall4(SYS_PTRACE, request as i64, pid, addr, data))
442}
443
444#[no_mangle]
445pub unsafe extern "C" fn personality(persona: u64) -> i64 {
446    <Arch as Syscalls>::syscall1(SYS_PERSONALITY, persona as i64)
447}
448
449const LINUX_REBOOT_MAGIC1: i64 = 0xfee1dead;
450const LINUX_REBOOT_MAGIC2: i64 = 0x28121969;
451
452#[no_mangle]
453pub unsafe extern "C" fn reboot(cmd: c_int) -> i32 {
454    // musl's public API is reboot(cmd), not the four-argument syscall.
455    syscall_ret(<Arch as Syscalls>::syscall3(
456        SYS_REBOOT,
457        LINUX_REBOOT_MAGIC1,
458        LINUX_REBOOT_MAGIC2,
459        cmd as i64,
460    )) as i32
461}
462
463#[no_mangle]
464pub unsafe extern "C" fn pivot_root(new_root: *const core::ffi::c_char, put_old: *const core::ffi::c_char) -> i32 {
465    syscall_ret(<Arch as Syscalls>::syscall2(SYS_PIVOT_ROOT, new_root as i64, put_old as i64)) as i32
466}
467
468#[no_mangle]
469pub unsafe extern "C" fn mount(source: *const core::ffi::c_char, target: *const core::ffi::c_char, filesystemtype: *const core::ffi::c_char, mountflags: u64, data: *const core::ffi::c_void) -> i32 {
470    syscall_ret(<Arch as Syscalls>::syscall5(SYS_MOUNT, source as i64, target as i64, filesystemtype as i64, mountflags as i64, data as i64)) as i32
471}
472
473#[no_mangle]
474pub unsafe extern "C" fn umount(target: *const core::ffi::c_char) -> i32 {
475    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, 0)) as i32
476}
477
478#[no_mangle]
479pub unsafe extern "C" fn umount2(target: *const core::ffi::c_char, flags: i32) -> i32 {
480    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, flags as i64)) as i32
481}
482
483// ============================================================
484// resolver functions
485// ============================================================
486
487
488// ============================================================
489// signal/error functions
490// ============================================================
491
492#[no_mangle]
493pub unsafe extern "C" fn psiginfo(_pinfo: *const core::ffi::c_void, s: *const core::ffi::c_char) {
494    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
495    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
496}
497
498#[no_mangle]
499pub unsafe extern "C" fn psignal(sig: i32, s: *const core::ffi::c_char) {
500    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
501    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
502    let msg = strsignal(sig);
503    crate::write(2, msg as *const core::ffi::c_void, crate::strlen(msg));
504    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
505}
506
507#[no_mangle]
508pub unsafe extern "C" fn strsignal(sig: c_int) -> *const c_char {
509    static NAMES: [&[u8]; 32] = [
510        b"Unknown signal\0",
511        b"Hangup\0",
512        b"Interrupt\0",
513        b"Quit\0",
514        b"Illegal instruction\0",
515        b"Trace/breakpoint trap\0",
516        b"Aborted\0",
517        b"Bus error\0",
518        b"Floating point exception\0",
519        b"Killed\0",
520        b"User defined signal 1\0",
521        b"Segmentation fault\0",
522        b"User defined signal 2\0",
523        b"Broken pipe\0",
524        b"Alarm clock\0",
525        b"Terminated\0",
526        b"Stack fault\0",
527        b"Child process status\0",
528        b"Continued\0",
529        b"Stopped (signal)\0",
530        b"Stopped\0",
531        b"Stopped (tty input)\0",
532        b"Stopped (tty output)\0",
533        b"Urgent I/O condition\0",
534        b"CPU time limit exceeded\0",
535        b"File size limit exceeded\0",
536        b"Virtual timer expired\0",
537        b"Profiling timer expired\0",
538        b"Window changed\0",
539        b"I/O possible\0",
540        b"Power failure\0",
541        b"Bad system call\0",
542    ];
543    static mut RT_BUF: [c_char; 32] = [0; 32];
544    if sig > 0 && sig < 32 {
545        return NAMES[sig as usize].as_ptr() as *const c_char;
546    }
547    if sig >= 32 && sig < 65 {
548        let mut o = 0usize;
549        for &c in b"Real-time signal \0" {
550            if c == 0 { break; }
551            RT_BUF[o] = c as c_char;
552            o += 1;
553        }
554        let mut v = (sig - 32) as u32;
555        let mut digits = [0u8; 10];
556        let mut d = 0usize;
557        if v == 0 { digits[0] = b'0'; d = 1; }
558        while v > 0 { digits[d] = b'0' + (v % 10) as u8; v /= 10; d += 1; }
559        while d > 0 { d -= 1; RT_BUF[o] = digits[d] as c_char; o += 1; }
560        RT_BUF[o] = 0;
561        return RT_BUF.as_ptr();
562    }
563    b"Unknown signal\0".as_ptr() as *const c_char
564}
565
566#[no_mangle]
567pub unsafe extern "C" fn __strerror_l(errnum: i32, _loc: *mut core::ffi::c_void) -> *const core::ffi::c_char {
568    crate::strerror(errnum)
569}
570
571// ============================================================
572// preadv functions
573// ============================================================
574
575#[no_mangle]
576pub unsafe extern "C" fn preadv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
577    // preadv takes a 64-bit offset split into pos_l/pos_h on x86_64 and the
578    // generic ABI; passing only pos_l leaves the high half undefined.
579    syscall_ret(<Arch as Syscalls>::syscall5(
580        SYS_PREADV,
581        fd as i64,
582        iov as i64,
583        iovcnt as i64,
584        offset,
585        offset >> 32,
586    )) as isize
587}
588
589#[no_mangle]
590pub unsafe extern "C" fn pwritev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
591    syscall_ret(<Arch as Syscalls>::syscall5(
592        SYS_PWRITEV,
593        fd as i64,
594        iov as i64,
595        iovcnt as i64,
596        offset,
597        offset >> 32,
598    )) as isize
599}
600
601#[no_mangle]
602pub unsafe extern "C" fn preadv2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
603    // x86_64/generic preadv2 split the 64-bit offset into pos_l/pos_h and
604    // take the flags as the sixth argument.
605    syscall_ret(<Arch as Syscalls>::syscall6(
606        SYS_PREADV2,
607        fd as i64,
608        iov as i64,
609        iovcnt as i64,
610        offset,
611        offset >> 32,
612        flags as i64,
613    )) as isize
614}
615
616#[no_mangle]
617pub unsafe extern "C" fn pwritev2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
618    syscall_ret(<Arch as Syscalls>::syscall6(
619        SYS_PWRITEV2,
620        fd as i64,
621        iov as i64,
622        iovcnt as i64,
623        offset,
624        offset >> 32,
625        flags as i64,
626    )) as isize
627}
628
629// ============================================================
630// nice function
631// ============================================================
632
633#[no_mangle]
634pub unsafe extern "C" fn nice(inc: i32) -> i32 {
635    let mut prio = inc;
636    if inc > -40 && inc < 40 {
637        prio += getpriority(0, 0);
638    }
639    if prio > 19 { prio = 19; }
640    if prio < -20 { prio = -20; }
641    if setpriority(0, 0, prio) != 0 {
642        if ERRNO!() == EACCES { ERRNO!() = EPERM; } // EACCES -> EPERM, as musl does
643        return -1;
644    }
645    prio
646}
647
648// ============================================================
649// misc functions
650// ============================================================
651
652const A64L_DIGITS: &[u8; 64] =
653    b"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
654
655#[no_mangle]
656pub unsafe extern "C" fn l64a(value: i64) -> *mut core::ffi::c_char {
657    static mut BUF: [core::ffi::c_char; 7] = [0; 7];
658    let mut v = value as u32;
659    let mut i = 0;
660    while v > 0 && i < 6 {
661        BUF[i] = A64L_DIGITS[(v & 0x3f) as usize] as core::ffi::c_char;
662        v >>= 6;
663        i += 1;
664    }
665    BUF[i] = 0;
666    BUF.as_mut_ptr()
667}
668
669#[no_mangle]
670pub unsafe extern "C" fn a64l(s: *const core::ffi::c_char) -> i64 {
671    let mut x: u32 = 0;
672    let mut e = 0u32;
673    while e < 36 {
674        let c = *s.add((e / 6) as usize) as u8;
675        if c == 0 { break; }
676        let d = match A64L_DIGITS.iter().position(|&d| d == c) {
677            Some(d) => d as u32,
678            None => break,
679        };
680        x |= d << e;
681        e += 6;
682    }
683    x as i32 as i64
684}
685
686#[no_mangle]
687pub unsafe extern "C" fn lchmod(path: *const core::ffi::c_char, mode: u32) -> i32 {
688    fchmodat(AT_FDCWD, path, mode, AT_SYMLINK_NOFOLLOW)
689}
690
691#[no_mangle]
692pub unsafe extern "C" fn lutimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
693    utimensat(AT_FDCWD, filename, times as *const timespec, AT_SYMLINK_NOFOLLOW)
694}
695
696#[no_mangle]
697pub unsafe extern "C" fn mknod(pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
698    #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64"))]
699    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKNOD, pathname as i64, mode as i64, dev as i64)) as i32 }
700    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64", target_arch = "loongarch64"))]
701    {
702        syscall_ret(<Arch as Syscalls>::syscall4(SYS_MKNODAT, AT_FDCWD as i64, pathname as i64, mode as i64, dev as i64)) as i32
703    }
704}
705
706#[no_mangle]
707pub unsafe extern "C" fn memfd_create(name: *const core::ffi::c_char, flags: u32) -> i32 {
708    syscall_ret(<Arch as Syscalls>::syscall2(SYS_MEMFD_CREATE, name as i64, flags as i64)) as i32
709}
710
711#[no_mangle]
712pub unsafe extern "C" fn mlock2(addr: *const core::ffi::c_void, len: usize, flags: u32) -> i32 {
713    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MLOCK2, addr as i64, len as i64, flags as i64)) as i32
714}
715
716
717
718#[no_mangle]
719pub unsafe extern "C" fn remap_file_pages(addr: *mut core::ffi::c_void, size: usize, prot: i32, pgoff: usize, flags: u32) -> i32 {
720    syscall_ret(<Arch as Syscalls>::syscall5(SYS_REMAP_FILE_PAGES, addr as i64, size as i64, prot as i64, pgoff as i64, flags as i64)) as i32
721}
722
723include!("compat_symbols.rs");
724// ============================================================
725// Final missing symbols
726// ============================================================
727
728
729
730#[no_mangle]
731pub unsafe extern "C" fn strtod_l(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, _loc: *mut core::ffi::c_void) -> f64 {
732    crate::strtod(nptr, endptr)
733}
734
735#[no_mangle]
736pub unsafe extern "C" fn strtof_l(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, _loc: *mut core::ffi::c_void) -> f32 {
737    crate::strtof(nptr, endptr)
738}
739
740#[cfg(not(target_arch = "x86_64"))]
741#[no_mangle]
742pub unsafe extern "C" fn strtold_l(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, _loc: *mut core::ffi::c_void) -> f128 {
743    f64_to_f128(crate::strtod(nptr, endptr))
744}
745
746// ============================================================
747// Directory operations - real implementations
748// ============================================================
749
750#[repr(C)]
751struct linux_dirent64 {
752    d_ino: u64,
753    d_off: i64,
754    d_reclen: u16,
755    d_type: u8,
756    d_name: [u8; 0], // flexible array
757}
758
759// Directory streams used to be a process-wide singleton, which broke any
760// nested opendir/readdir sequence (git, find, glob, ...). Each DIR now owns
761// its fd and read buffer, like musl's __dirstream.
762const DIR_BUF_SIZE: usize = 4096;
763
764#[repr(C)]
765struct DirStream {
766    fd: i32,
767    pos: usize,
768    len: usize,
769    last_off: i64,
770    buf: [u8; DIR_BUF_SIZE],
771}
772
773unsafe fn dir_stream_new(fd: i32) -> *mut core::ffi::c_void {
774    let ds = malloc(core::mem::size_of::<DirStream>()) as *mut DirStream;
775    if ds.is_null() {
776        crate::close(fd);
777        ERRNO!() = ENOMEM;
778        return core::ptr::null_mut();
779    }
780    core::ptr::write_bytes(ds, 0, 1);
781    (*ds).fd = fd;
782    ds as *mut core::ffi::c_void
783}
784
785#[no_mangle]
786pub unsafe extern "C" fn opendir(dirname: *const core::ffi::c_char) -> *mut core::ffi::c_void {
787    let fd = openat(AT_FDCWD, dirname, O_DIRECTORY, 0); // O_RDONLY | O_DIRECTORY
788    if fd < 0 { return core::ptr::null_mut(); }
789    dir_stream_new(fd)
790}
791
792#[no_mangle]
793pub unsafe extern "C" fn closedir(dirp: *mut core::ffi::c_void) -> i32 {
794    if dirp.is_null() { ERRNO!() = EINVAL; return -1; }
795    let ds = dirp as *mut DirStream;
796    let r = crate::close((*ds).fd);
797    free(dirp);
798    r
799}
800
801#[no_mangle]
802pub unsafe extern "C" fn readdir(dirp: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
803    if dirp.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
804    let ds = &mut *(dirp as *mut DirStream);
805
806    loop {
807        if ds.pos >= ds.len {
808            let nread = syscall_ret(<Arch as Syscalls>::syscall3(
809                SYS_GETDENTS64,
810                ds.fd as i64,
811                ds.buf.as_mut_ptr() as i64,
812                DIR_BUF_SIZE as i64,
813            )) as isize;
814            if nread <= 0 { return core::ptr::null_mut(); }
815            ds.len = nread as usize;
816            ds.pos = 0;
817        }
818
819        let ent = ds.buf.as_ptr().add(ds.pos) as *const linux_dirent64;
820        let ent_ref = &*ent;
821        if ent_ref.d_reclen as usize == 0 {
822            ds.len = 0;
823            return core::ptr::null_mut();
824        }
825        ds.pos += ent_ref.d_reclen as usize;
826        ds.last_off = ent_ref.d_off;
827
828        // Return a pointer into this stream's buffer (valid until next call).
829        return ent as *mut core::ffi::c_void;
830    }
831}
832
833#[repr(C)]
834struct DirentCopy {
835    d_ino: u64,
836    d_off: i64,
837    d_reclen: u16,
838    d_type: u8,
839    d_name: [core::ffi::c_char; 256],
840}
841
842#[no_mangle]
843pub unsafe extern "C" fn readdir_r(dirp: *mut core::ffi::c_void, entry: *mut core::ffi::c_void, result: *mut *mut core::ffi::c_void) -> i32 {
844    if dirp.is_null() || entry.is_null() || result.is_null() {
845        return EINVAL;
846    }
847    let ent = readdir(dirp);
848    if ent.is_null() {
849        *result = core::ptr::null_mut();
850        return 0;
851    }
852    let reclen = (* (ent as *const linux_dirent64)).d_reclen as usize;
853    let copy = reclen.min(core::mem::size_of::<DirentCopy>());
854    core::ptr::copy_nonoverlapping(ent as *const u8, entry as *mut u8, copy);
855    *result = entry;
856    0
857}
858
859#[no_mangle]
860pub unsafe extern "C" fn seekdir(dirp: *mut core::ffi::c_void, loc: i64) {
861    if dirp.is_null() { return; }
862    let ds = &mut *(dirp as *mut DirStream);
863    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, loc, 0);
864    ds.pos = 0;
865    ds.len = 0;
866}
867
868#[no_mangle]
869pub unsafe extern "C" fn telldir(dirp: *mut core::ffi::c_void) -> i64 {
870    if dirp.is_null() { return -1; }
871    (*(dirp as *mut DirStream)).last_off
872}
873
874#[no_mangle]
875pub unsafe extern "C" fn rewinddir(dirp: *mut core::ffi::c_void) {
876    if dirp.is_null() { return; }
877    let ds = &mut *(dirp as *mut DirStream);
878    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, 0, 0);
879    ds.pos = 0;
880    ds.len = 0;
881    ds.last_off = 0;
882}
883
884#[no_mangle]
885pub unsafe extern "C" fn dirfd(dirp: *mut core::ffi::c_void) -> i32 {
886    if dirp.is_null() { ERRNO!() = EINVAL; return -1; }
887    (*(dirp as *mut DirStream)).fd
888}
889
890// ============================================================
891// Memory management - real implementations
892// ============================================================
893
894#[no_mangle]
895pub unsafe extern "C" fn mprotect(addr: *mut u8, len: usize, prot: i32) -> i32 {
896    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MPROTECT, addr as i64, len as i64, prot as i64)) as i32
897}
898
899#[no_mangle]
900pub unsafe extern "C" fn msync(addr: *mut u8, len: usize, flags: i32) -> i32 {
901    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MSYNC, addr as i64, len as i64, flags as i64)) as i32
902}
903
904#[no_mangle]
905pub unsafe extern "C" fn mlock(addr: *const u8, len: usize) -> i32 {
906    syscall_ret(<Arch as Syscalls>::syscall2(SYS_MLOCK, addr as i64, len as i64)) as i32
907}
908
909#[no_mangle]
910pub unsafe extern "C" fn munlock(addr: *const u8, len: usize) -> i32 {
911    syscall_ret(<Arch as Syscalls>::syscall2(SYS_MUNLOCK, addr as i64, len as i64)) as i32
912}
913
914#[no_mangle]
915pub unsafe extern "C" fn mlockall(flags: i32) -> i32 {
916    syscall_ret(<Arch as Syscalls>::syscall1(SYS_MLOCKALL, flags as i64)) as i32
917}
918
919#[no_mangle]
920pub unsafe extern "C" fn munlockall() -> i32 {
921    syscall_ret(<Arch as Syscalls>::syscall0(SYS_MUNLOCKALL)) as i32
922}
923
924#[no_mangle]
925pub unsafe extern "C" fn madvise(addr: *mut u8, len: usize, advice: i32) -> i32 {
926    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MADVISE, addr as i64, len as i64, advice as i64)) as i32
927}
928
929#[no_mangle]
930pub unsafe extern "C" fn mincore(addr: *mut u8, len: usize, vec: *mut u8) -> i32 {
931    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MINCORE, addr as i64, len as i64, vec as i64)) as i32
932}
933
934// ============================================================
935
936include!("compat_abi.rs");
937include!("resolver.rs");
938include!("legacy_compat.rs");
939include!("shadow.rs");