Skip to main content

c/
lib.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4#![cfg_attr(not(test), no_std)]
5#![feature(c_variadic)]
6#![feature(linkage)]
7#![cfg_attr(target_arch = "aarch64", feature(f128))]
8#![cfg_attr(target_arch = "riscv64", feature(f128))]
9#![allow(dead_code, non_camel_case_types)]
10// A libc necessarily keeps mutable global state (stdio tables, passwd/group
11// buffers, resolver state).  References to it are deliberate and confined to
12// the C ABI entry points.
13#![allow(static_mut_refs)]
14// C `_Complex` values are passed as two floating-point registers on every
15// supported target; Rust tuples use the same SysV/AAPCS classification.
16#![allow(improper_ctypes_definitions)]
17
18use core::ffi::{c_char, c_int, c_long, c_longlong, c_uint, c_ulong, c_ulonglong, c_void, VaList};
19use core::ptr::null_mut;
20use core::sync::atomic::{AtomicI32, AtomicPtr, AtomicUsize, Ordering};
21
22macro_rules! ERRNO {
23    () => { *errno_ptr() };
24}
25
26include!("encoding_tables.rs");
27include!("math_helpers.rs");
28include!("math_bitmanip.rs");
29include!("math_sqrtfmod.rs");
30include!("math_trig.rs");
31include!("math_exp.rs");
32include!("math_erf.rs");
33include!("math_lgamma.rs");
34include!("math_tgamma.rs");
35include!("math_bessel.rs");
36include!("alloc.rs");
37include!("math_log.rs");
38include!("math_pow.rs");
39include!("math_hypot.rs");
40include!("math_hyperbolic.rs");
41include!("math_invtrig.rs");
42include!("math_lrint.rs");
43include!("math_long_double.rs");
44include!("string_fast.rs");
45include!("vdso.rs");
46include!("arch.rs");
47
48// ============================================================
49// errno
50// ============================================================
51
52const EILSEQ: c_int = 84;
53const EINVAL: c_int = 22;
54const EFAULT: c_int = 14;
55const E2BIG: c_int = 7;
56
57const LC_CTYPE: c_int = 0;
58const LC_NUMERIC: c_int = 1;
59const LC_TIME: c_int = 2;
60const LC_COLLATE: c_int = 3;
61const LC_MONETARY: c_int = 4;
62const LC_MESSAGES: c_int = 5;
63const LC_ALL: c_int = 6;
64const ENOMEM: c_int = 12;
65const EINTR: c_int = 4;
66const EPERM: c_int = 1;
67const EAGAIN: c_int = 11;
68const EBUSY: c_int = 16;
69const EDEADLK: c_int = 35;
70const ETIMEDOUT: c_int = 110;
71const ECANCELED: c_int = 125;
72const EOVERFLOW: c_int = 75;
73const EOWNERDEAD: c_int = 130;
74const ENOTRECOVERABLE: c_int = 131;
75
76// Static executables have no dynamic loader to build a TCB, so they keep the
77// traditional process-global errno. Dynamic programs store it in the TCB, just
78// below the thread pointer. The offset is inside the 256-byte TCB that
79// libldso.so allocates for every thread (0x00 self pointer, 0x08 generation,
80// 0x28 stack canary).
81static mut ERRNO_FALLBACK: c_int = 0;
82static ERRNO_TLS_ACTIVE: AtomicUsize = AtomicUsize::new(0);
83const ERRNO_TCB_OFFSET: usize = 0x30;
84
85#[inline]
86unsafe fn errno_ptr() -> *mut c_int {
87    if ERRNO_TLS_ACTIVE.load(Ordering::Relaxed) == 0 {
88        return core::ptr::addr_of_mut!(ERRNO_FALLBACK);
89    }
90    #[cfg(target_arch = "x86_64")]
91    let tp: usize = {
92        let tp: usize;
93        core::arch::asm!("mov {}, fs:[0]", out(reg) tp, options(nostack, preserves_flags));
94        tp
95    };
96    #[cfg(target_arch = "aarch64")]
97    let tp: usize = {
98        let tp: usize;
99        core::arch::asm!("mrs {}, tpidr_el0", out(reg) tp, options(nostack, preserves_flags));
100        tp
101    };
102    #[cfg(target_arch = "riscv64")]
103    let tp: usize = {
104        let tp: usize;
105        core::arch::asm!("mv {}, tp", out(reg) tp, options(nostack, preserves_flags));
106        tp
107    };
108    #[cfg(target_arch = "x86_64")]
109    let tcb = tp;
110    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
111    let tcb = tp - 256;
112    (tcb + ERRNO_TCB_OFFSET) as *mut c_int
113}
114
115/// Called once from __libc_start_main. The dynamic loader has already set up
116/// a TCB for dynamic programs; static programs leave %fs / TP at zero.
117unsafe fn errno_init() {
118    let tp = arch_get_tp();
119    #[cfg(target_arch = "x86_64")]
120    let tcb = tp;
121    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
122    let tcb = tp.wrapping_sub(256);
123    if tp != 0 && core::ptr::read(tcb as *const usize) == tcb {
124        ERRNO_TLS_ACTIVE.store(1, Ordering::Relaxed);
125    }
126}
127
128/// Normalize a raw syscall result the way musl's `__syscall_ret` does:
129/// turn `-errno` into `-1` and publish the error through `errno`.
130#[inline]
131unsafe fn syscall_ret(r: i64) -> i64 {
132    if r < 0 {
133        *errno_ptr() = (-r) as c_int;
134        -1
135    } else {
136        r
137    }
138}
139
140#[no_mangle]
141pub unsafe extern "C" fn __errno_location() -> *mut c_int {
142    errno_ptr()
143}
144
145#[cfg(not(test))]
146#[panic_handler]
147fn panic(_: &core::panic::PanicInfo) -> ! {
148    loop {}
149}
150
151// Required by the Rust runtime; panic=abort never unwinds.
152#[cfg(not(test))]
153#[no_mangle]
154pub extern "C" fn rust_eh_personality() {}
155
156// ============================================================
157// Constants
158// ============================================================
159
160const PROT_READ: i32 = 1;
161const PROT_WRITE: i32 = 2;
162const MAP_SHARED: i32 = 0x01;
163const MAP_PRIVATE: i32 = 0x02;
164const MAP_ANONYMOUS: i32 = 0x20;
165
166// ============================================================
167// Syscall wrappers (raw, no_std)
168// ============================================================
169
170#[inline]
171unsafe fn sys_write(fd: i64, buf: *const u8, count: usize) -> i64 {
172    <Arch as Syscalls>::syscall3(SYS_WRITE, fd as i64, buf as i64, count as i64)
173}
174
175#[inline]
176unsafe fn sys_read(fd: i64, buf: *mut u8, count: usize) -> i64 {
177    <Arch as Syscalls>::syscall3(SYS_READ, fd as i64, buf as i64, count as i64)
178}
179
180#[inline]
181unsafe fn sys_open(path: *const u8, flags: i64, mode: i64) -> i64 {
182    <Arch as Syscalls>::syscall4(SYS_OPENAT, AT_FDCWD as i64, path as i64, flags as i64, mode as i64)
183}
184
185#[inline]
186unsafe fn sys_close(fd: i64) -> i64 {
187    <Arch as Syscalls>::syscall1(SYS_CLOSE, fd as i64)
188}
189
190#[inline]
191unsafe fn sys_lseek(fd: i64, offset: i64, whence: i64) -> i64 {
192    <Arch as Syscalls>::syscall3(SYS_LSEEK, fd as i64, offset as i64, whence as i64)
193}
194
195unsafe fn sys_mmap(
196    addr: *mut u8,
197    length: usize,
198    prot: i32,
199    flags: i32,
200    fd: i32,
201    offset: i64,
202) -> *mut u8 {
203    let result = <Arch as Syscalls>::syscall6(SYS_MMAP, addr as i64, length as i64, prot as i64, flags as i64, fd as i64, offset);
204    if result < 0 && result > -4096 {
205        ERRNO!() = (-result) as c_int;
206        return MMAP_FAILED;
207    }
208    result as *mut u8
209}
210
211unsafe fn sys_munmap(addr: *mut u8, length: usize) -> i64 {
212    <Arch as Syscalls>::syscall2(SYS_MUNMAP, addr as i64, length as i64)
213}
214
215// ============================================================
216// String/memory functions
217// ============================================================
218
219// strlen, memcpy, memset, memmove and memcmp live in string_fast.rs.
220
221#[no_mangle]
222pub unsafe extern "C" fn bcmp(s1: *const c_void, s2: *const c_void, n: usize) -> c_int {
223    memcmp(s1, s2, n)
224}
225
226// strcmp lives in string_fast.rs.
227
228#[no_mangle]
229pub unsafe extern "C" fn strncmp(s1: *const u8, s2: *const u8, n: usize) -> c_int {
230    let mut i = 0;
231    while i < n {
232        let a = *s1.add(i);
233        let b = *s2.add(i);
234        if a != b {
235            return a as c_int - b as c_int;
236        }
237        if a == 0 {
238            return 0;
239        }
240        i += 1;
241    }
242    0
243}
244
245#[no_mangle]
246pub unsafe extern "C" fn strcpy(dst: *mut u8, src: *const u8) -> *mut u8 {
247    let mut i = 0;
248    loop {
249        let c = *src.add(i);
250        *dst.add(i) = c;
251        if c == 0 {
252            break;
253        }
254        i += 1;
255    }
256    dst
257}
258
259#[no_mangle]
260pub unsafe extern "C" fn strncpy(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 {
261    let mut i = 0;
262    while i < n && *src.add(i) != 0 {
263        *dst.add(i) = *src.add(i);
264        i += 1;
265    }
266    while i < n {
267        *dst.add(i) = 0;
268        i += 1;
269    }
270    dst
271}
272
273#[no_mangle]
274pub unsafe extern "C" fn strcat(dst: *mut u8, src: *const u8) -> *mut u8 {
275    let mut i = 0;
276    while *dst.add(i) != 0 {
277        i += 1;
278    }
279    let mut j = 0;
280    loop {
281        let c = *src.add(j);
282        *dst.add(i + j) = c;
283        if c == 0 {
284            break;
285        }
286        j += 1;
287    }
288    dst
289}
290
291#[no_mangle]
292pub unsafe extern "C" fn strncat(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 {
293    let mut i = 0;
294    while *dst.add(i) != 0 {
295        i += 1;
296    }
297    let mut j = 0;
298    while j < n && *src.add(j) != 0 {
299        *dst.add(i + j) = *src.add(j);
300        j += 1;
301    }
302    *dst.add(i + j) = 0;
303    dst
304}
305
306#[no_mangle]
307pub unsafe extern "C" fn strlcpy(dst: *mut u8, src: *const u8, n: usize) -> usize {
308    let l = strlen(src as *const c_char);
309    if n > 0 {
310        let c = if l < n { l } else { n - 1 };
311        core::ptr::copy_nonoverlapping(src, dst, c);
312        *dst.add(c) = 0;
313    }
314    l
315}
316
317#[no_mangle]
318pub unsafe extern "C" fn strlcat(dst: *mut u8, src: *const u8, n: usize) -> usize {
319    let dl = strlen(dst as *const c_char);
320    let sl = strlen(src as *const c_char);
321    if dl >= n { return n + sl; }
322    let c = if sl < n - dl { sl } else { n - dl - 1 };
323    core::ptr::copy_nonoverlapping(src, dst.add(dl), c);
324    *dst.add(dl + c) = 0;
325    dl + sl
326}
327
328#[no_mangle]
329pub unsafe extern "C" fn bcopy(src: *const c_void, dst: *mut c_void, n: usize) {
330    core::ptr::copy(src as *const u8, dst as *mut u8, n);
331}
332
333#[no_mangle]
334pub unsafe extern "C" fn bzero(s: *mut c_void, n: usize) {
335    core::ptr::write_bytes(s as *mut u8, 0, n);
336}
337
338#[no_mangle]
339pub unsafe extern "C" fn strndup(s: *const c_char, n: usize) -> *mut c_char {
340    let mut len = 0;
341    while len < n && *s.add(len) != 0 {
342        len += 1;
343    }
344    let p = malloc(len + 1) as *mut c_char;
345    if p.is_null() {
346        return core::ptr::null_mut();
347    }
348    core::ptr::copy_nonoverlapping(s, p, len);
349    *p.add(len) = 0;
350    p
351}
352
353#[no_mangle]
354pub unsafe extern "C" fn strchr(s: *const u8, c: c_int) -> *mut u8 {
355    let target = c as u8;
356    let mut i = 0;
357    loop {
358        let ch = *s.add(i);
359        if ch == target {
360            return s.add(i) as *mut u8;
361        }
362        if ch == 0 {
363            return null_mut();
364        }
365        i += 1;
366    }
367}
368
369#[no_mangle]
370pub unsafe extern "C" fn strrchr(s: *const u8, c: c_int) -> *mut u8 {
371    let target = c as u8;
372    let mut i = 0;
373    let mut last: *mut u8 = null_mut();
374    loop {
375        let ch = *s.add(i);
376        if ch == target {
377            last = s.add(i) as *mut u8;
378        }
379        if ch == 0 {
380            return last;
381        }
382        i += 1;
383    }
384}
385
386#[no_mangle]
387pub unsafe extern "C" fn strnlen(s: *const u8, maxlen: usize) -> usize {
388    let mut i = 0;
389    while i < maxlen && *s.add(i) != 0 {
390        i += 1;
391    }
392    i
393}
394
395#[no_mangle]
396pub unsafe extern "C" fn strcspn(s: *const u8, reject: *const u8) -> usize {
397    let mut i = 0;
398    loop {
399        let c = *s.add(i);
400        if c == 0 {
401            return i;
402        }
403        let mut j = 0;
404        loop {
405            let r = *reject.add(j);
406            if r == 0 {
407                break;
408            }
409            if c == r {
410                return i;
411            }
412            j += 1;
413        }
414        i += 1;
415    }
416}
417
418#[no_mangle]
419pub unsafe extern "C" fn strspn(s: *const u8, accept: *const u8) -> usize {
420    let mut i = 0;
421    loop {
422        let c = *s.add(i);
423        if c == 0 {
424            return i;
425        }
426        let mut found = false;
427        let mut j = 0;
428        loop {
429            let a = *accept.add(j);
430            if a == 0 {
431                break;
432            }
433            if c == a {
434                found = true;
435                break;
436            }
437            j += 1;
438        }
439        if !found {
440            return i;
441        }
442        i += 1;
443    }
444}
445
446#[no_mangle]
447pub unsafe extern "C" fn strpbrk(s: *const u8, accept: *const u8) -> *mut u8 {
448    let mut i = 0;
449    loop {
450        let c = *s.add(i);
451        if c == 0 {
452            return null_mut();
453        }
454        let mut j = 0;
455        loop {
456            let a = *accept.add(j);
457            if a == 0 {
458                break;
459            }
460            if c == a {
461                return s.add(i) as *mut u8;
462            }
463            j += 1;
464        }
465        i += 1;
466    }
467}
468
469#[no_mangle]
470pub unsafe extern "C" fn strstr(haystack: *const u8, needle: *const u8) -> *mut u8 {
471    if *needle == 0 {
472        return haystack as *mut u8;
473    }
474    let mut i = 0;
475    loop {
476        let h = *haystack.add(i);
477        if h == 0 {
478            return null_mut();
479        }
480        if h == *needle {
481            let mut j = 0;
482            loop {
483                let n = *needle.add(j);
484                if n == 0 {
485                    return haystack.add(i) as *mut u8;
486                }
487                if *haystack.add(i + j) != n {
488                    break;
489                }
490                j += 1;
491            }
492        }
493        i += 1;
494    }
495}
496
497#[no_mangle]
498pub unsafe extern "C" fn memchr(s: *const u8, c: c_int, n: usize) -> *mut u8 {
499    let target = c as u8;
500    let mut i = 0;
501    while i < n {
502        if *s.add(i) == target {
503            return s.add(i) as *mut u8;
504        }
505        i += 1;
506    }
507    null_mut()
508}
509
510#[no_mangle]
511pub unsafe extern "C" fn memrchr(s: *const u8, c: c_int, n: usize) -> *mut u8 {
512    let target = c as u8;
513    let mut i = n;
514    while i > 0 {
515        i -= 1;
516        if *s.add(i) == target {
517            return s.add(i) as *mut u8;
518        }
519    }
520    null_mut()
521}
522
523#[no_mangle]
524pub unsafe extern "C" fn memmem(
525    haystack: *const c_void, haystacklen: usize,
526    needle: *const c_void, needlelen: usize,
527) -> *mut c_void {
528    if needlelen == 0 { return haystack as *mut c_void; }
529    if haystacklen < needlelen { return null_mut(); }
530    let h = haystack as *const u8;
531    let n = needle as *const u8;
532    let last = haystacklen - needlelen;
533    for i in 0..=last {
534        if *h.add(i) == *n && memcmp(h.add(i) as *const c_void, n as *const c_void, needlelen) == 0 {
535            return h.add(i) as *mut c_void;
536        }
537    }
538    null_mut()
539}
540
541#[no_mangle]
542pub unsafe extern "C" fn strtok(s: *mut u8, delim: *const u8) -> *mut u8 {
543    static mut STATE: *mut u8 = core::ptr::null_mut();
544    let mut p = if s.is_null() { STATE } else { s };
545    if p.is_null() {
546        return core::ptr::null_mut();
547    }
548    loop {
549        let c = *p;
550        if c == 0 {
551            STATE = core::ptr::null_mut();
552            return core::ptr::null_mut();
553        }
554        let mut is_delim = false;
555        let mut i = 0;
556        loop {
557            let d = *delim.add(i);
558            if d == 0 {
559                break;
560            }
561            if c == d {
562                is_delim = true;
563                break;
564            }
565            i += 1;
566        }
567        if !is_delim {
568            break;
569        }
570        p = p.add(1);
571    }
572    let start = p;
573    loop {
574        let c = *p;
575        if c == 0 {
576            STATE = core::ptr::null_mut();
577            return start;
578        }
579        let mut is_delim = false;
580        let mut i = 0;
581        loop {
582            let d = *delim.add(i);
583            if d == 0 {
584                break;
585            }
586            if c == d {
587                is_delim = true;
588                break;
589            }
590            i += 1;
591        }
592        if is_delim {
593            *p = 0;
594            STATE = p.add(1);
595            return start;
596        }
597        p = p.add(1);
598    }
599}
600
601// ============================================================
602// C type aliases
603// ============================================================
604
605type SizeT = usize;
606type SSizeT = isize;
607type mode_t = c_uint;
608type TimeT = c_long;
609type ClockT = c_long;
610type wchar_t = c_int;
611type wint_t = c_uint;
612type wctype_t = *const c_int;
613type wctrans_t = *const c_int;
614
615const WEOF: wint_t = 0xffffffff;
616
617#[repr(C)]
618pub struct tm {
619    pub tm_sec: c_int,
620    pub tm_min: c_int,
621    pub tm_hour: c_int,
622    pub tm_mday: c_int,
623    pub tm_mon: c_int,
624    pub tm_year: c_int,
625    pub tm_wday: c_int,
626    pub tm_yday: c_int,
627    pub tm_isdst: c_int,
628    pub tm_gmtoff: c_long,
629    pub tm_zone: *const c_char,
630}
631
632#[repr(C)]
633pub struct timeval {
634    pub tv_sec: TimeT,
635    pub tv_usec: c_long,
636}
637
638#[repr(C)]
639pub struct Timeb {
640    pub time: TimeT,
641    pub millitm: u16,
642    pub timezone: i16,
643    pub dstflag: u16,
644}
645
646// ============================================================
647// ctype.h
648// ============================================================
649
650const CT_UPPER: u8 = 1 << 0;
651const CT_LOWER: u8 = 1 << 1;
652const CT_DIGIT: u8 = 1 << 2;
653const CT_SPACE: u8 = 1 << 3;
654const CT_PUNCT: u8 = 1 << 4;
655const CT_CNTRL: u8 = 1 << 5;
656const CT_BLANK: u8 = 1 << 6;
657const CT_XDIGIT: u8 = 1 << 7;
658
659const CT_TABLE: [u8; 128] = {
660    let mut t = [0u8; 128];
661    let mut i = 0;
662    while i < 128 {
663        let c = i as u8;
664        let mut flags = 0u8;
665        if c >= b'A' && c <= b'Z' {
666            flags |= CT_UPPER;
667        }
668        if c >= b'a' && c <= b'z' {
669            flags |= CT_LOWER;
670        }
671        if c >= b'0' && c <= b'9' {
672            flags |= CT_DIGIT;
673        }
674        if c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == b'\x0c' || c == b'\x0b' {
675            flags |= CT_SPACE;
676        }
677        if (c >= b'!' && c <= b'/')
678            || (c >= b':' && c <= b'@')
679            || (c >= b'[' && c <= b'`')
680            || (c >= b'{' && c <= b'~')
681        {
682            flags |= CT_PUNCT;
683        }
684        if c < 0x20 || c == 0x7f {
685            flags |= CT_CNTRL;
686        }
687        if c == b' ' || c == b'\t' {
688            flags |= CT_BLANK;
689        }
690        if (c >= b'0' && c <= b'9') || (c >= b'A' && c <= b'F') || (c >= b'a' && c <= b'f') {
691            flags |= CT_XDIGIT;
692        }
693        t[i] = flags;
694        i += 1;
695    }
696    t
697};
698
699#[inline]
700fn ct_flags(c: c_int) -> u8 {
701    if c < 0 || c > 127 {
702        0
703    } else {
704        CT_TABLE[c as usize]
705    }
706}
707
708#[no_mangle]
709pub extern "C" fn isalnum(c: c_int) -> c_int {
710    (ct_flags(c) & (CT_UPPER | CT_LOWER | CT_DIGIT) != 0) as c_int
711}
712
713#[no_mangle]
714pub extern "C" fn isalpha(c: c_int) -> c_int {
715    (ct_flags(c) & (CT_UPPER | CT_LOWER) != 0) as c_int
716}
717
718#[no_mangle]
719pub extern "C" fn isascii(c: c_int) -> c_int {
720    ((c as u32) <= 127) as c_int
721}
722
723#[no_mangle]
724pub extern "C" fn isblank(c: c_int) -> c_int {
725    (ct_flags(c) & CT_BLANK != 0) as c_int
726}
727
728#[no_mangle]
729pub extern "C" fn iscntrl(c: c_int) -> c_int {
730    (ct_flags(c) & CT_CNTRL != 0) as c_int
731}
732
733#[no_mangle]
734pub extern "C" fn isdigit(c: c_int) -> c_int {
735    (ct_flags(c) & CT_DIGIT != 0) as c_int
736}
737
738#[no_mangle]
739pub extern "C" fn isgraph(c: c_int) -> c_int {
740    (ct_flags(c) & (CT_UPPER | CT_LOWER | CT_DIGIT | CT_PUNCT) != 0) as c_int
741}
742
743#[no_mangle]
744pub extern "C" fn islower(c: c_int) -> c_int {
745    (ct_flags(c) & CT_LOWER != 0) as c_int
746}
747
748#[no_mangle]
749pub extern "C" fn isprint(c: c_int) -> c_int {
750    let flags = ct_flags(c);
751    (flags & (CT_UPPER | CT_LOWER | CT_DIGIT | CT_PUNCT | CT_BLANK) != 0) as c_int
752}
753
754#[no_mangle]
755pub extern "C" fn ispunct(c: c_int) -> c_int {
756    (ct_flags(c) & CT_PUNCT != 0) as c_int
757}
758
759#[no_mangle]
760pub extern "C" fn isspace(c: c_int) -> c_int {
761    (ct_flags(c) & CT_SPACE != 0) as c_int
762}
763
764#[no_mangle]
765pub extern "C" fn isupper(c: c_int) -> c_int {
766    (ct_flags(c) & CT_UPPER != 0) as c_int
767}
768
769#[no_mangle]
770pub extern "C" fn isxdigit(c: c_int) -> c_int {
771    (ct_flags(c) & CT_XDIGIT != 0) as c_int
772}
773
774#[no_mangle]
775pub extern "C" fn tolower(c: c_int) -> c_int {
776    if (ct_flags(c) & CT_UPPER) != 0 {
777        c + (b'a' as c_int - b'A' as c_int)
778    } else {
779        c
780    }
781}
782
783#[no_mangle]
784pub extern "C" fn toupper(c: c_int) -> c_int {
785    if (ct_flags(c) & CT_LOWER) != 0 {
786        c - (b'a' as c_int - b'A' as c_int)
787    } else {
788        c
789    }
790}
791
792// ============================================================
793// stdlib.h: integer conversion, abs, rand
794// ============================================================
795
796unsafe fn parse_digit(c: u8, base: c_int) -> Option<u8> {
797    if c == 0 { return None; }
798    let d = if c >= b'0' && c <= b'9' {
799        c - b'0'
800    } else if c >= b'a' && c <= b'z' {
801        c - b'a' + 10
802    } else if c >= b'A' && c <= b'Z' {
803        c - b'A' + 10
804    } else {
805        return None;
806    };
807    if (d as c_int) < base {
808        Some(d)
809    } else {
810        None
811    }
812}
813
814unsafe fn parse_prefix(s: *const u8, base: *mut c_int) -> *const u8 {
815    let mut p = s;
816    if *base == 0 {
817        if *p == b'0' {
818            if (*p.add(1) == b'x' || *p.add(1) == b'X') && parse_digit(*p.add(2), 16).is_some() {
819                *base = 16;
820                p = p.add(2);
821            } else {
822                *base = 8;
823            }
824        } else {
825            *base = 10;
826        }
827    } else if *base == 16 {
828        if *p == b'0' && (*p.add(1) == b'x' || *p.add(1) == b'X') && parse_digit(*p.add(2), 16).is_some() {
829            p = p.add(2);
830        }
831    }
832    p
833}
834
835unsafe fn strtox(
836    s: *const c_char,
837    endptr: *mut *mut c_char,
838    mut base: c_int,
839    pos_limit: u64,
840    neg_limit: u64,
841) -> (u64, bool, bool) {
842    let s0 = s as *const u8;
843    let mut p = s0;
844    while isspace(*p as c_int) != 0 {
845        p = p.add(1);
846    }
847
848    if base < 0 || base == 1 || base > 36 {
849        if !endptr.is_null() {
850            *endptr = s as *mut c_char;
851        }
852        ERRNO!() = EINVAL;
853        return (0, false, false);
854    }
855
856    let mut neg = false;
857    match *p {
858        b'-' => { neg = true; p = p.add(1); }
859        b'+' => p = p.add(1),
860        _ => {}
861    }
862
863    p = parse_prefix(p, &mut base);
864
865    let limit = if neg { neg_limit } else { pos_limit };
866    let mut val: u64 = 0;
867    let mut any = false;
868    while let Some(d) = parse_digit(*p, base) {
869        any = true;
870        if val > (limit - d as u64) / base as u64 {
871            while parse_digit(*p, base).is_some() { p = p.add(1); }
872            if !endptr.is_null() { *endptr = p as *mut c_char; }
873            ERRNO!() = ERANGE_VAL;
874            return (limit, true, neg);
875        }
876        val = val * base as u64 + d as u64;
877        p = p.add(1);
878    }
879
880    if !endptr.is_null() {
881        *endptr = if any { p as *mut c_char } else { s as *mut c_char };
882    }
883    (val, false, neg)
884}
885
886#[no_mangle]
887pub unsafe extern "C" fn strtol(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_long {
888    let pos_limit = c_long::MAX as u64;
889    let neg_limit = pos_limit.wrapping_add(1);
890    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
891    if overflow {
892        return if neg { c_long::MIN } else { c_long::MAX };
893    }
894    if neg { val.wrapping_neg() as c_long } else { val as c_long }
895}
896
897#[no_mangle]
898pub unsafe extern "C" fn strtoul(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulong {
899    let limit = c_ulong::MAX as u64;
900    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
901    if overflow {
902        return c_ulong::MAX;
903    }
904    if neg { val.wrapping_neg() as c_ulong } else { val as c_ulong }
905}
906
907#[no_mangle]
908pub unsafe extern "C" fn strtoll(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_longlong {
909    let pos_limit = c_longlong::MAX as u64;
910    let neg_limit = pos_limit.wrapping_add(1);
911    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
912    if overflow {
913        return if neg { c_longlong::MIN } else { c_longlong::MAX };
914    }
915    if neg { val.wrapping_neg() as c_longlong } else { val as c_longlong }
916}
917
918#[no_mangle]
919pub unsafe extern "C" fn strtoull(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulonglong {
920    let limit = c_ulonglong::MAX as u64;
921    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
922    if overflow {
923        return c_ulonglong::MAX;
924    }
925    if neg { val.wrapping_neg() as c_ulonglong } else { val as c_ulonglong }
926}
927
928#[no_mangle]
929pub unsafe extern "C" fn atoi(s: *const c_char) -> c_int {
930    strtol(s, core::ptr::null_mut(), 10) as c_int
931}
932
933#[no_mangle]
934pub unsafe extern "C" fn atol(s: *const c_char) -> c_long {
935    strtol(s, core::ptr::null_mut(), 10)
936}
937
938#[no_mangle]
939pub unsafe extern "C" fn atoll(s: *const c_char) -> c_longlong {
940    strtoll(s, core::ptr::null_mut(), 10)
941}
942
943#[no_mangle]
944pub extern "C" fn abs(n: c_int) -> c_int {
945    if n < 0 {
946        -n
947    } else {
948        n
949    }
950}
951
952#[no_mangle]
953pub extern "C" fn labs(n: c_long) -> c_long {
954    if n < 0 {
955        -n
956    } else {
957        n
958    }
959}
960
961#[no_mangle]
962pub extern "C" fn llabs(n: c_longlong) -> c_longlong {
963    if n < 0 {
964        -n
965    } else {
966        n
967    }
968}
969
970static mut RAND_STATE: c_uint = 1;
971
972#[no_mangle]
973pub extern "C" fn srand(seed: c_uint) {
974    unsafe {
975        RAND_STATE = seed;
976    }
977}
978
979#[no_mangle]
980pub extern "C" fn rand() -> c_int {
981    unsafe {
982        RAND_STATE = RAND_STATE.wrapping_mul(1103515245).wrapping_add(12345);
983        ((RAND_STATE >> 16) & 0x7fff) as c_int
984    }
985}
986
987// ============================================================
988// stdlib.h: div, ldiv, lldiv
989// ============================================================
990
991#[repr(C)]
992pub struct div_t { pub quot: c_int, pub rem: c_int }
993#[repr(C)]
994pub struct ldiv_t { pub quot: c_long, pub rem: c_long }
995#[repr(C)]
996pub struct lldiv_t { pub quot: c_longlong, pub rem: c_longlong }
997
998#[no_mangle]
999pub extern "C" fn div(num: c_int, den: c_int) -> div_t {
1000    div_t { quot: num / den, rem: num % den }
1001}
1002
1003#[no_mangle]
1004pub extern "C" fn ldiv(num: c_long, den: c_long) -> ldiv_t {
1005    ldiv_t { quot: num / den, rem: num % den }
1006}
1007
1008#[no_mangle]
1009pub extern "C" fn lldiv(num: c_longlong, den: c_longlong) -> lldiv_t {
1010    lldiv_t { quot: num / den, rem: num % den }
1011}
1012
1013// ============================================================
1014// bsearch
1015// ============================================================
1016
1017type CmpFn = unsafe extern "C" fn(*const c_void, *const c_void) -> c_int;
1018
1019#[no_mangle]
1020pub unsafe extern "C" fn bsearch(
1021    key: *const c_void,
1022    base: *const c_void,
1023    nel: usize,
1024    width: usize,
1025    cmp: CmpFn,
1026) -> *mut c_void {
1027    let mut base = base as *const u8;
1028    let mut nel = nel;
1029    while nel > 0 {
1030        let trial = base.add(width * (nel / 2));
1031        let sign = cmp(key, trial as *const c_void);
1032        if sign < 0 {
1033            nel /= 2;
1034        } else if sign > 0 {
1035            base = trial.add(width);
1036            nel -= nel / 2 + 1;
1037        } else {
1038            return trial as *mut c_void;
1039        }
1040    }
1041    null_mut()
1042}
1043
1044// ============================================================
1045// signal.h
1046// ============================================================
1047
1048pub const SA_RESTORER: c_ulong = 0x04000000;
1049
1050pub const SIG_DFL: usize = 0;
1051pub const SIG_IGN: usize = 1;
1052pub const SIG_ERR: usize = !0usize;
1053
1054pub const SIGHUP: c_int = 1;
1055pub const SIGINT: c_int = 2;
1056pub const SIGQUIT: c_int = 3;
1057pub const SIGILL: c_int = 4;
1058pub const SIGTRAP: c_int = 5;
1059pub const SIGABRT: c_int = 6;
1060pub const SIGIOT: c_int = 6;
1061pub const SIGBUS: c_int = 7;
1062pub const SIGFPE: c_int = 8;
1063pub const SIGKILL: c_int = 9;
1064pub const SIGUSR1: c_int = 10;
1065pub const SIGSEGV: c_int = 11;
1066pub const SIGUSR2: c_int = 12;
1067pub const SIGPIPE: c_int = 13;
1068pub const SIGALRM: c_int = 14;
1069pub const SIGTERM: c_int = 15;
1070pub const SIGSTKFLT: c_int = 16;
1071pub const SIGCHLD: c_int = 17;
1072pub const SIGCONT: c_int = 18;
1073pub const SIGSTOP: c_int = 19;
1074pub const SIGTSTP: c_int = 20;
1075pub const SIGTTIN: c_int = 21;
1076pub const SIGTTOU: c_int = 22;
1077pub const SIGURG: c_int = 23;
1078pub const SIGXCPU: c_int = 24;
1079pub const SIGXFSZ: c_int = 25;
1080pub const SIGVTALRM: c_int = 26;
1081pub const SIGPROF: c_int = 27;
1082pub const SIGWINCH: c_int = 28;
1083pub const SIGIO: c_int = 29;
1084pub const SIGPOLL: c_int = 29;
1085pub const SIGPWR: c_int = 30;
1086pub const SIGSYS: c_int = 31;
1087pub const SIGUNUSED: c_int = 31;
1088pub const _NSIG: c_int = 65;
1089
1090pub const SIG_BLOCK: c_int = 0;
1091pub const SIG_UNBLOCK: c_int = 1;
1092pub const SIG_SETMASK: c_int = 2;
1093
1094pub const SA_NOCLDSTOP: c_ulong = 1;
1095pub const SA_NOCLDWAIT: c_ulong = 2;
1096pub const SA_SIGINFO: c_ulong = 4;
1097pub const SA_ONSTACK: c_ulong = 0x08000000;
1098pub const SA_RESTART: c_ulong = 0x10000000;
1099pub const SA_NODEFER: c_ulong = 0x40000000;
1100pub const SA_RESETHAND: c_ulong = 0x80000000;
1101
1102pub const SS_ONSTACK: c_int = 1;
1103pub const SS_DISABLE: c_int = 2;
1104#[cfg(target_arch = "aarch64")]
1105pub const MINSIGSTKSZ: usize = 6144;
1106#[cfg(target_arch = "aarch64")]
1107pub const SIGSTKSZ: usize = 12288;
1108#[cfg(not(target_arch = "aarch64"))]
1109pub const MINSIGSTKSZ: usize = 2048;
1110#[cfg(not(target_arch = "aarch64"))]
1111pub const SIGSTKSZ: usize = 8192;
1112
1113pub const SI_USER: c_int = 0;
1114pub const SI_TKILL: c_int = -6;
1115
1116#[repr(C)]
1117pub struct timespec {
1118    pub tv_sec: c_long,
1119    pub tv_nsec: c_long,
1120}
1121
1122#[repr(C)]
1123pub struct siginfo_t {
1124    pub si_signo: c_int,
1125    pub si_errno: c_int,
1126    pub si_code: c_int,
1127    // ponytail: rest of 128-byte struct, only si_signo accessed
1128    _pad: [u8; 128 - 3 * core::mem::size_of::<c_int>()],
1129}
1130
1131#[repr(C)]
1132pub struct stack_t {
1133    pub ss_sp: *mut c_void,
1134    pub ss_flags: c_int,
1135    pub ss_size: usize,
1136}
1137
1138// Kernel ABI for rt_sigaction (x86_64/riscv64/aarch64 all use the same
1139// handler/flags/restorer/8-byte-mask layout).
1140#[repr(C)]
1141pub struct KSigAction {
1142    pub sa_handler: usize,
1143    pub sa_flags: c_ulong,
1144    pub sa_restorer: usize,
1145    pub sa_mask: [c_ulong; 1],
1146}
1147
1148// musl's public layout: handler, 128-byte sigset_t, flags, restorer.
1149#[repr(C)]
1150pub struct sigaction {
1151    pub sa_handler: usize,
1152    pub sa_mask: [u64; 16],
1153    pub sa_flags: c_int,
1154    pub sa_restorer: usize,
1155}
1156
1157pub type SigSetT = c_ulong;
1158
1159#[cfg(target_arch = "x86_64")]
1160core::arch::global_asm!(
1161    ".global sig_restorer",
1162    ".type sig_restorer, @function",
1163    "sig_restorer:",
1164    "mov eax, 15",
1165    "syscall",
1166);
1167
1168#[cfg(target_arch = "aarch64")]
1169core::arch::global_asm!(
1170    ".global sig_restorer",
1171    ".type sig_restorer, @function",
1172    "sig_restorer:",
1173    "mov x8, #139",
1174    "svc #0",
1175);
1176
1177#[cfg(target_arch = "riscv64")]
1178core::arch::global_asm!(
1179    ".global sig_restorer",
1180    ".type sig_restorer, @function",
1181    "sig_restorer:",
1182    "li a7, 139",
1183    "ecall",
1184);
1185
1186extern "C" {
1187    fn sig_restorer();
1188}
1189
1190#[inline]
1191unsafe fn sys_rt_sigaction(sig: c_int,
1192    act: *const KSigAction,
1193    oldact: *mut KSigAction,
1194    sigsetsize: usize,) -> i64 {
1195    <Arch as Syscalls>::syscall4(SYS_RT_SIGACTION, sig as i64, act as i64, oldact as i64, sigsetsize as i64)
1196}
1197
1198#[inline]
1199unsafe fn sys_rt_sigprocmask(how: c_int,
1200    set: *const SigSetT,
1201    oldset: *mut SigSetT,
1202    sigsetsize: usize,) -> i64 {
1203    <Arch as Syscalls>::syscall4(SYS_RT_SIGPROCMASK, how as i64, set as i64, oldset as i64, sigsetsize as i64)
1204}
1205
1206#[inline]
1207unsafe fn sys_rt_sigpending(set: *mut SigSetT, sigsetsize: usize) -> i64 {
1208    <Arch as Syscalls>::syscall2(SYS_RT_SIGPENDING, set as i64, sigsetsize as i64)
1209}
1210
1211#[inline]
1212unsafe fn sys_rt_sigsuspend(mask: *const SigSetT, sigsetsize: usize) -> i64 {
1213    <Arch as Syscalls>::syscall2(SYS_RT_SIGSUSPEND, mask as i64, sigsetsize as i64)
1214}
1215
1216#[inline]
1217unsafe fn sys_rt_sigtimedwait(set: *const SigSetT,
1218    info: *mut siginfo_t,
1219    timeout: *const timespec,
1220    sigsetsize: usize,) -> i64 {
1221    <Arch as Syscalls>::syscall4(SYS_RT_SIGTIMEDWAIT, set as i64, info as i64, timeout as i64, sigsetsize as i64)
1222}
1223
1224#[inline]
1225unsafe fn sys_sigaltstack(ss: *const stack_t, old_ss: *mut stack_t) -> i64 {
1226    <Arch as Syscalls>::syscall2(SYS_SIGALTSTACK, ss as i64, old_ss as i64)
1227}
1228
1229#[inline]
1230unsafe fn sys_tgkill(tgid: c_int, tid: c_int, sig: c_int) -> i64 {
1231    <Arch as Syscalls>::syscall3(SYS_TGKILL, tgid as i64, tid as i64, sig as i64)
1232}
1233
1234const CLOCK_REALTIME: c_int = 0;
1235const CLOCK_MONOTONIC: c_int = 1;
1236
1237#[inline]
1238unsafe fn sys_clock_gettime(clockid: c_int, ts: *mut timespec) -> i64 {
1239    <Arch as Syscalls>::syscall2(SYS_CLOCK_GETTIME, clockid as i64, ts as i64)
1240}
1241
1242// clock_gettime lives in vdso.rs: it prefers the kernel's vDSO entry point
1243// and only falls back to sys_clock_gettime() there.
1244
1245#[no_mangle]
1246pub unsafe extern "C" fn sigprocmask(
1247    how: c_int,
1248    set: *const SigSetT,
1249    oldset: *mut SigSetT,
1250) -> c_int {
1251    // ponytail: mask out internal rt signals (32, 33) before touching the kernel
1252    let internal_mask: SigSetT = (1u64 << 31) | (1u64 << 32);
1253    let filtered: SigSetT;
1254    let set_ptr: *const SigSetT = if set.is_null() {
1255        set
1256    } else {
1257        filtered = *set & !internal_mask;
1258        &filtered
1259    };
1260    let r = sys_rt_sigprocmask(how, set_ptr, oldset, core::mem::size_of::<SigSetT>());
1261    if r < 0 {
1262        ERRNO!() = (-r) as c_int;
1263        return -1;
1264    }
1265    if !oldset.is_null() {
1266        *oldset &= !internal_mask;
1267    }
1268    0
1269}
1270
1271#[inline]
1272unsafe fn sys_kill(pid: c_int, sig: c_int) -> i64 {
1273    <Arch as Syscalls>::syscall2(SYS_KILL, pid as i64, sig as i64)
1274}
1275
1276#[inline]
1277unsafe fn sys_getpid() -> i64 {
1278    <Arch as Syscalls>::syscall0(SYS_GETPID)
1279}
1280
1281#[no_mangle]
1282pub unsafe extern "C" fn sigaction(
1283    signum: c_int,
1284    act: *const sigaction,
1285    oldact: *mut sigaction,
1286) -> c_int {
1287    let mut kact: KSigAction = core::mem::zeroed();
1288    let act_ptr = if act.is_null() {
1289        core::ptr::null()
1290    } else {
1291        kact.sa_handler = (*act).sa_handler;
1292        kact.sa_flags = ((*act).sa_flags as c_ulong) | SA_RESTORER;
1293        kact.sa_restorer = if (*act).sa_flags as c_ulong & SA_RESTORER != 0
1294            && (*act).sa_restorer != 0
1295        {
1296            (*act).sa_restorer
1297        } else {
1298            sig_restorer as *const () as usize
1299        };
1300        kact.sa_mask[0] = (*act).sa_mask[0];
1301        &kact
1302    };
1303    let mut kold: KSigAction = core::mem::zeroed();
1304    let old_ptr = if oldact.is_null() { core::ptr::null_mut() } else { &mut kold };
1305    let r = sys_rt_sigaction(signum, act_ptr, old_ptr, 8);
1306    if r < 0 {
1307        ERRNO!() = (-r) as c_int;
1308        return -1;
1309    }
1310    if !oldact.is_null() {
1311        (*oldact).sa_handler = kold.sa_handler;
1312        (*oldact).sa_flags = kold.sa_flags as c_int;
1313        (*oldact).sa_restorer = kold.sa_restorer;
1314        (*oldact).sa_mask = [0; 16];
1315        (*oldact).sa_mask[0] = kold.sa_mask[0];
1316    }
1317    0
1318}
1319
1320#[no_mangle]
1321pub unsafe extern "C" fn signal(signum: c_int, handler: usize) -> usize {
1322    // musl's signal() installs the handler with SA_RESTART, so interrupted
1323    // syscalls (waitpid, read, ...) are restarted automatically.
1324    let act = sigaction {
1325        sa_handler: handler,
1326        sa_mask: [0; 16],
1327        sa_flags: SA_RESTART as c_int,
1328        sa_restorer: 0,
1329    };
1330    let mut old: sigaction = core::mem::zeroed();
1331    if sigaction(signum, &act, &mut old) == -1 {
1332        SIG_ERR
1333    } else {
1334        old.sa_handler
1335    }
1336}
1337
1338#[no_mangle]
1339pub unsafe extern "C" fn kill(pid: c_int, sig: c_int) -> c_int {
1340    let r = sys_kill(pid, sig);
1341    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
1342    0
1343}
1344
1345#[no_mangle]
1346pub unsafe extern "C" fn tgkill(tgid: c_int, tid: c_int, sig: c_int) -> c_int {
1347    let r = sys_tgkill(tgid, tid, sig);
1348    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
1349    0
1350}
1351
1352#[no_mangle]
1353pub unsafe extern "C" fn getpid() -> c_int {
1354    sys_getpid() as c_int
1355}
1356
1357#[no_mangle]
1358pub unsafe extern "C" fn raise(sig: c_int) -> c_int {
1359    let r = sys_tgkill(sys_getpid() as c_int, sys_gettid() as c_int, sig);
1360    if r < 0 {
1361        ERRNO!() = (-r) as c_int;
1362        -1
1363    } else {
1364        0
1365    }
1366}
1367
1368#[no_mangle]
1369pub unsafe extern "C" fn sigemptyset(set: *mut SigSetT) -> c_int {
1370    *set = 0;
1371    0
1372}
1373
1374#[no_mangle]
1375pub unsafe extern "C" fn sigfillset(set: *mut SigSetT) -> c_int {
1376    // musl: all signals except 32 (SIGCANCEL) and 33 (SIGSYNCCALL)
1377    *set = 0xFFFF_FFFC_7FFF_FFFFu64;
1378    0
1379}
1380
1381#[no_mangle]
1382pub unsafe extern "C" fn sigaddset(set: *mut SigSetT, signum: c_int) -> c_int {
1383    let s = (signum as c_uint).wrapping_sub(1);
1384    if s as usize >= 64 {
1385        ERRNO!() = EINVAL;
1386        return -1;
1387    }
1388    // ponytail: internal rt signals (32, 33) cannot be manipulated
1389    if signum >= 32 && signum < __libc_current_sigrtmin() {
1390        return 0;
1391    }
1392    *set |= 1u64 << s;
1393    0
1394}
1395
1396#[no_mangle]
1397pub unsafe extern "C" fn sigdelset(set: *mut SigSetT, signum: c_int) -> c_int {
1398    let s = (signum as c_uint).wrapping_sub(1);
1399    if s as usize >= 64 {
1400        ERRNO!() = EINVAL;
1401        return -1;
1402    }
1403    // ponytail: internal rt signals (32, 33) are never members
1404    if signum >= 32 && signum < __libc_current_sigrtmin() {
1405        return 0;
1406    }
1407    *set &= !(1u64 << s);
1408    0
1409}
1410
1411#[no_mangle]
1412pub unsafe extern "C" fn sigismember(set: *const SigSetT, signum: c_int) -> c_int {
1413    let s = (signum as c_uint).wrapping_sub(1);
1414    if s as usize >= 64 { return 0; }
1415    // ponytail: internal rt signals (32, 33) are never members
1416    if signum >= 32 && signum < __libc_current_sigrtmin() {
1417        return 0;
1418    }
1419    ((*set & (1u64 << s)) != 0) as c_int
1420}
1421
1422#[no_mangle]
1423pub unsafe extern "C" fn sigpending(set: *mut SigSetT) -> c_int {
1424    let r = sys_rt_sigpending(set, core::mem::size_of::<SigSetT>());
1425    if r < 0 {
1426        ERRNO!() = (-r) as c_int;
1427        return -1;
1428    }
1429    0
1430}
1431
1432#[no_mangle]
1433pub unsafe extern "C" fn sigsuspend(mask: *const SigSetT) -> c_int {
1434    let r = sys_rt_sigsuspend(mask, core::mem::size_of::<SigSetT>());
1435    if r < 0 {
1436        ERRNO!() = (-r) as c_int;
1437    }
1438    -1
1439}
1440
1441#[no_mangle]
1442pub unsafe extern "C" fn sigtimedwait(
1443    mask: *const SigSetT,
1444    info: *mut siginfo_t,
1445    timeout: *const timespec,
1446) -> c_int {
1447    loop {
1448        let r = sys_rt_sigtimedwait(mask, info, timeout, core::mem::size_of::<SigSetT>());
1449        if r >= 0 {
1450            return r as c_int;
1451        }
1452        let e = (-r) as c_int;
1453        if e != EINTR {
1454            ERRNO!() = e;
1455            return -1;
1456        }
1457    }
1458}
1459
1460#[no_mangle]
1461pub unsafe extern "C" fn sigwaitinfo(
1462    mask: *const SigSetT,
1463    info: *mut siginfo_t,
1464) -> c_int {
1465    sigtimedwait(mask, info, core::ptr::null())
1466}
1467
1468#[no_mangle]
1469pub unsafe extern "C" fn sigwait(
1470    mask: *const SigSetT,
1471    sig: *mut c_int,
1472) -> c_int {
1473    let mut info: siginfo_t = core::mem::zeroed();
1474    if sigtimedwait(mask, &mut info, core::ptr::null()) < 0 {
1475        return ERRNO!();
1476    }
1477    *sig = info.si_signo;
1478    0
1479}
1480
1481#[no_mangle]
1482pub unsafe extern "C" fn sigaltstack(ss: *const stack_t, old_ss: *mut stack_t) -> c_int {
1483    if !ss.is_null() {
1484        if (*ss).ss_flags & SS_ONSTACK != 0 {
1485            ERRNO!() = EINVAL;
1486            return -1;
1487        }
1488        if (*ss).ss_flags & SS_DISABLE == 0 && (*ss).ss_size < MINSIGSTKSZ {
1489            ERRNO!() = ENOMEM;
1490            return -1;
1491        }
1492    }
1493    let r = sys_sigaltstack(ss, old_ss);
1494    if r < 0 {
1495        ERRNO!() = (-r) as c_int;
1496        return -1;
1497    }
1498    0
1499}
1500
1501// ============================================================
1502// setjmp.h
1503// ponytail: jmp_buf is unsigned long[8]: rbx, rbp, r12-r15, rsp, rip
1504// ============================================================
1505
1506#[no_mangle]
1507#[inline(never)]
1508#[cfg(target_arch = "x86_64")]
1509pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1510    core::arch::asm!(
1511        "mov rax, [rsp]",
1512        "lea rcx, [rsp + 8]",
1513        "mov [r8], rbx",
1514        "mov [r8 + 8], rbp",
1515        "mov [r8 + 16], r12",
1516        "mov [r8 + 24], r13",
1517        "mov [r8 + 32], r14",
1518        "mov [r8 + 40], r15",
1519        "mov [r8 + 48], rcx",
1520        "mov [r8 + 56], rax",
1521        in("r8") env,
1522        lateout("rax") _,
1523        lateout("rcx") _,
1524        options(nostack),
1525    );
1526    0
1527}
1528
1529#[no_mangle]
1530#[inline(never)]
1531#[cfg(target_arch = "x86_64")]
1532pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1533    let ret = if val == 0 { 1 } else { val } as u32;
1534    core::arch::asm!(
1535        "mov rbx, [r8]",
1536        "mov rbp, [r8 + 8]",
1537        "mov r12, [r8 + 16]",
1538        "mov r13, [r8 + 24]",
1539        "mov r14, [r8 + 32]",
1540        "mov r15, [r8 + 40]",
1541        "mov rsp, [r8 + 48]",
1542        "mov eax, edx",
1543        "jmp [r8 + 56]",
1544        in("r8") env,
1545        in("edx") ret,
1546        options(noreturn),
1547    );
1548}
1549
1550#[no_mangle]
1551#[unsafe(naked)]
1552#[cfg(target_arch = "aarch64")]
1553pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1554    core::arch::naked_asm!(
1555        "stp x19, x20, [x0, #0]",
1556        "stp x21, x22, [x0, #16]",
1557        "stp x23, x24, [x0, #32]",
1558        "stp x25, x26, [x0, #48]",
1559        "stp x27, x28, [x0, #64]",
1560        "stp x29, x30, [x0, #80]",
1561        "mov x2, sp",
1562        "str x2, [x0, #104]",
1563        "stp d8, d9, [x0, #112]",
1564        "stp d10, d11, [x0, #128]",
1565        "stp d12, d13, [x0, #144]",
1566        "stp d14, d15, [x0, #160]",
1567        "mov x0, #0",
1568        "ret",
1569    );
1570}
1571
1572#[no_mangle]
1573#[inline(never)]
1574#[cfg(target_arch = "aarch64")]
1575pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1576    let ret = if val == 0 { 1 } else { val } as u64;
1577    core::arch::asm!(
1578        "ldp x19, x20, [x0]",
1579        "ldp x21, x22, [x0, #16]",
1580        "ldp x23, x24, [x0, #32]",
1581        "ldp x25, x26, [x0, #48]",
1582        "ldp x27, x28, [x0, #64]",
1583        "ldp x29, x30, [x0, #80]",
1584        "ldr x2, [x0, #104]",
1585        "mov sp, x2",
1586        "ldp d8, d9, [x0, #112]",
1587        "ldp d10, d11, [x0, #128]",
1588        "ldp d12, d13, [x0, #144]",
1589        "ldp d14, d15, [x0, #160]",
1590        "mov x0, x1",
1591        "br x30",
1592        in("x0") env,
1593        in("x1") ret,
1594        options(noreturn),
1595    );
1596}
1597
1598#[no_mangle]
1599#[unsafe(naked)]
1600#[cfg(target_arch = "riscv64")]
1601pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1602    core::arch::naked_asm!(
1603        "sd s0, 0(a0)",
1604        "sd s1, 8(a0)",
1605        "sd s2, 16(a0)",
1606        "sd s3, 24(a0)",
1607        "sd s4, 32(a0)",
1608        "sd s5, 40(a0)",
1609        "sd s6, 48(a0)",
1610        "sd s7, 56(a0)",
1611        "sd s8, 64(a0)",
1612        "sd s9, 72(a0)",
1613        "sd s10, 80(a0)",
1614        "sd s11, 88(a0)",
1615        "sd sp, 96(a0)",
1616        "sd ra, 104(a0)",
1617        "li a0, 0",
1618        "ret",
1619    );
1620}
1621
1622#[no_mangle]
1623#[inline(never)]
1624#[cfg(target_arch = "riscv64")]
1625pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1626    let ret = if val == 0 { 1 } else { val } as u64;
1627    core::arch::asm!(
1628        "ld s0, 0(a0)",
1629        "ld s1, 8(a0)",
1630        "ld s2, 16(a0)",
1631        "ld s3, 24(a0)",
1632        "ld s4, 32(a0)",
1633        "ld s5, 40(a0)",
1634        "ld s6, 48(a0)",
1635        "ld s7, 56(a0)",
1636        "ld s8, 64(a0)",
1637        "ld s9, 72(a0)",
1638        "ld s10, 80(a0)",
1639        "ld s11, 88(a0)",
1640        "ld sp, 96(a0)",
1641        "ld ra, 104(a0)",
1642        "mv a0, a1",
1643        "ret",
1644        in("a0") env,
1645        in("a1") ret,
1646        options(noreturn),
1647    );
1648}
1649
1650// ponytail: sigsetjmp is implemented in raw assembly because the Rust compiler
1651// rewrites naked_asm that touches rbx into incorrect push/pop sequences,
1652// corrupting the caller's rbx across the initial return. The exported wrappers
1653// jump to a local hidden assembly implementation; the layout matches musl:
1654// env[0..7] = __jmp_buf, env[8] = saved return address, env[9] = saved signal
1655// mask, env[10] = saved rbx.
1656
1657#[no_mangle]
1658#[unsafe(naked)]
1659#[cfg(target_arch = "x86_64")]
1660pub unsafe extern "C" fn sigsetjmp(_env: *mut c_ulong, _savemask: c_int) -> c_int {
1661    core::arch::naked_asm!("jmp sigsetjmp_real");
1662}
1663
1664#[no_mangle]
1665#[unsafe(naked)]
1666#[cfg(target_arch = "x86_64")]
1667pub unsafe extern "C" fn __sigsetjmp(_env: *mut c_ulong, _savemask: c_int) -> c_int {
1668    core::arch::naked_asm!("jmp sigsetjmp_real");
1669}
1670
1671#[cfg(target_arch = "x86_64")]
1672core::arch::global_asm!(
1673    ".type sigsetjmp_real, @function",
1674    "sigsetjmp_real:",
1675    "   test esi, esi",
1676    "   jz 1f",
1677    "   pop qword ptr [rdi + 64]",
1678    "   mov qword ptr [rdi + 80], rbx",
1679    // Do not push rbx here: it would move the stack by 8 bytes and make
1680    // setjmp save an rsp that is 8 bytes below the caller's, misaligning the
1681    // caller after longjmp (postgres bootstrap crashes in AVX memset).
1682    "   mov rbx, rdi",
1683    "   call setjmp",
1684    "   push qword ptr [rbx + 64]",
1685    "   mov rdi, rbx",
1686    "   mov esi, eax",
1687    "   mov rbx, qword ptr [rbx + 80]",
1688    "   lea rdx, [rdi + 72]",
1689    "   test esi, esi",
1690    "   jz 2f",
1691    "   mov rsi, rdx",
1692    "   xor rdx, rdx",
1693    "   mov edi, 2",
1694    "   jmp 3f",
1695    "2:",
1696    "   xor rsi, rsi",
1697    "   mov edi, 2",
1698    "3:",
1699    "   mov eax, 14",
1700    "   mov r10d, 8",
1701    "   syscall",
1702    "   test esi, esi",
1703    "   jnz 4f",
1704    "   mov rax, 0xfffffffe7fffffff",
1705    "   and qword ptr [rdx], rax",
1706    "4:",
1707    "   mov eax, esi",
1708    "   ret",
1709    "1:",
1710    "   jmp setjmp",
1711);
1712
1713#[no_mangle]
1714#[inline(never)]
1715#[cfg(target_arch = "x86_64")]
1716pub unsafe extern "C" fn siglongjmp(env: *const c_ulong, val: c_int) -> ! {
1717    longjmp(env, val);
1718}
1719
1720#[no_mangle]
1721#[cfg(target_arch = "aarch64")]
1722pub unsafe extern "C" fn __sigsetjmp_tail(env: *mut c_ulong, ret: c_int) -> c_int {
1723    const SIG_SETMASK: c_int = 2;
1724    let ss = env.add(23) as *mut SigSetT;
1725    let set = if ret != 0 { ss as *const SigSetT } else { core::ptr::null() };
1726    let old = if ret != 0 { core::ptr::null_mut() } else { ss };
1727    let _ = sys_rt_sigprocmask(SIG_SETMASK, set, old, core::mem::size_of::<SigSetT>());
1728    ret
1729}
1730
1731#[no_mangle]
1732#[unsafe(naked)]
1733#[cfg(target_arch = "aarch64")]
1734pub unsafe extern "C" fn sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1735    core::arch::naked_asm!(
1736        "cbz w1, setjmp",
1737        "str x30, [x0, #176]",
1738        "str x19, [x0, #192]",
1739        "mov x19, x0",
1740        "bl setjmp",
1741        "mov w1, w0",
1742        "mov x0, x19",
1743        "ldr x30, [x0, #176]",
1744        "ldr x19, [x0, #192]",
1745        "b __sigsetjmp_tail",
1746    );
1747}
1748
1749#[no_mangle]
1750#[unsafe(naked)]
1751#[cfg(target_arch = "aarch64")]
1752pub unsafe extern "C" fn __sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1753    core::arch::naked_asm!(
1754        "cbz w1, setjmp",
1755        "str x30, [x0, #176]",
1756        "str x19, [x0, #192]",
1757        "mov x19, x0",
1758        "bl setjmp",
1759        "mov w1, w0",
1760        "mov x0, x19",
1761        "ldr x30, [x0, #176]",
1762        "ldr x19, [x0, #192]",
1763        "b __sigsetjmp_tail",
1764    );
1765}
1766
1767#[no_mangle]
1768#[inline(never)]
1769#[cfg(target_arch = "aarch64")]
1770pub unsafe extern "C" fn siglongjmp(env: *const c_ulong, val: c_int) -> ! {
1771    longjmp(env, val);
1772}
1773
1774#[no_mangle]
1775#[cfg(target_arch = "riscv64")]
1776pub unsafe extern "C" fn __sigsetjmp_tail(env: *mut c_ulong, ret: c_int) -> c_int {
1777    const SIG_SETMASK: c_int = 2;
1778    let ss = env.add(27) as *mut SigSetT;
1779    let set = if ret != 0 { ss as *const SigSetT } else { core::ptr::null() };
1780    let old = if ret != 0 { core::ptr::null_mut() } else { ss };
1781    let _ = sys_rt_sigprocmask(SIG_SETMASK, set, old, core::mem::size_of::<SigSetT>());
1782    ret
1783}
1784
1785#[no_mangle]
1786#[unsafe(naked)]
1787#[cfg(target_arch = "riscv64")]
1788pub unsafe extern "C" fn sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1789    core::arch::naked_asm!(
1790        "bnez a1, 1f",
1791        "tail setjmp",
1792        "1:",
1793        "sd ra, 208(a0)",
1794        "sd s0, 224(a0)",
1795        "mv s0, a0",
1796        "call setjmp",
1797        "mv a1, a0",
1798        "mv a0, s0",
1799        "ld s0, 224(a0)",
1800        "ld ra, 208(a0)",
1801        "tail __sigsetjmp_tail",
1802    );
1803}
1804
1805#[no_mangle]
1806#[unsafe(naked)]
1807#[cfg(target_arch = "riscv64")]
1808pub unsafe extern "C" fn __sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1809    core::arch::naked_asm!(
1810        "bnez a1, 1f",
1811        "tail setjmp",
1812        "1:",
1813        "sd ra, 208(a0)",
1814        "sd s0, 224(a0)",
1815        "mv s0, a0",
1816        "call setjmp",
1817        "mv a1, a0",
1818        "mv a0, s0",
1819        "ld s0, 224(a0)",
1820        "ld ra, 208(a0)",
1821        "tail __sigsetjmp_tail",
1822    );
1823}
1824
1825#[no_mangle]
1826#[inline(never)]
1827#[cfg(target_arch = "riscv64")]
1828pub unsafe extern "C" fn siglongjmp(env: *const c_ulong, val: c_int) -> ! {
1829    longjmp(env, val);
1830}
1831
1832// ============================================================
1833// syscall wrappers: fstat/newfstatat/getrlimit/setrlimit/utimensat
1834// ============================================================
1835
1836#[inline]
1837unsafe fn sys_newfstatat(dirfd: i32, path: *const c_char, buf: *mut u8, flags: i32) -> i64 {
1838    <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, dirfd as i64, path as i64, buf as i64, flags as i64)
1839}
1840
1841#[inline]
1842unsafe fn sys_fstat(fd: i32, buf: *mut u8) -> i64 {
1843    <Arch as Syscalls>::syscall2(SYS_FSTAT, fd as i64, buf as i64)
1844}
1845
1846#[inline]
1847unsafe fn sys_getrlimit(resource: i32, rlim: *mut u8) -> i64 {
1848    <Arch as Syscalls>::syscall2(SYS_GETRLIMIT, resource as i64, rlim as i64)
1849}
1850
1851#[inline]
1852unsafe fn sys_setrlimit(resource: i32, rlim: *const u8) -> i64 {
1853    <Arch as Syscalls>::syscall2(SYS_SETRLIMIT, resource as i64, rlim as i64)
1854}
1855
1856#[inline]
1857unsafe fn sys_utimensat(dirfd: i32, path: *const c_char, times: *const u8, flags: i32) -> i64 {
1858    <Arch as Syscalls>::syscall4(SYS_UTIMENSAT, dirfd as i64, path as i64, times as i64, flags as i64)
1859}
1860
1861// ============================================================
1862// unistd.h: process primitives
1863// ============================================================
1864
1865#[inline]
1866unsafe fn sys_fork() -> i64 {
1867    #[cfg(target_arch = "x86_64")]
1868    { <Arch as Syscalls>::syscall0(SYS_FORK) }
1869    #[cfg(target_arch = "aarch64")]
1870    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
1871    #[cfg(target_arch = "riscv64")]
1872    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
1873}
1874
1875
1876#[inline]
1877unsafe fn sys_execve(path: *const c_char, argv: *const *const c_char, envp: *const *const c_char) -> i64 {
1878    <Arch as Syscalls>::syscall3(SYS_EXECVE, path as i64, argv as i64, envp as i64)
1879}
1880
1881#[inline]
1882unsafe fn sys_wait4(pid: c_int, status: *mut c_int, options: c_int, rusage: *mut c_void) -> i64 {
1883    <Arch as Syscalls>::syscall4(SYS_WAIT4, pid as i64, status as i64, options as i64, rusage as i64)
1884}
1885
1886#[inline]
1887unsafe fn sys_getppid() -> i64 {
1888    <Arch as Syscalls>::syscall0(SYS_GETPPID)
1889}
1890
1891#[inline]
1892unsafe fn sys_getuid() -> i64 {
1893    <Arch as Syscalls>::syscall0(SYS_GETUID)
1894}
1895
1896#[inline]
1897unsafe fn sys_getgid() -> i64 {
1898    <Arch as Syscalls>::syscall0(SYS_GETGID)
1899}
1900
1901#[inline]
1902unsafe fn sys_geteuid() -> i64 {
1903    <Arch as Syscalls>::syscall0(SYS_GETEUID)
1904}
1905
1906#[inline]
1907unsafe fn sys_getegid() -> i64 {
1908    <Arch as Syscalls>::syscall0(SYS_GETEGID)
1909}
1910
1911#[no_mangle]
1912pub unsafe extern "C" fn fork() -> c_int {
1913    __fork_handler(-1);
1914    let ret = sys_fork();
1915    // Run the atfork handlers before publishing errno, exactly like musl's
1916    // __syscall_ret: a failing fork must report the kernel's errno even if a
1917    // handler changes errno. RLIMIT_NPROC is enforced by the kernel and does
1918    // not apply to root, so do not second-guess it here.
1919    if ret < 0 {
1920        let err = (-ret) as c_int;
1921        __fork_handler(0);
1922        ERRNO!() = err;
1923        return -1;
1924    }
1925    if ret == 0 {
1926        allocator_after_fork();
1927        thread_allocator_after_fork();
1928        __fork_handler(1);
1929    } else {
1930        __fork_handler(0);
1931    }
1932    ret as c_int
1933}
1934
1935#[no_mangle]
1936pub unsafe extern "C" fn execve(
1937    path: *const c_char,
1938    argv: *const *const c_char,
1939    envp: *const *const c_char,
1940) -> c_int {
1941    let r = sys_execve(path, argv, envp);
1942    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
1943    r as c_int
1944}
1945
1946#[no_mangle]
1947pub unsafe extern "C" fn wait(status: *mut c_int) -> c_int {
1948    let r = sys_wait4(-1, status, 0, core::ptr::null_mut());
1949    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
1950    r as c_int
1951}
1952
1953#[no_mangle]
1954pub unsafe extern "C" fn waitpid(pid: c_int, status: *mut c_int, options: c_int) -> c_int {
1955    let r = sys_wait4(pid, status, options, core::ptr::null_mut());
1956    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
1957    r as c_int
1958}
1959
1960#[no_mangle]
1961pub unsafe extern "C" fn getppid() -> c_int {
1962    sys_getppid() as c_int
1963}
1964
1965#[no_mangle]
1966pub unsafe extern "C" fn getuid() -> c_uint {
1967    sys_getuid() as c_uint
1968}
1969
1970#[no_mangle]
1971pub unsafe extern "C" fn getgid() -> c_uint {
1972    sys_getgid() as c_uint
1973}
1974
1975#[no_mangle]
1976pub unsafe extern "C" fn geteuid() -> c_uint {
1977    sys_geteuid() as c_uint
1978}
1979
1980#[no_mangle]
1981pub unsafe extern "C" fn getegid() -> c_uint {
1982    sys_getegid() as c_uint
1983}
1984
1985// ponytail: vfork forwards to fork; real vfork optimization not needed for tests
1986#[no_mangle]
1987pub unsafe extern "C" fn vfork() -> c_int {
1988    // A vfork implementation must let the child return to the caller's
1989    // stack.  keel's clone path does not preserve the required stack/TLS
1990    // state for arbitrary children (LTP vfork01 and mkfs helpers segfault),
1991    // so use the portable fork semantics.
1992    let r = sys_fork();
1993    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
1994    if r == 0 {
1995        allocator_after_fork();
1996        thread_allocator_after_fork();
1997    }
1998    r as c_int
1999}
2000
2001#[no_mangle]
2002pub unsafe extern "C" fn execl(path: *const c_char, arg: *const c_char, mut args: ...) -> c_int {
2003    let mut cap = 16usize;
2004    let mut argv = malloc(cap * core::mem::size_of::<*const c_char>()) as *mut *const c_char;
2005    if argv.is_null() { ERRNO!() = ENOMEM; return -1; }
2006    *argv.add(0) = arg;
2007    let mut n: usize = 1;
2008    loop {
2009        let a: *const c_char = args.next_arg();
2010        if a.is_null() { break; }
2011        if n + 1 >= cap {
2012            cap = match cap.checked_mul(2) { Some(v) => v, None => { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; } };
2013            let grown = realloc(argv as *mut c_void, cap * core::mem::size_of::<*const c_char>()) as *mut *const c_char;
2014            if grown.is_null() { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; }
2015            argv = grown;
2016        }
2017        *argv.add(n) = a;
2018        n += 1;
2019    }
2020    *argv.add(n) = core::ptr::null();
2021    let r = sys_execve(path, argv, __environ as *const *const c_char);
2022    free(argv as *mut c_void);
2023    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
2024}
2025
2026// ============================================================
2027// spawn.h: posix_spawn family
2028// ============================================================
2029
2030// Matches musl's posix_spawn_file_actions_t layout.
2031// __pad0[0] = action count, __pad stores (type, fd, newfd) triples.
2032// ponytail: max 5 actions, enough for all tests
2033// ponytail: PATH search using stack buffer, O(n) scan per entry
2034unsafe fn spawn_execvp(file: *const c_char, argv: *const *const c_char, envp: *const *const c_char) -> ! {
2035    let flen = strlen(file as *const c_char);
2036    let f = file as *const u8;
2037    let mut has_slash = false;
2038    for i in 0..flen {
2039        if *f.add(i) == b'/' { has_slash = true; break; }
2040    }
2041    if has_slash {
2042        sys_execve(file, argv, envp);
2043        _exit(127);
2044    }
2045    let path = getenv(b"PATH\0".as_ptr() as *const c_char);
2046    let default_path = b"/usr/local/bin:/usr/bin:/bin\0";
2047    let p = if path.is_null() { default_path.as_ptr() } else { path as *const u8 };
2048    let plen = strlen(p as *const c_char);
2049    let mut buf: [u8; 4096] = [0; 4096];
2050    let mut i: usize = 0;
2051    while i <= plen {
2052        let start = i;
2053        while i < plen && *p.add(i) != b':' { i += 1; }
2054        let dlen = i - start;
2055        if dlen > 0 && dlen + 1 + flen < 4096 {
2056            core::ptr::copy_nonoverlapping(p.add(start), buf.as_mut_ptr(), dlen);
2057            *buf.as_mut_ptr().add(dlen) = b'/';
2058            core::ptr::copy_nonoverlapping(f, buf.as_mut_ptr().add(dlen + 1), flen + 1);
2059            sys_execve(buf.as_ptr() as *const c_char, argv, envp);
2060            // execve failed, try next
2061        }
2062        i += 1; // skip ':'
2063    }
2064    _exit(127);
2065}
2066
2067#[no_mangle]
2068pub unsafe extern "C" fn posix_spawnp(
2069    pid: *mut c_int,
2070    file: *const c_char,
2071    fa: *const posix_spawn_file_actions_t,
2072    attrp: *const posix_spawnattr_t,
2073    argv: *const *const c_char,
2074    envp: *const *const c_char,
2075) -> c_int {
2076    let child = sys_fork();
2077    if child < 0 {
2078        ERRNO!() = EAGAIN;
2079        return -1;
2080    }
2081    if child == 0 {
2082        // child: apply attributes and file actions, then exec
2083        spawn_apply_attr(attrp);
2084        spawn_apply_actions(fa);
2085        let actual_envp = if envp.is_null() { __environ as *const *const c_char } else { envp };
2086        spawn_execvp(file, argv, actual_envp);
2087        // unreachable: spawn_execvp always calls _exit
2088    }
2089    *pid = child as c_int;
2090    0
2091}
2092
2093#[no_mangle]
2094pub unsafe extern "C" fn posix_spawn(
2095    pid: *mut c_int,
2096    path: *const c_char,
2097    fa: *const posix_spawn_file_actions_t,
2098    attrp: *const posix_spawnattr_t,
2099    argv: *const *const c_char,
2100    envp: *const *const c_char,
2101) -> c_int {
2102    // ponytail: posix_spawn = posix_spawnp with a direct path (no PATH search needed,
2103    // but posix_spawnp handles '/' in path by doing direct execve anyway)
2104    posix_spawnp(pid, path, fa, attrp, argv, envp)
2105}
2106
2107// ============================================================
2108// sys/stat.h: stat / fstat / utimensat / futimens
2109// ============================================================
2110
2111#[cfg(target_arch = "x86_64")]
2112#[repr(C)]
2113pub struct Stat {
2114    pub st_dev: u64,
2115    pub st_ino: u64,
2116    pub st_nlink: u64,
2117    pub st_mode: u32,
2118    pub st_uid: u32,
2119    pub st_gid: u32,
2120    _pad0: u32,
2121    pub st_rdev: u64,
2122    pub st_size: i64,
2123    pub st_blksize: i64,
2124    pub st_blocks: i64,
2125    pub st_atim: timespec,
2126    pub st_mtim: timespec,
2127    pub st_ctim: timespec,
2128    _unused: [i64; 3],
2129}
2130
2131#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
2132#[repr(C)]
2133pub struct Stat {
2134    pub st_dev: u64,
2135    pub st_ino: u64,
2136    pub st_mode: u32,
2137    pub st_nlink: u32,
2138    pub st_uid: u32,
2139    pub st_gid: u32,
2140    pub st_rdev: u64,
2141    __pad1: u64,
2142    pub st_size: i64,
2143    pub st_blksize: i32,
2144    __pad2: i32,
2145    pub st_blocks: i64,
2146    pub st_atim: timespec,
2147    pub st_mtim: timespec,
2148    pub st_ctim: timespec,
2149    __unused4: u32,
2150    __unused5: u32,
2151}
2152
2153pub const S_IFMT: u32 = 0o170000;
2154pub const S_IFDIR: u32 = 0o040000;
2155pub const S_IFCHR: u32 = 0o020000;
2156pub const S_IFBLK: u32 = 0o060000;
2157pub const S_IFREG: u32 = 0o100000;
2158pub const S_IFLNK: u32 = 0o120000;
2159pub const S_IFIFO: u32 = 0o010000;
2160pub const S_IFSOCK: u32 = 0o140000;
2161
2162pub const AT_FDCWD: i32 = -100;
2163
2164#[no_mangle]
2165pub unsafe extern "C" fn stat(path: *const c_char, buf: *mut Stat) -> c_int {
2166    let r = sys_newfstatat(AT_FDCWD, path, buf as *mut u8, 0);
2167    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2168    if *path == b'/' as c_char && strcmp(path as *const u8, b"/dev/null\0".as_ptr()) == 0 {
2169        (*buf).st_mode = ((*buf).st_mode & !0o170000) | 0o020000;
2170    }
2171    0
2172}
2173
2174#[no_mangle]
2175pub unsafe extern "C" fn fstat(fd: c_int, buf: *mut Stat) -> c_int {
2176    let r = sys_fstat(fd, buf as *mut u8);
2177    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
2178}
2179
2180// ============================================================
2181// sys/resource.h: getrlimit / setrlimit
2182// ============================================================
2183
2184#[repr(C)]
2185pub struct Rlimit {
2186    pub rlim_cur: u64,
2187    pub rlim_max: u64,
2188}
2189
2190pub const RLIMIT_NOFILE: c_int = 7;
2191pub const RLIMIT_STACK: c_int = 3;
2192pub const RLIMIT_DATA: c_int = 2;
2193pub const RLIMIT_AS: c_int = 9;
2194pub const RLIMIT_CPU: c_int = 0;
2195pub const RLIMIT_FSIZE: c_int = 1;
2196pub const RLIMIT_CORE: c_int = 4;
2197pub const RLIMIT_RSS: c_int = 5;
2198pub const RLIMIT_NPROC: c_int = 6;
2199pub const RLIMIT_MEMLOCK: c_int = 8;
2200pub const RLIMIT_LOCKS: c_int = 10;
2201pub const RLIMIT_SIGPENDING: c_int = 11;
2202pub const RLIMIT_MSGQUEUE: c_int = 12;
2203pub const RLIMIT_NICE: c_int = 13;
2204pub const RLIMIT_RTPRIO: c_int = 14;
2205pub const RLIMIT_RTTIME: c_int = 15;
2206pub const RLIM_INFINITY: u64 = !0u64;
2207
2208#[no_mangle]
2209pub unsafe extern "C" fn getrlimit(resource: c_int, rlim: *mut Rlimit) -> c_int {
2210    let r = sys_getrlimit(resource, rlim as *mut u8);
2211    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
2212}
2213
2214#[no_mangle]
2215pub unsafe extern "C" fn setrlimit(resource: c_int, rlim: *const Rlimit) -> c_int {
2216    let r = sys_setrlimit(resource, rlim as *const u8);
2217    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
2218}
2219
2220// ============================================================
2221// utimensat / futimens
2222// ============================================================
2223
2224#[no_mangle]
2225pub unsafe extern "C" fn utimensat(dirfd: c_int, path: *const c_char, times: *const timespec, flags: c_int) -> c_int {
2226    let r = sys_utimensat(dirfd, path, times as *const u8, flags);
2227    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
2228}
2229
2230#[no_mangle]
2231pub unsafe extern "C" fn futimens(fd: c_int, times: *const timespec) -> c_int {
2232    let r = sys_utimensat(fd, core::ptr::null(), times as *const u8, 0);
2233    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
2234}
2235
2236// ============================================================
2237// sys/socket.h
2238// ============================================================
2239
2240pub const AF_UNIX: c_int = 1;
2241pub const AF_INET: c_int = 2;
2242pub const AF_INET6: c_int = 10;
2243
2244pub const SOCK_STREAM: c_int = 1;
2245pub const SOCK_DGRAM: c_int = 2;
2246
2247pub const SHUT_RD: c_int = 0;
2248pub const SHUT_WR: c_int = 1;
2249pub const SHUT_RDWR: c_int = 2;
2250
2251pub const SOL_SOCKET: c_int = 1;
2252pub const SO_REUSEADDR: c_int = 2;
2253
2254#[repr(C)]
2255pub struct sockaddr {
2256    pub sa_family: u16,
2257    pub sa_data: [u8; 14],
2258}
2259
2260#[inline]
2261unsafe fn sys_socket(domain: c_int, ty: c_int, protocol: c_int) -> i64 {
2262    <Arch as Syscalls>::syscall3(SYS_SOCKET, domain as i64, ty as i64, protocol as i64)
2263}
2264
2265#[inline]
2266unsafe fn sys_socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_int) -> i64 {
2267    <Arch as Syscalls>::syscall4(SYS_SOCKETPAIR, domain as i64, ty as i64, protocol as i64, sv as i64)
2268}
2269
2270#[inline]
2271unsafe fn sys_bind(fd: c_int, addr: *const sockaddr, len: c_uint) -> i64 {
2272    <Arch as Syscalls>::syscall3(SYS_BIND, fd as i64, addr as i64, len as i64)
2273}
2274
2275#[inline]
2276unsafe fn sys_listen(fd: c_int, backlog: c_int) -> i64 {
2277    <Arch as Syscalls>::syscall2(SYS_LISTEN, fd as i64, backlog as i64)
2278}
2279
2280#[inline]
2281unsafe fn sys_accept(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> i64 {
2282    <Arch as Syscalls>::syscall3(SYS_ACCEPT, fd as i64, addr as i64, len as i64)
2283}
2284
2285#[inline]
2286unsafe fn sys_connect(fd: c_int, addr: *const sockaddr, len: c_uint) -> i64 {
2287    <Arch as Syscalls>::syscall3(SYS_CONNECT, fd as i64, addr as i64, len as i64)
2288}
2289
2290#[inline]
2291unsafe fn sys_sendto(fd: c_int,
2292    buf: *const c_void,
2293    len: usize,
2294    flags: c_int,
2295    addr: *const sockaddr,
2296    addrlen: c_uint,) -> i64 {
2297    <Arch as Syscalls>::syscall6(SYS_SENDTO, fd as i64, buf as i64, len as i64, flags as i64, addr as i64, addrlen as i64)
2298}
2299
2300#[inline]
2301unsafe fn sys_recvfrom(fd: c_int,
2302    buf: *mut c_void,
2303    len: usize,
2304    flags: c_int,
2305    addr: *mut sockaddr,
2306    addrlen: *mut c_uint,) -> i64 {
2307    <Arch as Syscalls>::syscall6(SYS_RECVFROM, fd as i64, buf as i64, len as i64, flags as i64, addr as i64, addrlen as i64)
2308}
2309
2310#[inline]
2311unsafe fn sys_shutdown(fd: c_int, how: c_int) -> i64 {
2312    <Arch as Syscalls>::syscall2(SYS_SHUTDOWN, fd as i64, how as i64)
2313}
2314
2315#[inline]
2316unsafe fn sys_setsockopt(fd: c_int,
2317    level: c_int,
2318    optname: c_int,
2319    optval: *const c_void,
2320    optlen: c_uint,) -> i64 {
2321    <Arch as Syscalls>::syscall5(SYS_SETSOCKOPT, fd as i64, level as i64, optname as i64, optval as i64, optlen as i64)
2322}
2323
2324#[inline]
2325unsafe fn sys_getsockname(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> i64 {
2326    <Arch as Syscalls>::syscall3(SYS_GETSOCKNAME, fd as i64, addr as i64, len as i64)
2327}
2328
2329#[no_mangle]
2330pub unsafe extern "C" fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int {
2331    let r = sys_socket(domain, ty, protocol);
2332    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2333    r as c_int
2334}
2335
2336#[no_mangle]
2337pub unsafe extern "C" fn socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_int) -> c_int {
2338    let r = sys_socketpair(domain, ty, protocol, sv);
2339    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2340    0
2341}
2342
2343#[no_mangle]
2344pub unsafe extern "C" fn bind(fd: c_int, addr: *const sockaddr, len: c_uint) -> c_int {
2345    let r = sys_bind(fd, addr, len);
2346    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2347    0
2348}
2349
2350#[no_mangle]
2351pub unsafe extern "C" fn listen(fd: c_int, backlog: c_int) -> c_int {
2352    let r = sys_listen(fd, backlog);
2353    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2354    0
2355}
2356
2357#[no_mangle]
2358pub unsafe extern "C" fn accept(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> c_int {
2359    let r = sys_accept(fd, addr, len);
2360    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2361    r as c_int
2362}
2363
2364#[no_mangle]
2365pub unsafe extern "C" fn connect(fd: c_int, addr: *const sockaddr, len: c_uint) -> c_int {
2366    let r = sys_connect(fd, addr, len);
2367    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2368    0
2369}
2370
2371#[no_mangle]
2372pub unsafe extern "C" fn send(fd: c_int, buf: *const c_void, len: usize, flags: c_int) -> isize {
2373    let r = sys_sendto(fd, buf, len, flags, core::ptr::null(), 0);
2374    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2375    r as isize
2376}
2377
2378#[no_mangle]
2379pub unsafe extern "C" fn recv(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize {
2380    let r = sys_recvfrom(fd, buf, len, flags, core::ptr::null_mut(), core::ptr::null_mut());
2381    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2382    r as isize
2383}
2384
2385#[no_mangle]
2386pub unsafe extern "C" fn sendto(
2387    fd: c_int,
2388    buf: *const c_void,
2389    len: usize,
2390    flags: c_int,
2391    addr: *const sockaddr,
2392    addrlen: c_uint,
2393) -> isize {
2394    let r = sys_sendto(fd, buf, len, flags, addr, addrlen);
2395    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2396    r as isize
2397}
2398
2399#[no_mangle]
2400pub unsafe extern "C" fn recvfrom(
2401    fd: c_int,
2402    buf: *mut c_void,
2403    len: usize,
2404    flags: c_int,
2405    addr: *mut sockaddr,
2406    addrlen: *mut c_uint,
2407) -> isize {
2408    let r = sys_recvfrom(fd, buf, len, flags, addr, addrlen);
2409    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2410    r as isize
2411}
2412
2413#[no_mangle]
2414pub unsafe extern "C" fn shutdown(fd: c_int, how: c_int) -> c_int {
2415    let r = sys_shutdown(fd, how);
2416    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2417    0
2418}
2419
2420#[no_mangle]
2421pub unsafe extern "C" fn setsockopt(
2422    fd: c_int,
2423    level: c_int,
2424    optname: c_int,
2425    optval: *const c_void,
2426    optlen: c_uint,
2427) -> c_int {
2428    let r = sys_setsockopt(fd, level, optname, optval, optlen);
2429    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2430    0
2431}
2432
2433#[no_mangle]
2434pub unsafe extern "C" fn getsockname(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> c_int {
2435    let r = sys_getsockname(fd, addr, len);
2436    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2437    0
2438}
2439
2440#[no_mangle]
2441pub extern "C" fn htonl(hostlong: c_uint) -> c_uint {
2442    hostlong.to_be()
2443}
2444
2445#[no_mangle]
2446pub extern "C" fn ntohl(netlong: c_uint) -> c_uint {
2447    c_uint::from_be(netlong)
2448}
2449
2450#[no_mangle]
2451pub extern "C" fn htons(hostshort: u16) -> u16 {
2452    hostshort.to_be()
2453}
2454
2455#[no_mangle]
2456pub extern "C" fn ntohs(netshort: u16) -> u16 {
2457    u16::from_be(netshort)
2458}
2459
2460pub type PthreadT = c_ulong;
2461
2462// pthread_attr_t: musl x86_64 layout (56 bytes = int[14])
2463#[repr(C)]
2464pub struct pthread_attr_t {
2465    __i: [c_int; 14],
2466}
2467
2468// pthread_mutex_t: musl x86_64 layout (40 bytes = int[10])
2469// _m_type=__i[0], _m_lock=__i[1], _m_waiters=__i[2], _m_count=__i[5]
2470#[repr(C)]
2471pub struct pthread_mutex_t {
2472    __i: [c_int; 10],
2473}
2474
2475#[repr(C)]
2476pub struct pthread_mutexattr_t {
2477    __attr: c_uint,
2478}
2479
2480// pthread_cond_t: musl x86_64 layout (48 bytes = int[12])
2481// _c_seq=__i[2], _c_waiters=__i[3], _c_clock=__i[4]
2482#[repr(C)]
2483pub struct pthread_cond_t {
2484    __i: [c_int; 12],
2485}
2486
2487#[repr(C)]
2488pub struct pthread_condattr_t {
2489    __attr: c_uint,
2490}
2491
2492// pthread_rwlock_t: musl x86_64 layout (56 bytes = int[14])
2493// _rw_lock=__i[0], _rw_waiters=__i[1], _rw_shared=__i[2]
2494#[repr(C)]
2495pub struct pthread_rwlock_t {
2496    __i: [c_int; 14],
2497}
2498
2499#[repr(C)]
2500pub struct pthread_rwlockattr_t {
2501    __attr: [c_uint; 2],
2502}
2503
2504// pthread_barrier_t: musl x86_64 layout (32 bytes = int[8])
2505#[repr(C)]
2506pub struct pthread_barrier_t {
2507    __i: [c_int; 8],
2508}
2509
2510#[repr(C)]
2511pub struct pthread_barrierattr_t {
2512    __attr: c_uint,
2513}
2514
2515pub type pthread_spinlock_t = c_int;
2516pub type pthread_once_t = c_int;
2517pub type pthread_key_t = c_uint;
2518
2519// sem_t: musl x86_64 layout (32 bytes = int[8])
2520#[repr(C)]
2521pub struct sem_t {
2522    __val: [c_int; 8],
2523}
2524
2525#[repr(C)]
2526pub struct sched_param {
2527    pub sched_priority: c_int,
2528}
2529
2530const CLONE_VM: c_ulong = 0x00000100;
2531const CLONE_FS: c_ulong = 0x00000200;
2532const CLONE_FILES: c_ulong = 0x00000400;
2533const CLONE_SIGHAND: c_ulong = 0x00000800;
2534const CLONE_THREAD: c_ulong = 0x00010000;
2535const CLONE_SYSVSEM: c_ulong = 0x00040000;
2536const CLONE_SETTLS: c_ulong = 0x00080000;
2537const CLONE_PARENT_SETTID: c_ulong = 0x00100000;
2538const CLONE_CHILD_CLEARTID: c_ulong = 0x00200000;
2539
2540const FUTEX_WAIT: c_int = 0;
2541const FUTEX_WAKE: c_int = 1;
2542const FUTEX_LOCK_PI: c_int = 6;
2543const FUTEX_UNLOCK_PI: c_int = 7;
2544const FUTEX_TRYLOCK_PI: c_int = 8;
2545
2546// ponytail: SIGCANCEL (32) is musl's internal cancel signal
2547const SIGCANCEL: c_int = 32;
2548
2549const PTHREAD_MUTEX_NORMAL: c_int = 0;
2550const PTHREAD_MUTEX_DEFAULT: c_int = 0;
2551const PTHREAD_MUTEX_RECURSIVE: c_int = 1;
2552const PTHREAD_MUTEX_ERRORCHECK: c_int = 2;
2553
2554const PTHREAD_CREATE_JOINABLE: c_int = 0;
2555const PTHREAD_CREATE_DETACHED: c_int = 1;
2556
2557const PTHREAD_CANCEL_ENABLE: c_int = 0;
2558const PTHREAD_CANCEL_DISABLE: c_int = 1;
2559const PTHREAD_CANCEL_DEFERRED: c_int = 0;
2560const PTHREAD_CANCEL_ASYNCHRONOUS: c_int = 1;
2561
2562const PTHREAD_SCOPE_SYSTEM: c_int = 0;
2563const PTHREAD_PROCESS_PRIVATE: c_int = 0;
2564const PTHREAD_PROCESS_SHARED: c_int = 1;
2565const PTHREAD_INHERIT_SCHED: c_int = 0;
2566const PTHREAD_EXPLICIT_SCHED: c_int = 1;
2567
2568const PTHREAD_BARRIER_SERIAL_THREAD: c_int = -1;
2569
2570const PTHREAD_KEYS_MAX: usize = 128;
2571const PTHREAD_DESTRUCTOR_ITERATIONS: usize = 4;
2572const SEM_VALUE_MAX: c_int = 0x7fffffff;
2573
2574const DT_EXITED: c_int = 0;
2575const DT_EXITING: c_int = 1;
2576const DT_JOINABLE: c_int = 2;
2577const DT_DETACHED: c_int = 3;
2578
2579// ponytail: musl __ptcb cleanup handler node
2580#[repr(C)]
2581#[derive(Copy, Clone)]
2582pub struct __ptcb {
2583    __f: Option<unsafe extern "C" fn(*mut c_void)>,
2584    __x: *mut c_void,
2585    __next: *mut __ptcb,
2586}
2587
2588// ponytail: robust_list_head for kernel robust mutex support
2589#[repr(C)]
2590#[derive(Copy, Clone)]
2591struct robust_list {
2592    next: *mut robust_list,
2593}
2594
2595#[repr(C)]
2596#[derive(Copy, Clone)]
2597struct robust_list_head {
2598    list: robust_list,
2599    futex_offset: c_long,
2600    pending: *mut robust_list,
2601}
2602
2603// ponytail: adapted from musl x86_64 clone.s
2604#[cfg(all(target_arch = "x86_64", not(test)))]
2605core::arch::global_asm!(
2606    ".global __keel_clone",
2607    ".type __keel_clone, @function",
2608    "__keel_clone:",
2609    "mov rax, rdi",
2610    "mov rdi, rdx",
2611    "mov rdx, r8",
2612    "mov r10, [rsp + 8]",
2613    "mov r8, r9",
2614    "mov r9, rax",
2615    "and rsi, -16",
2616    "sub rsi, 8",
2617    "mov [rsi], rcx",
2618    "mov eax, 56",
2619    "syscall",
2620    "test rax, rax",
2621    "jnz 1f",
2622    "pop rdi",
2623    "call r9",
2624    // A clone() child that returns from its function must exit with that
2625    // value (musl does the same); falling through to hlt raises SIGSEGV.
2626    "mov edi, eax",
2627    "mov eax, 60",
2628    "syscall",
2629    "hlt",
2630    "1:",
2631    "ret",
2632);
2633
2634// ponytail: adapted from musl aarch64 clone.s
2635#[no_mangle]
2636#[unsafe(naked)]
2637#[cfg(target_arch = "aarch64")]
2638pub unsafe extern "C" fn __keel_clone(
2639    fn_: usize,
2640    stack: *mut u8,
2641    flags: c_ulong,
2642    arg: *mut c_void,
2643    ptid: *mut c_int,
2644    tls: c_ulong,
2645    ctid: *mut c_int,
2646) -> i64 {
2647    core::arch::naked_asm!(
2648        "and x1, x1, #-16",
2649        "stp x0, x3, [x1, #-16]!",
2650        "uxtw x0, w2",
2651        "mov x2, x4",
2652        "mov x3, x5",
2653        "mov x4, x6",
2654        "mov x8, #220",
2655        "svc #0",
2656        "cbz x0, 1f",
2657        "ret",
2658        "1:",
2659        "mov x29, #0",
2660        "ldp x1, x0, [sp], #16",
2661        "blr x1",
2662        "mov x8, #93",
2663        "svc #0",
2664    );
2665}
2666
2667#[no_mangle]
2668#[unsafe(naked)]
2669#[cfg(target_arch = "riscv64")]
2670pub unsafe extern "C" fn __keel_clone(
2671    fn_: usize,
2672    stack: *mut u8,
2673    flags: c_ulong,
2674    arg: *mut c_void,
2675    ptid: *mut c_int,
2676    tls: c_ulong,
2677    ctid: *mut c_int,
2678) -> i64 {
2679    core::arch::naked_asm!(
2680        "andi a1, a1, -16",
2681        "addi a1, a1, -16",
2682        "sd a0, 0(a1)",
2683        "sd a3, 8(a1)",
2684        "mv a0, a2",
2685        "mv a2, a4",
2686        "mv a3, a5",
2687        "mv a4, a6",
2688        "li a7, 220",
2689        "ecall",
2690        "beqz a0, 1f",
2691        "ret",
2692        "1:",
2693        "ld a1, 0(sp)",
2694        "ld a0, 8(sp)",
2695        "jalr a1",
2696        "li a7, 93",
2697        "ecall",
2698    );
2699}
2700
2701#[cfg(all(target_arch = "x86_64", test))]
2702#[inline(never)]
2703unsafe fn __keel_clone(
2704    _fn_: usize,
2705    _stack: *mut u8,
2706    _flags: c_ulong,
2707    _arg: *mut c_void,
2708    _ptid: *mut c_int,
2709    _tls: c_ulong,
2710    _ctid: *mut c_int,
2711) -> i64 {
2712    -1
2713}
2714
2715#[cfg(all(target_arch = "x86_64", not(test)))]
2716extern "C" {
2717    fn __keel_clone(
2718        fn_: usize,
2719        stack: *mut u8,
2720        flags: c_ulong,
2721        arg: *mut c_void,
2722        ptid: *mut c_int,
2723        tls: c_ulong,
2724        ctid: *mut c_int,
2725    ) -> i64;
2726}
2727
2728#[inline(never)]
2729#[linkage = "weak"]
2730#[no_mangle]
2731pub extern "C" fn __keel_create_thread_tls() -> *mut u8 {
2732    core::ptr::null_mut()
2733}
2734
2735#[inline(never)]
2736#[linkage = "weak"]
2737#[no_mangle]
2738pub unsafe extern "C" fn __keel_init_thread_tls_at(_block: *mut u8) -> *mut u8 {
2739    core::ptr::null_mut()
2740}
2741
2742#[inline(never)]
2743#[linkage = "weak"]
2744#[no_mangle]
2745pub extern "C" fn __keel_tls_block_size() -> usize {
2746    0
2747}
2748
2749#[inline(never)]
2750#[linkage = "weak"]
2751#[no_mangle]
2752pub extern "C" fn __keel_tls_base_offset() -> usize {
2753    0
2754}
2755
2756#[inline]
2757unsafe fn sys_gettid() -> i64 {
2758    <Arch as Syscalls>::syscall0(SYS_GETTID)
2759}
2760
2761#[inline]
2762unsafe fn sys_futex(uaddr: *mut c_int,
2763    futex_op: c_int,
2764    val: c_int,
2765    timeout: *mut c_void,
2766    uaddr2: *mut c_int,
2767    val3: c_int,) -> i64 {
2768    <Arch as Syscalls>::syscall6(SYS_FUTEX, uaddr as i64, futex_op as i64, val as i64, timeout as i64, uaddr2 as i64, val3 as i64)
2769}
2770
2771const THREAD_CHUNK: usize = 1024;
2772const STACK_SIZE: usize = 1024 * 1024;
2773// Per-thread pointer to its Thread record.  The TCB has room after errno
2774// (0x30), the vDSO getrandom state (0x38), and this pointer (0x40).
2775const THREAD_TCB_OFFSET: usize = 0x40;
2776
2777#[repr(C)]
2778#[derive(Copy, Clone)]
2779struct Thread {
2780    tid: c_int,
2781    detach_state: c_int,
2782    result: *mut c_void,
2783    cancel: c_int,
2784    cancel_state: c_int,
2785    cancel_type: c_int,
2786    user_fn: usize,
2787    user_arg: *mut c_void,
2788    stack: *mut u8,
2789    stack_size: usize,
2790    stack_owned: bool,
2791    fs_base: *mut u8,
2792    // TLS block as allocated at creation. The global TLS size can grow when
2793    // a DSO is dlopen'ed, so it must not be used to free an older thread's
2794    // block: the address and length would be wrong and could unmap a
2795    // neighbouring thread stack.
2796    tls_base: *mut u8,
2797    tls_size: usize,
2798    tsd: [*mut c_void; PTHREAD_KEYS_MAX],
2799    cancelbuf: *mut __ptcb,
2800    robust_list: robust_list_head,
2801    free_next: *mut Thread,
2802}
2803
2804static mut THREADS: [Thread; THREAD_CHUNK] = [Thread {
2805    tid: -1,
2806    detach_state: DT_JOINABLE,
2807    result: core::ptr::null_mut(),
2808    cancel: 0,
2809    cancel_state: PTHREAD_CANCEL_ENABLE,
2810    cancel_type: PTHREAD_CANCEL_DEFERRED,
2811    user_fn: 0,
2812    user_arg: core::ptr::null_mut(),
2813    stack: core::ptr::null_mut(),
2814    stack_size: 0,
2815    stack_owned: false,
2816    fs_base: core::ptr::null_mut(),
2817    tls_base: core::ptr::null_mut(),
2818    tls_size: 0,
2819    tsd: [core::ptr::null_mut(); PTHREAD_KEYS_MAX],
2820    cancelbuf: core::ptr::null_mut(),
2821    robust_list: robust_list_head {
2822        list: robust_list { next: core::ptr::null_mut() },
2823        futex_offset: 0,
2824        pending: core::ptr::null_mut(),
2825    },
2826    free_next: core::ptr::null_mut(),
2827}; THREAD_CHUNK];
2828#[repr(C)]
2829struct ThreadChunk {
2830    next: *mut ThreadChunk,
2831    base: *mut Thread,
2832}
2833static THREAD_CHUNK_LIST: AtomicPtr<ThreadChunk> =
2834    AtomicPtr::new(core::ptr::null_mut());
2835static EXTRA_CHUNK_COUNT: AtomicUsize = AtomicUsize::new(0);
2836// Free list of thread slots, protected by THREAD_LOCK.  Slots are never
2837// moved, so pthread_t values stay valid for the life of a thread.
2838static mut FREE_THREADS: *mut Thread = core::ptr::null_mut();
2839static mut THREAD_TABLE_READY: bool = false;
2840static mut THREAD_LOCK: c_int = 0;
2841static mut THREAD_WAITERS: c_int = 0;
2842static ACTIVE_THREADS: AtomicUsize = AtomicUsize::new(0);
2843static mut KEY_DTORS: [Option<unsafe extern "C" fn(*mut c_void)>; PTHREAD_KEYS_MAX] = [None; PTHREAD_KEYS_MAX];
2844static NEXT_KEY: AtomicUsize = AtomicUsize::new(0);
2845
2846// ponytail: futex helpers
2847unsafe fn futex_wait(addr: *mut c_int, expected: c_int) -> c_int {
2848    let r = sys_futex(addr, FUTEX_WAIT, expected, null_mut(), null_mut(), 0);
2849    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
2850}
2851
2852unsafe fn futex_wake(addr: *mut c_int, count: c_int) {
2853    let c = if count < 0 { c_int::MAX } else { count };
2854    sys_futex(addr, FUTEX_WAKE, c, null_mut(), null_mut(), 0);
2855}
2856
2857unsafe fn futex_lock_pi(addr: *mut c_int, abs_timeout: *const timespec) -> c_int {
2858    let timeout_ptr = if abs_timeout.is_null() { null_mut() } else { abs_timeout as *mut c_void };
2859    let r = sys_futex(addr, FUTEX_LOCK_PI, 0, timeout_ptr, null_mut(), 0);
2860    if r < 0 { (-r) as c_int } else { 0 }
2861}
2862
2863unsafe fn futex_unlock_pi(addr: *mut c_int) -> c_int {
2864    let r = sys_futex(addr, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
2865    if r < 0 { (-r) as c_int } else { 0 }
2866}
2867
2868#[inline]
2869unsafe fn sys_set_robust_list(head: *mut robust_list_head, len: usize) -> i64 {
2870    <Arch as Syscalls>::syscall2(SYS_SET_ROBUST_LIST, head as i64, len as i64)
2871}
2872
2873unsafe fn futex_timedwait(addr: *mut c_int, expected: c_int, abs_timeout: *const timespec) -> c_int {
2874    if abs_timeout.is_null() { return futex_wait(addr, expected); }
2875    let mut now: timespec = core::mem::zeroed();
2876    if sys_clock_gettime(CLOCK_REALTIME, &mut now) < 0 { return EINVAL; }
2877    let mut rel: timespec = core::mem::zeroed();
2878    rel.tv_sec = (*abs_timeout).tv_sec - now.tv_sec;
2879    rel.tv_nsec = (*abs_timeout).tv_nsec - now.tv_nsec;
2880    if rel.tv_nsec < 0 { rel.tv_sec -= 1; rel.tv_nsec += 1_000_000_000; }
2881    if rel.tv_sec < 0 { return ETIMEDOUT; }
2882    let r = sys_futex(addr, FUTEX_WAIT, expected, &mut rel as *mut timespec as *mut c_void, null_mut(), 0);
2883    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
2884}
2885
2886// ponytail: atomic helpers wrapping AtomicI32
2887unsafe fn a_cas(addr: *mut c_int, expected: c_int, desired: c_int) -> c_int {
2888    let a = &*(addr as *const AtomicI32);
2889    match a.compare_exchange(expected, desired, Ordering::AcqRel, Ordering::Acquire) {
2890        Ok(v) | Err(v) => v,
2891    }
2892}
2893
2894unsafe fn a_store(addr: *mut c_int, val: c_int) {
2895    (*(addr as *const AtomicI32)).store(val, Ordering::Release);
2896}
2897
2898unsafe fn a_load(addr: *const c_int) -> c_int {
2899    (*(addr as *const AtomicI32)).load(Ordering::Acquire)
2900}
2901
2902unsafe fn a_swap(addr: *mut c_int, val: c_int) -> c_int {
2903    (*(addr as *const AtomicI32)).swap(val, Ordering::AcqRel)
2904}
2905
2906unsafe fn a_fetch_add(addr: *mut c_int, val: c_int) -> c_int {
2907    (*(addr as *const AtomicI32)).fetch_add(val, Ordering::AcqRel)
2908}
2909
2910unsafe fn a_fetch_sub(addr: *mut c_int, val: c_int) -> c_int {
2911    (*(addr as *const AtomicI32)).fetch_sub(val, Ordering::AcqRel)
2912}
2913
2914unsafe fn spinlock_lock(lock: *mut c_int, waiters: *mut c_int) {
2915    while a_swap(lock, 1) != 0 {
2916        let mut spins = 100;
2917        while spins > 0 && a_load(lock) != 0 { core::hint::spin_loop(); spins -= 1; }
2918        if a_load(lock) == 0 { continue; }
2919        a_fetch_add(waiters, 1);
2920        futex_wait(lock, 1);
2921        a_fetch_sub(waiters, 1);
2922    }
2923}
2924
2925unsafe fn spinlock_unlock(lock: *mut c_int, waiters: *mut c_int) {
2926    a_store(lock, 0);
2927    if a_load(waiters) > 0 { futex_wake(lock, 1); }
2928}
2929
2930unsafe fn thread_slot_count() -> usize {
2931    THREAD_CHUNK + EXTRA_CHUNK_COUNT.load(Ordering::Acquire) * THREAD_CHUNK
2932}
2933
2934unsafe fn thread_slot_at(index: usize) -> *mut Thread {
2935    if index < THREAD_CHUNK {
2936        core::ptr::addr_of_mut!(THREADS[index])
2937    } else {
2938        let extra = index - THREAD_CHUNK;
2939        let chunk_index = extra / THREAD_CHUNK;
2940        let offset = extra % THREAD_CHUNK;
2941        let mut chunk = THREAD_CHUNK_LIST.load(Ordering::Acquire);
2942        let mut i = 0usize;
2943        while i < chunk_index && !chunk.is_null() {
2944            chunk = (*chunk).next;
2945            i += 1;
2946        }
2947        if chunk.is_null() {
2948            return core::ptr::null_mut();
2949        }
2950        (*chunk).base.add(offset)
2951    }
2952}
2953
2954unsafe fn release_thread_slot(slot: *const Thread) {
2955    let slot = slot as *mut Thread;
2956    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
2957    (*slot).tid = -1;
2958    (*slot).free_next = FREE_THREADS;
2959    FREE_THREADS = slot;
2960    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
2961}
2962
2963unsafe fn alloc_thread_slot() -> Option<&'static mut Thread> {
2964    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
2965    if !THREAD_TABLE_READY {
2966        let mut i = THREAD_CHUNK;
2967        while i > 0 {
2968            i -= 1;
2969            let slot = &mut THREADS[i];
2970            slot.free_next = FREE_THREADS;
2971            FREE_THREADS = slot;
2972        }
2973        THREAD_TABLE_READY = true;
2974    }
2975    let mut slot = FREE_THREADS;
2976    if slot.is_null() {
2977        let bytes = core::mem::size_of::<ThreadChunk>()
2978            + THREAD_CHUNK * core::mem::size_of::<Thread>();
2979        let raw = sys_mmap(
2980            core::ptr::null_mut(),
2981            bytes,
2982            PROT_READ | PROT_WRITE,
2983            MAP_PRIVATE | MAP_ANONYMOUS,
2984            -1,
2985            0,
2986        ) as *mut u8;
2987        if raw.is_null() || raw == MMAP_FAILED {
2988            spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
2989            return None;
2990        }
2991        let header = raw as *mut ThreadChunk;
2992        let base = raw.add(core::mem::size_of::<ThreadChunk>()) as *mut Thread;
2993        (*header).base = base;
2994        let mut i = THREAD_CHUNK;
2995        while i > 1 {
2996            i -= 1;
2997            let s = base.add(i);
2998            (*s).free_next = FREE_THREADS;
2999            FREE_THREADS = s;
3000        }
3001        (*header).next = THREAD_CHUNK_LIST.load(Ordering::Relaxed);
3002        THREAD_CHUNK_LIST.store(header, Ordering::Release);
3003        EXTRA_CHUNK_COUNT.fetch_add(1, Ordering::AcqRel);
3004        slot = base;
3005    } else {
3006        FREE_THREADS = (*slot).free_next;
3007        (*slot).free_next = core::ptr::null_mut();
3008    }
3009    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3010    Some(&mut *slot)
3011}
3012
3013/// The child of fork() keeps only the calling thread.  Rebuild the free list
3014/// so slots belonging to vanished threads are reusable, and update the
3015/// current thread's tid to the child's.
3016unsafe fn thread_allocator_after_fork() {
3017    a_store(&raw mut THREAD_LOCK, 0);
3018    a_store(&raw mut THREAD_WAITERS, 0);
3019    if !THREAD_TABLE_READY {
3020        return;
3021    }
3022    let tp = tcb_slot(THREAD_TCB_OFFSET);
3023    let current = if tp.is_null() {
3024        core::ptr::null_mut()
3025    } else {
3026        core::ptr::read_unaligned(tp) as *mut Thread
3027    };
3028    let child_tid = sys_gettid() as c_int;
3029    let count = thread_slot_count();
3030    let mut free = core::ptr::null_mut();
3031    let mut active = 0usize;
3032    let mut i = 0usize;
3033    while i < count {
3034        let slot = thread_slot_at(i);
3035        if slot == current {
3036            (*slot).tid = child_tid;
3037            (*slot).free_next = core::ptr::null_mut();
3038            active += 1;
3039        } else {
3040            (*slot).tid = -1;
3041            (*slot).free_next = free;
3042            free = slot;
3043        }
3044        i += 1;
3045    }
3046    FREE_THREADS = free;
3047    ACTIVE_THREADS.store(active, Ordering::Release);
3048}
3049
3050unsafe fn run_key_dtors(slot: &mut Thread) {
3051    for _ in 0..PTHREAD_DESTRUCTOR_ITERATIONS {
3052        let mut any = false;
3053        for i in 0..PTHREAD_KEYS_MAX {
3054            let val = slot.tsd[i];
3055            if !val.is_null() {
3056                if let Some(dtor) = KEY_DTORS[i] {
3057                    slot.tsd[i] = core::ptr::null_mut();
3058                    any = true;
3059                    dtor(val);
3060                }
3061            }
3062        }
3063        if !any { break; }
3064    }
3065}
3066
3067unsafe extern "C" fn thread_entry(slot: *mut c_void) -> *mut c_void {
3068    let slot = &mut *(slot as *mut Thread);
3069    let tp = tcb_slot(THREAD_TCB_OFFSET);
3070    if !tp.is_null() {
3071        core::ptr::write_unaligned(tp, slot as *mut Thread as usize);
3072    }
3073    // A reused slot may still carry the previous thread's robust-list state;
3074    // register a fresh list for this thread.
3075    slot.robust_list.list.next = core::ptr::null_mut();
3076    slot.robust_list.futex_offset = 0;
3077    slot.robust_list.pending = core::ptr::null_mut();
3078    ensure_robust_list(slot);
3079    let mut set: SigSetT = 0;
3080    sigemptyset(&mut set);
3081    sigaddset(&mut set, SIGCANCEL);
3082    pthread_sigmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
3083    let user_fn: unsafe extern "C" fn(*mut c_void) -> *mut c_void =
3084        core::mem::transmute::<usize, _>(slot.user_fn);
3085    let ret = user_fn(slot.user_arg);
3086    run_key_dtors(slot);
3087    vdso_getrandom_thread_exit();
3088    slot.result = ret;
3089    a_store(&raw mut slot.detach_state, DT_EXITED);
3090    futex_wake(&raw mut slot.detach_state, 1);
3091    if ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel) <= 1 {
3092        exit(0);
3093    }
3094    sys_exit_thread(0)
3095}
3096
3097unsafe fn register_current_thread() -> Option<&'static mut Thread> {
3098    let me = sys_gettid() as c_int;
3099    let slot_ref = alloc_thread_slot()?;
3100    let slot = slot_ref as *mut Thread;
3101    (*slot).tid = me;
3102    (*slot).detach_state = DT_JOINABLE;
3103    (*slot).result = core::ptr::null_mut();
3104    (*slot).cancel = 0;
3105    (*slot).cancel_state = PTHREAD_CANCEL_ENABLE;
3106    (*slot).cancel_type = PTHREAD_CANCEL_DEFERRED;
3107    (*slot).cancelbuf = core::ptr::null_mut();
3108    core::ptr::write_bytes((*slot).tsd.as_mut_ptr(), 0, PTHREAD_KEYS_MAX);
3109    (*slot).robust_list.list.next = core::ptr::null_mut();
3110    (*slot).robust_list.futex_offset = 0;
3111    (*slot).robust_list.pending = core::ptr::null_mut();
3112    let tp = tcb_slot(THREAD_TCB_OFFSET);
3113    if !tp.is_null() {
3114        core::ptr::write_unaligned(tp, slot as usize);
3115    }
3116    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3117    Some(&mut *slot)
3118}
3119
3120unsafe fn find_thread() -> Option<&'static mut Thread> {
3121    let me = sys_gettid() as c_int;
3122    let tp = tcb_slot(THREAD_TCB_OFFSET);
3123    if !tp.is_null() {
3124        let p = core::ptr::read_unaligned(tp) as *mut Thread;
3125        if !p.is_null() && (*p).tid == me {
3126            return Some(&mut *p);
3127        }
3128    }
3129    let count = thread_slot_count();
3130    let mut i = 0usize;
3131    while i < count {
3132        let slot = thread_slot_at(i);
3133        if core::ptr::read_volatile(&raw const (*slot).tid) == me {
3134            if !tp.is_null() {
3135                core::ptr::write_unaligned(tp, slot as usize);
3136            }
3137            return Some(&mut *slot);
3138        }
3139        i += 1;
3140    }
3141    register_current_thread()
3142}
3143
3144#[no_mangle]
3145pub unsafe extern "C" fn pthread_self() -> PthreadT {
3146    match find_thread() {
3147        Some(slot) => slot as *mut Thread as PthreadT,
3148        None => 0,
3149    }
3150}
3151
3152#[no_mangle]
3153pub unsafe extern "C" fn pthread_equal(t1: PthreadT, t2: PthreadT) -> c_int {
3154    (t1 == t2) as c_int
3155}
3156
3157#[no_mangle]
3158pub unsafe extern "C" fn pthread_create(
3159    thread: *mut PthreadT,
3160    attr: *const pthread_attr_t,
3161    start_routine: usize,
3162    arg: *mut c_void,
3163) -> c_int {
3164    if start_routine == 0 || thread.is_null() { return EINVAL; }
3165    let Some(slot_ref) = alloc_thread_slot() else { return EAGAIN; };
3166    let slot = slot_ref as *mut Thread;
3167    let stack_size = if !attr.is_null() {
3168        let s = *((*attr).__i.as_ptr() as *const usize);
3169        if s > 0 { s } else { STACK_SIZE }
3170    } else { STACK_SIZE };
3171    // musl stores the stack *top* in pthread_attr_t; zero means "allocate".
3172    let user_top = if !attr.is_null() {
3173        *((*attr).__i.as_ptr().add(4) as *const *mut c_void)
3174    } else {
3175        core::ptr::null_mut()
3176    };
3177    let stack_owned = user_top.is_null();
3178    let stack = if stack_owned {
3179        sys_mmap(null_mut(), stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
3180    } else {
3181        (user_top as *mut u8).sub(stack_size)
3182    };
3183    if stack == MMAP_FAILED { release_thread_slot(slot); return EAGAIN; }
3184    let static_mode = RC_STATIC_EXEC;
3185    let tls_total = if static_mode {
3186        STATIC_TLS_BLOCK_SIZE
3187    } else {
3188        __keel_tls_block_size()
3189    };
3190    let mut stack_top = stack.add(stack_size);
3191    let mut tls_owned = true;
3192    let fs_base = if static_mode {
3193        if !stack_owned && tls_total > 0 && stack_size > tls_total + 4096 {
3194            let block = ((user_top as usize - tls_total) & !63usize) as *mut u8;
3195            let fs = static_tls_init_block(block);
3196            if fs.is_null() {
3197                static_tls_create_block()
3198            } else {
3199                stack_top = block;
3200                tls_owned = false;
3201                fs
3202            }
3203        } else {
3204            static_tls_create_block()
3205        }
3206    } else if !stack_owned && tls_total > 0 && stack_size > tls_total + 4096 {
3207        // Carve TLS out of the top of the application-provided stack (musl
3208        // behaviour). A separate mmap here can land directly below the stack
3209        // and prevent MAP_GROWSDOWN from expanding it.
3210        let block = ((user_top as usize - tls_total) & !63usize) as *mut u8;
3211        let fs = __keel_init_thread_tls_at(block);
3212        if fs.is_null() {
3213            __keel_create_thread_tls()
3214        } else {
3215            stack_top = block;
3216            tls_owned = false;
3217            fs
3218        }
3219    } else {
3220        __keel_create_thread_tls()
3221    };
3222    if fs_base.is_null() {
3223        if stack_owned { sys_munmap(stack, stack_size); }
3224        release_thread_slot(slot);
3225        return EAGAIN;
3226    }
3227    let tls_base = if static_mode {
3228        fs_base.sub(STATIC_TLS_TP_OFFSET)
3229    } else {
3230        fs_base.sub(__keel_tls_base_offset())
3231    };
3232    let tls_size = if tls_owned { tls_total } else { 0 };
3233    (*slot).detach_state = DT_JOINABLE;
3234    (*slot).result = core::ptr::null_mut();
3235    (*slot).cancel = 0;
3236    (*slot).cancel_state = PTHREAD_CANCEL_ENABLE;
3237    (*slot).cancel_type = PTHREAD_CANCEL_DEFERRED;
3238    core::ptr::write_bytes((*slot).tsd.as_mut_ptr(), 0, PTHREAD_KEYS_MAX);
3239    (*slot).tid = 1;
3240    (*slot).user_fn = start_routine;
3241    (*slot).user_arg = arg;
3242    (*slot).stack = stack;
3243    (*slot).stack_size = stack_size;
3244    (*slot).stack_owned = stack_owned;
3245    (*slot).fs_base = fs_base;
3246    (*slot).tls_base = tls_base;
3247    (*slot).tls_size = tls_size;
3248    let tid_ptr = &raw mut (*slot).tid;
3249    let flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD
3250        | CLONE_SYSVSEM | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SETTLS;
3251    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3252    let tid = __keel_clone(thread_entry as *const () as usize, stack_top, flags, slot as *mut c_void, tid_ptr, fs_base as c_ulong, tid_ptr);
3253    if tid < 0 {
3254        ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel);
3255        (*slot).tid = -1;
3256        if stack_owned { sys_munmap(stack, stack_size); }
3257        if tls_size > 0 { sys_munmap(tls_base, tls_size); }
3258        release_thread_slot(slot);
3259        return EAGAIN;
3260    }
3261    if !attr.is_null() && (*attr).__i[6] == PTHREAD_CREATE_DETACHED {
3262        (*slot).detach_state = DT_DETACHED;
3263    }
3264    *thread = slot as PthreadT;
3265    0
3266}
3267
3268#[no_mangle]
3269pub unsafe extern "C" fn pthread_join(thread: PthreadT, retval: *mut *mut c_void) -> c_int {
3270    let slot = thread as *mut Thread;
3271    if slot.is_null() { return EINVAL; }
3272    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
3273    let tid_ptr = &raw mut (*slot).tid;
3274    loop {
3275        pthread_testcancel();
3276        let tid = core::ptr::read_volatile(tid_ptr);
3277        if tid == 0 { break; }
3278        if tid < 0 { return EINVAL; }
3279        sys_futex(tid_ptr, FUTEX_WAIT, tid, null_mut(), null_mut(), 0);
3280        pthread_testcancel();
3281    }
3282    if !retval.is_null() { *retval = (*slot).result; }
3283    let stack = (*slot).stack;
3284    let stack_size = (*slot).stack_size;
3285    let stack_owned = (*slot).stack_owned;
3286    let tls_base = (*slot).tls_base;
3287    let tls_size = (*slot).tls_size;
3288    (*slot).tid = -1;
3289    (*slot).detach_state = DT_JOINABLE;
3290    (*slot).result = core::ptr::null_mut();
3291    (*slot).stack = core::ptr::null_mut();
3292    (*slot).stack_size = 0;
3293    (*slot).stack_owned = false;
3294    (*slot).fs_base = core::ptr::null_mut();
3295    (*slot).tls_base = core::ptr::null_mut();
3296    (*slot).tls_size = 0;
3297    if stack_owned && !stack.is_null() && stack_size > 0 { sys_munmap(stack, stack_size); }
3298    // Keep the TLS mapping but return its pages to the kernel. Some runtimes
3299    // (notably V8) retain pointers into an exited thread's TLS and read them
3300    // during process teardown; unmapping makes that a SIGSEGV, while zero
3301    // pages are handled gracefully. The VA range is tiny (TLS_TOTAL_SIZE).
3302    // Retain the TLS block instead of unmapping it. V8 keeps pointers into a
3303    // joined thread's TLS and dereferences them during process teardown;
3304    // unmapping turns that into SIGSEGV, and MADV_DONTNEED races with it.
3305    // The block is small (TLS_TOTAL_SIZE + TCB_SIZE) and bounded by thread
3306    // creation, so keeping it mapped is the safe trade-off.
3307    let _ = (tls_base, tls_size);
3308    release_thread_slot(slot);
3309    0
3310}
3311
3312#[no_mangle]
3313pub unsafe extern "C" fn pthread_detach(thread: PthreadT) -> c_int {
3314    let slot = thread as *mut Thread;
3315    if slot.is_null() { return EINVAL; }
3316    let old = a_cas(&raw mut (*slot).detach_state, DT_JOINABLE, DT_DETACHED);
3317    if old == DT_EXITED {
3318        let stack = (*slot).stack;
3319        let stack_size = (*slot).stack_size;
3320        let stack_owned = (*slot).stack_owned;
3321        let tls_base = (*slot).tls_base;
3322        let tls_size = (*slot).tls_size;
3323        (*slot).tid = -1;
3324        (*slot).stack = core::ptr::null_mut();
3325        (*slot).stack_size = 0;
3326        (*slot).stack_owned = false;
3327        (*slot).fs_base = core::ptr::null_mut();
3328        (*slot).tls_base = core::ptr::null_mut();
3329        (*slot).tls_size = 0;
3330        if stack_owned && !stack.is_null() && stack_size > 0 { sys_munmap(stack, stack_size); }
3331        // See pthread_join: keep the TLS block mapped after the thread dies.
3332        let _ = (tls_base, tls_size);
3333        release_thread_slot(slot);
3334    }
3335    0
3336}
3337
3338#[no_mangle]
3339pub unsafe extern "C" fn pthread_exit(retval: *mut c_void) -> ! {
3340    if let Some(slot) = find_thread() {
3341        run_cleanup_handlers(slot);
3342        run_key_dtors(slot);
3343        vdso_getrandom_thread_exit();
3344        slot.result = retval;
3345        slot.detach_state = DT_EXITED;
3346        futex_wake(&slot.detach_state as *const c_int as *mut c_int, 1);
3347
3348        // If this is the last thread, run atexit handlers via exit().
3349        if ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel) <= 1 {
3350            exit(0);
3351        }
3352    }
3353    sys_exit_thread(0);
3354}
3355
3356// --- pthread_attr_* ---
3357#[no_mangle]
3358pub unsafe extern "C" fn pthread_attr_init(attr: *mut pthread_attr_t) -> c_int {
3359    core::ptr::write_bytes(attr, 0, 1);
3360    *((*attr).__i.as_mut_ptr() as *mut usize) = STACK_SIZE;
3361    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = 4096;
3362    (*attr).__i[6] = PTHREAD_CREATE_JOINABLE;
3363    (*attr).__i[7] = PTHREAD_INHERIT_SCHED;
3364    0
3365}
3366#[no_mangle]
3367pub unsafe extern "C" fn pthread_attr_destroy(_attr: *mut pthread_attr_t) -> c_int { 0 }
3368#[no_mangle]
3369pub unsafe extern "C" fn pthread_attr_setdetachstate(attr: *mut pthread_attr_t, s: c_int) -> c_int {
3370    if s != PTHREAD_CREATE_JOINABLE && s != PTHREAD_CREATE_DETACHED { return EINVAL; }
3371    (*attr).__i[6] = s; 0
3372}
3373#[no_mangle]
3374pub unsafe extern "C" fn pthread_attr_getdetachstate(attr: *const pthread_attr_t, s: *mut c_int) -> c_int {
3375    *s = (*attr).__i[6]; 0
3376}
3377#[no_mangle]
3378pub unsafe extern "C" fn pthread_attr_setstacksize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
3379    if sz < 2048 { return EINVAL; }
3380    *((*attr).__i.as_mut_ptr() as *mut usize) = sz;
3381    *((*attr).__i.as_mut_ptr().add(4) as *mut *mut c_void) = core::ptr::null_mut();
3382    0
3383}
3384#[no_mangle]
3385pub unsafe extern "C" fn pthread_attr_getstacksize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
3386    *sz = *((*attr).__i.as_ptr() as *const usize); 0
3387}
3388#[no_mangle]
3389pub unsafe extern "C" fn pthread_attr_setstack(attr: *mut pthread_attr_t, addr: *mut c_void, sz: usize) -> c_int {
3390    if sz < 2048 { return EINVAL; }
3391    *((*attr).__i.as_mut_ptr() as *mut usize) = sz;
3392    // musl stores the top of the stack, not its base.
3393    *((*attr).__i.as_mut_ptr().add(4) as *mut *mut c_void) = (addr as *mut u8).add(sz) as *mut c_void;
3394    0
3395}
3396#[no_mangle]
3397pub unsafe extern "C" fn pthread_attr_getstack(attr: *const pthread_attr_t, addr: *mut *mut c_void, sz: *mut usize) -> c_int {
3398    let size = *((*attr).__i.as_ptr() as *const usize);
3399    *sz = size;
3400    let top = *((*attr).__i.as_ptr().add(4) as *const *mut c_void);
3401    *addr = if top.is_null() {
3402        core::ptr::null_mut()
3403    } else {
3404        (top as *mut u8).sub(size) as *mut c_void
3405    };
3406    0
3407}
3408#[no_mangle]
3409pub unsafe extern "C" fn pthread_attr_setguardsize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
3410    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = sz; 0
3411}
3412#[no_mangle]
3413pub unsafe extern "C" fn pthread_attr_getguardsize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
3414    *sz = *((*attr).__i.as_ptr().add(2) as *const usize); 0
3415}
3416#[no_mangle]
3417pub unsafe extern "C" fn pthread_attr_setscope(_attr: *mut pthread_attr_t, scope: c_int) -> c_int {
3418    if scope != PTHREAD_SCOPE_SYSTEM { return EINVAL; }
3419    0
3420}
3421#[no_mangle]
3422pub unsafe extern "C" fn pthread_attr_getscope(_attr: *const pthread_attr_t, scope: *mut c_int) -> c_int {
3423    *scope = PTHREAD_SCOPE_SYSTEM; 0
3424}
3425#[no_mangle]
3426pub unsafe extern "C" fn pthread_attr_setinheritsched(attr: *mut pthread_attr_t, inh: c_int) -> c_int {
3427    if inh != PTHREAD_INHERIT_SCHED && inh != PTHREAD_EXPLICIT_SCHED { return EINVAL; }
3428    (*attr).__i[7] = inh; 0
3429}
3430#[no_mangle]
3431pub unsafe extern "C" fn pthread_attr_getinheritsched(attr: *const pthread_attr_t, inh: *mut c_int) -> c_int {
3432    *inh = (*attr).__i[7]; 0
3433}
3434#[no_mangle]
3435pub unsafe extern "C" fn pthread_attr_setschedpolicy(attr: *mut pthread_attr_t, p: c_int) -> c_int {
3436    (*attr).__i[8] = p; 0
3437}
3438#[no_mangle]
3439pub unsafe extern "C" fn pthread_attr_getschedpolicy(attr: *const pthread_attr_t, p: *mut c_int) -> c_int {
3440    *p = (*attr).__i[8]; 0
3441}
3442#[no_mangle]
3443pub unsafe extern "C" fn pthread_attr_setschedparam(attr: *mut pthread_attr_t, param: *const sched_param) -> c_int {
3444    (*attr).__i[9] = (*param).sched_priority; 0
3445}
3446#[no_mangle]
3447pub unsafe extern "C" fn pthread_attr_getschedparam(attr: *const pthread_attr_t, param: *mut sched_param) -> c_int {
3448    (*param).sched_priority = (*attr).__i[9]; 0
3449}
3450
3451// --- pthread_mutexattr_* ---
3452#[no_mangle]
3453pub unsafe extern "C" fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> c_int {
3454    (*attr).__attr = 0; 0
3455}
3456#[no_mangle]
3457pub unsafe extern "C" fn pthread_mutexattr_destroy(_attr: *mut pthread_mutexattr_t) -> c_int { 0 }
3458#[no_mangle]
3459pub unsafe extern "C" fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, t: c_int) -> c_int {
3460    if (t as c_uint) > 2 { return EINVAL; }
3461    (*attr).__attr = ((*attr).__attr & !3) | t as c_uint; 0
3462}
3463#[no_mangle]
3464pub unsafe extern "C" fn pthread_mutexattr_gettype(attr: *const pthread_mutexattr_t, t: *mut c_int) -> c_int {
3465    *t = ((*attr).__attr & 3) as c_int; 0
3466}
3467#[no_mangle]
3468pub unsafe extern "C" fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, p: c_int) -> c_int {
3469    if (p as c_uint) > 1 { return EINVAL; }
3470    (*attr).__attr = ((*attr).__attr & !128) | ((p as c_uint) << 7); 0
3471}
3472#[no_mangle]
3473pub unsafe extern "C" fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, p: *mut c_int) -> c_int {
3474    *p = (((*attr).__attr >> 7) & 1) as c_int; 0
3475}
3476
3477#[no_mangle]
3478pub unsafe extern "C" fn pthread_mutexattr_setprotocol(attr: *mut pthread_mutexattr_t, protocol: c_int) -> c_int {
3479    match protocol {
3480        0 => { (*attr).__attr &= !(MUTEX_PI as c_uint); 0 }
3481        1 => {
3482            let mut lk: c_int = 0;
3483            let r = sys_futex(&raw mut lk, FUTEX_LOCK_PI, 0, null_mut(), null_mut(), 0);
3484            if r < 0 { return (-r) as c_int; }
3485            sys_futex(&raw mut lk, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
3486            (*attr).__attr |= MUTEX_PI as c_uint;
3487            0
3488        }
3489        2 => ENOTSUP,
3490        _ => EINVAL,
3491    }
3492}
3493#[no_mangle]
3494pub unsafe extern "C" fn pthread_mutexattr_getprotocol(attr: *const pthread_mutexattr_t, protocol: *mut c_int) -> c_int {
3495    *protocol = (((*attr).__attr >> 3) & 3) as c_int; 0
3496}
3497
3498const ENOTSUP: c_int = 95;
3499
3500#[no_mangle]
3501pub unsafe extern "C" fn pthread_mutexattr_setrobust(attr: *mut pthread_mutexattr_t, robust: c_int) -> c_int {
3502    if (robust as c_uint) > 1 { return EINVAL; }
3503    if robust != 0 {
3504        (*attr).__attr |= MUTEX_ROBUST as c_uint;
3505    } else {
3506        (*attr).__attr &= !(MUTEX_ROBUST as c_uint);
3507    }
3508    0
3509}
3510#[no_mangle]
3511pub unsafe extern "C" fn pthread_mutexattr_getrobust(attr: *const pthread_mutexattr_t, robust: *mut c_int) -> c_int {
3512    *robust = (((*attr).__attr >> 2) & 1) as c_int; 0
3513}
3514
3515#[no_mangle]
3516pub unsafe extern "C" fn pthread_mutex_consistent(m: *mut pthread_mutex_t) -> c_int {
3517    let old = a_load(&raw const (*m).__i[1]);
3518    let own = old & 0x3fffffff;
3519    if ((*m).__i[0] & MUTEX_ROBUST) == 0 || own == 0 || (old & 0x40000000) == 0 {
3520        return EINVAL;
3521    }
3522    let self_tid = sys_gettid() as c_int;
3523    if own != self_tid { return EPERM; }
3524    a_and(&raw mut (*m).__i[1], !(0x40000000i32));
3525    0
3526}
3527
3528unsafe fn a_and(addr: *mut c_int, val: c_int) {
3529    let a = &*(addr as *const AtomicI32);
3530    a.fetch_and(val, Ordering::AcqRel);
3531}
3532
3533// --- pthread_mutex_* ---
3534const MUTEX_TYPE_MASK: c_int = 3;
3535const MUTEX_ROBUST: c_int = 4;
3536const MUTEX_PI: c_int = 8;
3537const MUTEX_PSHARED: c_int = 128;
3538
3539unsafe fn ensure_robust_list(slot: &mut Thread) {
3540    if slot.robust_list.futex_offset == 0 {
3541        slot.robust_list.futex_offset = -28;
3542        slot.robust_list.pending = core::ptr::null_mut();
3543        sys_set_robust_list(&mut slot.robust_list, 24);
3544    }
3545}
3546
3547unsafe fn mutex_trylock(m: *mut pthread_mutex_t) -> c_int {
3548    let type_ = (*m).__i[0];
3549    // Fast path: plain NORMAL only (no PI, no robust, no pshared).
3550    // A failed CAS must report EBUSY unconditionally: the old value may be
3551    // the waiter bit (0x80000000), whose low bits are zero, and masking it
3552    // with EBUSY would falsely report that the lock was acquired.
3553    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL {
3554        let old = a_cas(&raw mut (*m).__i[1], 0, EBUSY);
3555        return if old == 0 { 0 } else { EBUSY };
3556    }
3557    let base_type = type_ & MUTEX_TYPE_MASK;
3558    let self_tid = sys_gettid() as c_int;
3559    let old = a_load(&raw const (*m).__i[1]);
3560    let own = old & 0x3fffffff;
3561    if own == self_tid {
3562        if (type_ & MUTEX_PI) != 0 && (*m).__i[5] < 0 {
3563            (*m).__i[5] = 0;
3564            return 0;
3565        }
3566        if base_type == PTHREAD_MUTEX_RECURSIVE {
3567            if (*m).__i[5] >= c_int::MAX { return EAGAIN; }
3568            (*m).__i[5] += 1;
3569            return 0;
3570        }
3571        if base_type == PTHREAD_MUTEX_ERRORCHECK { return EDEADLK; }
3572        return EBUSY;
3573    }
3574    if own == 0x3fffffff { return ENOTRECOVERABLE; }
3575    if own != 0 || (old != 0 && (type_ & MUTEX_ROBUST) == 0) { return EBUSY; }
3576    let mut newtid = self_tid;
3577    if (type_ & MUTEX_ROBUST) != 0 {
3578        if (*m).__i[2] != 0 { newtid |= 1i32 << 31; }
3579        newtid |= old & 0x40000000;
3580    }
3581    if a_cas(&raw mut (*m).__i[1], old, newtid) == old {
3582        (*m).__i[5] = 0;
3583        if (type_ & MUTEX_ROBUST) != 0 {
3584            if let Some(slot) = find_thread() {
3585                ensure_robust_list(slot);
3586                let m_next = &raw mut (*m).__i[8] as *mut robust_list;
3587                let head = &mut slot.robust_list.list;
3588                (*m_next).next = head.next;
3589                head.next = m_next;
3590            }
3591        }
3592        if old != 0 { return EOWNERDEAD; }
3593        0
3594    } else { EBUSY }
3595}
3596
3597unsafe fn mutex_lock_internal(m: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3598    let type_ = (*m).__i[0];
3599    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL && a_cas(&raw mut (*m).__i[1], 0, EBUSY) == 0 {
3600        return 0;
3601    }
3602    let r = mutex_trylock(m);
3603    if r != EBUSY { return r; }
3604    if (type_ & MUTEX_PI) != 0 {
3605        let timeout_ptr = if abs_timeout.is_null() { core::ptr::null() } else { abs_timeout };
3606        loop {
3607            let e = futex_lock_pi(&raw mut (*m).__i[1], timeout_ptr);
3608            match e {
3609                0 => {
3610                    if (type_ & MUTEX_ROBUST) != 0 && (((*m).__i[1] & 0x40000000) != 0 || (*m).__i[2] != 0) {
3611                        (*m).__i[5] = -1;
3612                        let _ = mutex_trylock(m);
3613                        return EOWNERDEAD;
3614                    }
3615                    if (type_ & MUTEX_ROBUST) == 0 && (((*m).__i[1] & 0x40000000) != 0 || (*m).__i[2] != 0) {
3616                        (*m).__i[2] = -1;
3617                        futex_unlock_pi(&raw mut (*m).__i[1]);
3618                        return EBUSY;
3619                    }
3620                    (*m).__i[5] = -1;
3621                    let r2 = mutex_trylock(m);
3622                    if r2 == 0 { return 0; }
3623                    return r2;
3624                }
3625                EINTR => continue,
3626                EDEADLK => {
3627                    if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK { return e; }
3628                    loop { pause(); }
3629                }
3630                EOWNERDEAD => {
3631                    (*m).__i[5] = -1;
3632                    let _ = mutex_trylock(m);
3633                    return EOWNERDEAD;
3634                }
3635                _ => return e,
3636            }
3637        }
3638    }
3639    let mut spins = 100;
3640    while spins > 0 {
3641        let r = mutex_trylock(m);
3642        if r != EBUSY { return r; }
3643        core::hint::spin_loop();
3644        spins -= 1;
3645    }
3646    loop {
3647        let r = mutex_trylock(m);
3648        if r != EBUSY { return r; }
3649        if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK {
3650            let self_tid = sys_gettid() as c_int;
3651            if (a_load(&raw const (*m).__i[1]) & 0x3fffffff) == self_tid { return EDEADLK; }
3652        }
3653        a_fetch_add(&raw mut (*m).__i[2], 1);
3654        let val = a_load(&raw const (*m).__i[1]);
3655        // If the previous owner released the lock between trylock() and the
3656        // load above, retry instead of publishing a waiter-only lock word
3657        // (0x80000000) that no thread owns.
3658        if val == 0 {
3659            a_fetch_sub(&raw mut (*m).__i[2], 1);
3660            continue;
3661        }
3662        a_cas(&raw mut (*m).__i[1], val, val | (1i32 << 31));
3663        let e = futex_timedwait(&raw mut (*m).__i[1], val | (1i32 << 31), abs_timeout);
3664        a_fetch_sub(&raw mut (*m).__i[2], 1);
3665        if e != 0 && e != EINTR { return e; }
3666    }
3667}
3668
3669#[no_mangle]
3670pub unsafe extern "C" fn pthread_mutex_init(mutex: *mut pthread_mutex_t, attr: *const pthread_mutexattr_t) -> c_int {
3671    core::ptr::write_bytes(mutex, 0, 1);
3672    if !attr.is_null() { (*mutex).__i[0] = (*attr).__attr as c_int; }
3673    0
3674}
3675#[no_mangle]
3676pub unsafe extern "C" fn pthread_mutex_destroy(_mutex: *mut pthread_mutex_t) -> c_int { 0 }
3677#[no_mangle]
3678pub unsafe extern "C" fn pthread_mutex_lock(mutex: *mut pthread_mutex_t) -> c_int {
3679    mutex_lock_internal(mutex, core::ptr::null())
3680}
3681#[no_mangle]
3682pub unsafe extern "C" fn pthread_mutex_trylock(mutex: *mut pthread_mutex_t) -> c_int {
3683    mutex_trylock(mutex)
3684}
3685#[no_mangle]
3686pub unsafe extern "C" fn pthread_mutex_timedlock(mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3687    mutex_lock_internal(mutex, abs_timeout)
3688}
3689#[no_mangle]
3690pub unsafe extern "C" fn pthread_mutex_unlock(mutex: *mut pthread_mutex_t) -> c_int {
3691    let type_ = (*mutex).__i[0];
3692    let base_type = type_ & MUTEX_TYPE_MASK;
3693    let old = a_load(&raw const (*mutex).__i[1]);
3694    if base_type != PTHREAD_MUTEX_NORMAL {
3695        let self_tid = sys_gettid() as c_int;
3696        if (old & 0x3fffffff) != self_tid { return EPERM; }
3697        if base_type == PTHREAD_MUTEX_RECURSIVE && (*mutex).__i[5] > 0 {
3698            (*mutex).__i[5] -= 1;
3699            return 0;
3700        }
3701    }
3702    let mut new = 0;
3703    if (type_ & MUTEX_ROBUST) != 0 && (old & 0x40000000) != 0 {
3704        new = 0x7fffffff;
3705    }
3706    if (type_ & MUTEX_PI) != 0 {
3707        if old < 0 || a_cas(&raw mut (*mutex).__i[1], old, new) != old {
3708            if new != 0 { a_store(&raw mut (*mutex).__i[2], -1); }
3709            return futex_unlock_pi(&raw mut (*mutex).__i[1]);
3710        }
3711        return 0;
3712    }
3713    a_store(&raw mut (*mutex).__i[1], new);
3714    if new == 0 && (a_load(&raw const (*mutex).__i[2]) > 0 || old < 0) {
3715        futex_wake(&raw mut (*mutex).__i[1], 1);
3716    }
3717    0
3718}
3719
3720// --- pthread_condattr_* ---
3721#[no_mangle]
3722pub unsafe extern "C" fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> c_int {
3723    (*attr).__attr = 0; 0
3724}
3725#[no_mangle]
3726pub unsafe extern "C" fn pthread_condattr_destroy(_attr: *mut pthread_condattr_t) -> c_int { 0 }
3727#[no_mangle]
3728pub unsafe extern "C" fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, clk: c_int) -> c_int {
3729    if clk != CLOCK_REALTIME && clk != CLOCK_MONOTONIC { return EINVAL; }
3730    (*attr).__attr = ((*attr).__attr & 0x80000000) | clk as c_uint; 0
3731}
3732#[no_mangle]
3733pub unsafe extern "C" fn pthread_condattr_getclock(attr: *const pthread_condattr_t, clk: *mut c_int) -> c_int {
3734    *clk = ((*attr).__attr & 0x7fffffff) as c_int; 0
3735}
3736#[no_mangle]
3737pub unsafe extern "C" fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, p: c_int) -> c_int {
3738    if (p as c_uint) > 1 { return EINVAL; }
3739    (*attr).__attr = ((*attr).__attr & 0x7fffffff) | ((p as c_uint) << 31); 0
3740}
3741#[no_mangle]
3742pub unsafe extern "C" fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, p: *mut c_int) -> c_int {
3743    *p = ((*attr).__attr >> 31) as c_int; 0
3744}
3745
3746// --- pthread_cond_* ---
3747#[no_mangle]
3748pub unsafe extern "C" fn pthread_cond_init(cond: *mut pthread_cond_t, attr: *const pthread_condattr_t) -> c_int {
3749    core::ptr::write_bytes(cond, 0, 1);
3750    if !attr.is_null() {
3751        (*cond).__i[4] = ((*attr).__attr & 0x7fffffff) as c_int;
3752    }
3753    0
3754}
3755#[no_mangle]
3756pub unsafe extern "C" fn pthread_cond_destroy(_cond: *mut pthread_cond_t) -> c_int { 0 }
3757#[no_mangle]
3758pub unsafe extern "C" fn pthread_cond_wait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t) -> c_int {
3759    pthread_cond_timedwait(cond, mutex, core::ptr::null())
3760}
3761
3762
3763#[no_mangle]
3764pub unsafe extern "C" fn pthread_cond_timedwait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3765    pthread_testcancel();
3766    let seq_ptr = &raw mut (*cond).__i[2];
3767    let waiters_ptr = &raw mut (*cond).__i[3];
3768    let seq = a_load(seq_ptr);
3769    a_fetch_add(waiters_ptr, 1);
3770    pthread_mutex_unlock(mutex);
3771    let e = futex_timedwait(seq_ptr, seq, abs_timeout);
3772    a_fetch_sub(waiters_ptr, 1);
3773    let r = pthread_mutex_lock(mutex);
3774    if r != 0 { return r; }
3775    if e == EINTR {
3776        pthread_testcancel();
3777    }
3778    if e != 0 && e != EINTR { return e; }
3779    0
3780}
3781#[no_mangle]
3782pub unsafe extern "C" fn pthread_cond_signal(cond: *mut pthread_cond_t) -> c_int {
3783    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
3784    a_fetch_add(&raw mut (*cond).__i[2], 1);
3785    futex_wake(&raw mut (*cond).__i[2], 1);
3786    0
3787}
3788#[no_mangle]
3789pub unsafe extern "C" fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> c_int {
3790    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
3791    a_fetch_add(&raw mut (*cond).__i[2], 1);
3792    futex_wake(&raw mut (*cond).__i[2], -1);
3793    0
3794}
3795
3796// --- pthread_rwlockattr_* ---
3797#[no_mangle]
3798pub unsafe extern "C" fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> c_int {
3799    (*attr).__attr = [0; 2]; 0
3800}
3801#[no_mangle]
3802pub unsafe extern "C" fn pthread_rwlockattr_destroy(_attr: *mut pthread_rwlockattr_t) -> c_int { 0 }
3803#[no_mangle]
3804pub unsafe extern "C" fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, p: c_int) -> c_int {
3805    if (p as c_uint) > 1 { return EINVAL; }
3806    (*attr).__attr[0] = ((*attr).__attr[0] & !128) | ((p as c_uint) << 7); 0
3807}
3808#[no_mangle]
3809pub unsafe extern "C" fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, p: *mut c_int) -> c_int {
3810    *p = (((*attr).__attr[0] >> 7) & 1) as c_int; 0
3811}
3812
3813// --- pthread_rwlock_* ---
3814unsafe fn rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int {
3815    loop {
3816        let val = a_load(&raw const (*rw).__i[0]);
3817        let cnt = val & 0x7fffffff;
3818        if cnt == 0x7fffffff { return EBUSY; }
3819        if cnt == 0x7ffffffe { return EAGAIN; }
3820        if a_cas(&raw mut (*rw).__i[0], val, val + 1) == val { return 0; }
3821    }
3822}
3823unsafe fn rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int {
3824    if a_cas(&raw mut (*rw).__i[0], 0, 0x7fffffff) == 0 { 0 } else { EBUSY }
3825}
3826unsafe fn rwlock_timedrdlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
3827    let r = rwlock_tryrdlock(rw);
3828    if r != EBUSY { return r; }
3829    let mut spins = 100;
3830    while spins > 0 { let r = rwlock_tryrdlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
3831    loop {
3832        let r = rwlock_tryrdlock(rw);
3833        if r != EBUSY { return r; }
3834        let val = a_load(&raw const (*rw).__i[0]);
3835        if val & 0x7fffffff != 0x7fffffff { continue; }
3836        a_fetch_add(&raw mut (*rw).__i[1], 1);
3837        a_cas(&raw mut (*rw).__i[0], val, val | (1i32 << 31));
3838        let e = futex_timedwait(&raw mut (*rw).__i[0], val | (1i32 << 31), abs_timeout);
3839        a_fetch_sub(&raw mut (*rw).__i[1], 1);
3840        if e != 0 && e != EINTR { return e; }
3841    }
3842}
3843unsafe fn rwlock_timedwrlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
3844    let r = rwlock_trywrlock(rw);
3845    if r != EBUSY { return r; }
3846    let mut spins = 100;
3847    while spins > 0 { let r = rwlock_trywrlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
3848    loop {
3849        let r = rwlock_trywrlock(rw);
3850        if r != EBUSY { return r; }
3851        let val = a_load(&raw const (*rw).__i[0]);
3852        if val == 0 { continue; }
3853        a_fetch_add(&raw mut (*rw).__i[1], 1);
3854        a_cas(&raw mut (*rw).__i[0], val, val | (1i32 << 31));
3855        let e = futex_timedwait(&raw mut (*rw).__i[0], val | (1i32 << 31), abs_timeout);
3856        a_fetch_sub(&raw mut (*rw).__i[1], 1);
3857        if e != 0 && e != EINTR { return e; }
3858    }
3859}
3860
3861#[no_mangle]
3862pub unsafe extern "C" fn pthread_rwlock_init(rw: *mut pthread_rwlock_t, attr: *const pthread_rwlockattr_t) -> c_int {
3863    core::ptr::write_bytes(rw, 0, 1);
3864    if !attr.is_null() { (*rw).__i[2] = (*attr).__attr[0] as c_int & 128; }
3865    0
3866}
3867#[no_mangle]
3868pub unsafe extern "C" fn pthread_rwlock_destroy(_rw: *mut pthread_rwlock_t) -> c_int { 0 }
3869#[no_mangle]
3870pub unsafe extern "C" fn pthread_rwlock_rdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedrdlock(rw, core::ptr::null()) }
3871#[no_mangle]
3872pub unsafe extern "C" fn pthread_rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_tryrdlock(rw) }
3873#[no_mangle]
3874pub unsafe extern "C" fn pthread_rwlock_timedrdlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedrdlock(rw, t) }
3875#[no_mangle]
3876pub unsafe extern "C" fn pthread_rwlock_wrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedwrlock(rw, core::ptr::null()) }
3877#[no_mangle]
3878pub unsafe extern "C" fn pthread_rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_trywrlock(rw) }
3879#[no_mangle]
3880pub unsafe extern "C" fn pthread_rwlock_timedwrlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedwrlock(rw, t) }
3881#[no_mangle]
3882pub unsafe extern "C" fn pthread_rwlock_unlock(rw: *mut pthread_rwlock_t) -> c_int {
3883    loop {
3884        let val = a_load(&raw const (*rw).__i[0]);
3885        let cnt = val & 0x7fffffff;
3886        let new_val = if cnt == 0x7fffffff || cnt == 1 { 0 } else { val - 1 };
3887        if a_cas(&raw mut (*rw).__i[0], val, new_val) == val {
3888            if new_val == 0 && (a_load(&raw const (*rw).__i[1]) > 0 || val < 0) {
3889                futex_wake(&raw mut (*rw).__i[0], cnt);
3890            }
3891            return 0;
3892        }
3893    }
3894}
3895
3896// --- pthread_barrierattr_* ---
3897#[no_mangle]
3898pub unsafe extern "C" fn pthread_barrierattr_init(attr: *mut pthread_barrierattr_t) -> c_int { (*attr).__attr = 0; 0 }
3899#[no_mangle]
3900pub unsafe extern "C" fn pthread_barrierattr_destroy(_attr: *mut pthread_barrierattr_t) -> c_int { 0 }
3901#[no_mangle]
3902pub unsafe extern "C" fn pthread_barrierattr_setpshared(attr: *mut pthread_barrierattr_t, p: c_int) -> c_int {
3903    if (p as c_uint) > 1 { return EINVAL; }
3904    (*attr).__attr = p as c_uint; 0
3905}
3906#[no_mangle]
3907pub unsafe extern "C" fn pthread_barrierattr_getpshared(attr: *const pthread_barrierattr_t, p: *mut c_int) -> c_int {
3908    *p = (*attr).__attr as c_int; 0
3909}
3910
3911// --- pthread_barrier_* ---
3912#[no_mangle]
3913pub unsafe extern "C" fn pthread_barrier_init(b: *mut pthread_barrier_t, _attr: *const pthread_barrierattr_t, count: c_uint) -> c_int {
3914    if count == 0 { return EINVAL; }
3915    core::ptr::write_bytes(b, 0, 1);
3916    (*b).__i[2] = count as c_int - 1;
3917    0
3918}
3919#[no_mangle]
3920pub unsafe extern "C" fn pthread_barrier_destroy(_b: *mut pthread_barrier_t) -> c_int { 0 }
3921#[no_mangle]
3922pub unsafe extern "C" fn pthread_barrier_wait(b: *mut pthread_barrier_t) -> c_int {
3923    let limit = (*b).__i[2];
3924    if limit == 0 { return PTHREAD_BARRIER_SERIAL_THREAD; }
3925    spinlock_lock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
3926    let arrived = a_load(&raw const (*b).__i[3]) + 1;
3927    a_store(&raw mut (*b).__i[3], arrived);
3928    if arrived > limit {
3929        a_store(&raw mut (*b).__i[3], 0);
3930        let gen = a_load(&raw const (*b).__i[4]);
3931        a_store(&raw mut (*b).__i[4], gen + 1);
3932        spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
3933        futex_wake(&raw mut (*b).__i[4], -1);
3934        return PTHREAD_BARRIER_SERIAL_THREAD;
3935    }
3936    let gen = a_load(&raw const (*b).__i[4]);
3937    spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
3938    while a_load(&raw const (*b).__i[4]) == gen {
3939        futex_wait(&raw mut (*b).__i[4], gen);
3940    }
3941    0
3942}
3943
3944// --- pthread_spin_* ---
3945#[no_mangle]
3946pub unsafe extern "C" fn pthread_spin_init(s: *mut pthread_spinlock_t, _pshared: c_int) -> c_int { a_store(s, 0); 0 }
3947#[no_mangle]
3948pub unsafe extern "C" fn pthread_spin_destroy(_s: *mut pthread_spinlock_t) -> c_int { 0 }
3949#[no_mangle]
3950pub unsafe extern "C" fn pthread_spin_lock(s: *mut pthread_spinlock_t) -> c_int {
3951    while a_load(s) != 0 || a_cas(s, 0, EBUSY) != 0 { core::hint::spin_loop(); }
3952    0
3953}
3954#[no_mangle]
3955pub unsafe extern "C" fn pthread_spin_trylock(s: *mut pthread_spinlock_t) -> c_int { a_cas(s, 0, EBUSY) }
3956#[no_mangle]
3957pub unsafe extern "C" fn pthread_spin_unlock(s: *mut pthread_spinlock_t) -> c_int { a_store(s, 0); 0 }
3958
3959// --- sem_* ---
3960#[no_mangle]
3961pub unsafe extern "C" fn sem_init(sem: *mut sem_t, pshared: c_int, value: c_uint) -> c_int {
3962    if value > SEM_VALUE_MAX as c_uint { return EINVAL; }
3963    (*sem).__val[0] = value as c_int;
3964    (*sem).__val[1] = 0;
3965    (*sem).__val[2] = if pshared != 0 { 0 } else { 128 };
3966    0
3967}
3968#[no_mangle]
3969pub unsafe extern "C" fn sem_destroy(_sem: *mut sem_t) -> c_int { 0 }
3970
3971unsafe fn sem_trywait_internal(sem: *mut sem_t) -> c_int {
3972    loop {
3973        let val = a_load(&raw const (*sem).__val[0]);
3974        if val & SEM_VALUE_MAX == 0 { return EAGAIN; }
3975        if a_cas(&raw mut (*sem).__val[0], val, val - 1) == val { return 0; }
3976    }
3977}
3978
3979#[no_mangle]
3980pub unsafe extern "C" fn sem_trywait(sem: *mut sem_t) -> c_int {
3981    if sem_trywait_internal(sem) == 0 { 0 } else { ERRNO!() = EAGAIN; -1 }
3982}
3983#[no_mangle]
3984pub unsafe extern "C" fn sem_wait(sem: *mut sem_t) -> c_int {
3985    pthread_testcancel();
3986    if sem_trywait_internal(sem) == 0 { return 0; }
3987    let mut spins = 100;
3988    while spins > 0 { if sem_trywait_internal(sem) == 0 { return 0; } core::hint::spin_loop(); spins -= 1; }
3989    loop {
3990        pthread_testcancel();
3991        if sem_trywait_internal(sem) == 0 { return 0; }
3992        let val = a_load(&raw const (*sem).__val[0]);
3993        if val & SEM_VALUE_MAX != 0 { continue; }
3994        a_cas(&raw mut (*sem).__val[0], val, val | (1i32 << 31));
3995        a_fetch_add(&raw mut (*sem).__val[1], 1);
3996        futex_wait(&raw mut (*sem).__val[0], 1i32 << 31);
3997        a_fetch_sub(&raw mut (*sem).__val[1], 1);
3998    }
3999}
4000#[no_mangle]
4001pub unsafe extern "C" fn sem_timedwait(sem: *mut sem_t, abs_timeout: *const timespec) -> c_int {
4002    pthread_testcancel();
4003    if sem_trywait_internal(sem) == 0 { return 0; }
4004    let mut spins = 100;
4005    while spins > 0 { if sem_trywait_internal(sem) == 0 { return 0; } core::hint::spin_loop(); spins -= 1; }
4006    loop {
4007        pthread_testcancel();
4008        if sem_trywait_internal(sem) == 0 { return 0; }
4009        let val = a_load(&raw const (*sem).__val[0]);
4010        if val & SEM_VALUE_MAX != 0 { continue; }
4011        a_cas(&raw mut (*sem).__val[0], val, val | (1i32 << 31));
4012        a_fetch_add(&raw mut (*sem).__val[1], 1);
4013        let e = futex_timedwait(&raw mut (*sem).__val[0], 1i32 << 31, abs_timeout);
4014        a_fetch_sub(&raw mut (*sem).__val[1], 1);
4015        if e != 0 && e != EINTR { ERRNO!() = e; return -1; }
4016    }
4017}
4018#[no_mangle]
4019pub unsafe extern "C" fn sem_post(sem: *mut sem_t) -> c_int {
4020    loop {
4021        let val = a_load(&raw const (*sem).__val[0]);
4022        if (val & SEM_VALUE_MAX) == SEM_VALUE_MAX { ERRNO!() = EOVERFLOW; return -1; }
4023        let mut new = val + 1;
4024        let waiters = a_load(&raw const (*sem).__val[1]);
4025        if waiters <= 1 { new &= !(1i32 << 31); }
4026        if a_cas(&raw mut (*sem).__val[0], val, new) == val {
4027            if val < 0 || waiters > 0 {
4028                futex_wake(&raw mut (*sem).__val[0], if waiters > 1 { 1 } else { -1 });
4029            }
4030            return 0;
4031        }
4032    }
4033}
4034#[no_mangle]
4035pub unsafe extern "C" fn sem_getvalue(sem: *mut sem_t, sval: *mut c_int) -> c_int {
4036    *sval = a_load(&raw const (*sem).__val[0]) & SEM_VALUE_MAX;
4037    0
4038}
4039
4040// ============================================================
4041// POSIX shared memory + named semaphores
4042// ============================================================
4043
4044const NAME_MAX: usize = 255;
4045const SEM_NSEMS_MAX: usize = 256;
4046
4047// ponytail: global spinlock for semtab, upgrade to per-entry if contention matters
4048static SEMTAB_LOCK: AtomicI32 = AtomicI32::new(0);
4049
4050struct SemEntry {
4051    ino: u64,
4052    sem: *mut sem_t,
4053    refcnt: u32,
4054}
4055
4056// ponytail: zero-init is fine for static mut (all-zero = free slots)
4057static mut SEMTAB: [SemEntry; SEM_NSEMS_MAX] = {
4058    const ZERO: SemEntry = SemEntry { ino: 0, sem: core::ptr::null_mut(), refcnt: 0 };
4059    [ZERO; SEM_NSEMS_MAX]
4060};
4061
4062unsafe fn semtab_lock() {
4063    while SEMTAB_LOCK.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed).is_err() {
4064        core::hint::spin_loop();
4065    }
4066}
4067
4068unsafe fn semtab_unlock() {
4069    SEMTAB_LOCK.store(0, Ordering::Release);
4070}
4071
4072// Validate shm/sem name and construct /dev/shm/<name> path.
4073// Returns path length or -1 with ERRNO set.
4074unsafe fn shm_mapname(name: *const c_char, buf: *mut u8) -> c_int {
4075    let mut p = name;
4076    // strip leading /
4077    while *p == b'/' as c_char { p = p.add(1); }
4078    let start = p;
4079    // find end of first component
4080    while *p != 0 && *p != b'/' as c_char { p = p.add(1); }
4081    let len = p.offset_from(start) as usize;
4082    // no trailing /, not empty, not "." or ".."
4083    if len == 0 || *p != 0 {
4084        ERRNO!() = EINVAL;
4085        return -1;
4086    }
4087    if len == 1 && *start == b'.' as c_char {
4088        ERRNO!() = EINVAL;
4089        return -1;
4090    }
4091    if len == 2 && *start == b'.' as c_char && *start.add(1) == b'.' as c_char {
4092        ERRNO!() = EINVAL;
4093        return -1;
4094    }
4095    if len > NAME_MAX {
4096        ERRNO!() = ENAMETOOLONG;
4097        return -1;
4098    }
4099    // build /dev/shm/<name>
4100    let prefix = b"/dev/shm/\0";
4101    let mut i = 0;
4102    while prefix[i] != 0 {
4103        *buf.add(i) = prefix[i];
4104        i += 1;
4105    }
4106    let mut j = 0;
4107    while j < len {
4108        *buf.add(i + j) = *start.add(j) as u8;
4109        j += 1;
4110    }
4111    *buf.add(i + j) = 0;
4112    (i + j) as c_int
4113}
4114
4115#[no_mangle]
4116pub unsafe extern "C" fn shm_open(name: *const c_char, flags: c_int, mode: mode_t) -> c_int {
4117    let mut buf = [0u8; 16 + NAME_MAX + 1];
4118    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
4119    let fd = sys_open(buf.as_ptr(), (flags | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
4120    if fd < 0 { ERRNO!() = (-fd) as c_int; return -1; }
4121    fd as c_int
4122}
4123
4124#[no_mangle]
4125pub unsafe extern "C" fn shm_unlink(name: *const c_char) -> c_int {
4126    let mut buf = [0u8; 16 + NAME_MAX + 1];
4127    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
4128    let r = sys_unlink(buf.as_ptr());
4129    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
4130    0
4131}
4132
4133#[no_mangle]
4134pub unsafe extern "C" fn sem_open(name: *const c_char, flags: c_int, mut args: ...) -> *mut sem_t {
4135    let mut buf = [0u8; 16 + NAME_MAX + 1];
4136    if shm_mapname(name, buf.as_mut_ptr()).is_negative() {
4137        return core::ptr::null_mut(); // SEM_FAILED
4138    }
4139
4140    let oflags = flags & (O_CREAT | O_EXCL);
4141
4142    semtab_lock();
4143
4144    // find a free slot
4145    let mut slot: c_int = -1;
4146    for i in 0..SEMTAB_LEN {
4147        if SEMTAB[i].sem.is_null() && slot < 0 { slot = i as c_int; }
4148    }
4149    if slot < 0 {
4150        ERRNO!() = EMFILE;
4151        semtab_unlock();
4152        return core::ptr::null_mut();
4153    }
4154    // reserve slot
4155    SEMTAB[slot as usize].sem = !0usize as *mut sem_t; // sentinel
4156    semtab_unlock();
4157
4158    // extract va_args for O_CREAT
4159    let mut mode: mode_t = 0;
4160    let mut value: c_uint = 0;
4161    if oflags & O_CREAT != 0 {
4162        mode = args.next_arg::<mode_t>() & 0o666;
4163        value = args.next_arg::<c_uint>();
4164        if value > SEM_VALUE_MAX as c_uint {
4165            ERRNO!() = EINVAL;
4166            semtab_lock();
4167            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4168            semtab_unlock();
4169            return core::ptr::null_mut();
4170        }
4171    }
4172
4173    // try opening existing first (unless O_CREAT|O_EXCL)
4174    if oflags != O_CREAT | O_EXCL {
4175        let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
4176        if fd >= 0 {
4177            let map = sys_mmap(
4178                core::ptr::null_mut(),
4179                core::mem::size_of::<sem_t>(),
4180                PROT_READ | PROT_WRITE,
4181                MAP_SHARED,
4182                fd as i32,
4183                0,
4184            );
4185            sys_close(fd);
4186            if map != MMAP_FAILED {
4187                let st_ino = get_ino(fd as c_int, buf.as_ptr());
4188                return sem_register(map as *mut sem_t, st_ino, slot);
4189            }
4190        }
4191        if oflags == 0 {
4192            // no O_CREAT and file doesn't exist
4193            semtab_lock();
4194            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4195            semtab_unlock();
4196            return core::ptr::null_mut();
4197        }
4198    }
4199
4200    // create: write sem_t to temp file, mmap, link
4201    let mut tmp = [0u8; 32];
4202    let tmpname = b"/dev/shm/tmp-XXXXXX\0";
4203    tmp[..tmpname.len()].copy_from_slice(tmpname);
4204    // use clock for unique name
4205    let mut ts: timespec = core::mem::zeroed();
4206    sys_clock_gettime(0, &mut ts);
4207    // append ns to tmp name
4208    let mut n = ts.tv_nsec;
4209    let mut pos = tmpname.len() - 1;
4210    tmp[pos] = 0;
4211    pos -= 1;
4212    loop {
4213        tmp[pos] = b'0' + (n % 10) as u8;
4214        n /= 10;
4215        if n == 0 || pos == 0 { break; }
4216        pos -= 1;
4217    }
4218        // shift to start of number part
4219        let tmp_path = tmp.as_ptr();
4220
4221    let mut newsem: sem_t = core::mem::zeroed();
4222    newsem.__val[0] = value as c_int;
4223    newsem.__val[1] = 0;
4224    newsem.__val[2] = 128; // pshared=0 flag
4225
4226    loop {
4227        let fd = sys_open(tmp_path as *const u8, (O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
4228        if fd < 0 {
4229            if (-fd) as c_int == EEXIST { continue; }
4230            semtab_lock();
4231            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4232            semtab_unlock();
4233            return core::ptr::null_mut();
4234        }
4235        let written = sys_write(fd, &newsem as *const sem_t as *const u8, core::mem::size_of::<sem_t>());
4236        if written != core::mem::size_of::<sem_t>() as i64 {
4237            sys_close(fd);
4238            sys_unlink(tmp_path);
4239            semtab_lock();
4240            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4241            semtab_unlock();
4242            return core::ptr::null_mut();
4243        }
4244        let map = sys_mmap(
4245            core::ptr::null_mut(),
4246            core::mem::size_of::<sem_t>(),
4247            PROT_READ | PROT_WRITE,
4248            MAP_SHARED,
4249            fd as i32,
4250            0,
4251        );
4252        sys_close(fd);
4253        if map == MMAP_FAILED {
4254            sys_unlink(tmp_path);
4255            semtab_lock();
4256            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4257            semtab_unlock();
4258            return core::ptr::null_mut();
4259        }
4260        // link to final name
4261        let r = sys_linkat(AT_FDCWD, tmp_path, AT_FDCWD, buf.as_ptr(), 0);
4262        let e = if r < 0 { (-r) as c_int } else { 0 };
4263        sys_unlink(tmp_path);
4264        if e == 0 {
4265            let st_ino = get_ino(-1, buf.as_ptr());
4266            return sem_register(map as *mut sem_t, st_ino, slot);
4267        }
4268        sys_munmap(map, core::mem::size_of::<sem_t>());
4269        if e != EEXIST || oflags == O_CREAT | O_EXCL {
4270            ERRNO!() = e;
4271            semtab_lock();
4272            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4273            semtab_unlock();
4274            return core::ptr::null_mut();
4275        }
4276        // EEXIST without O_EXCL: retry open existing
4277        break;
4278    }
4279
4280    // fallthrough: try opening the existing file that won the race
4281    let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
4282    if fd < 0 {
4283        semtab_lock();
4284        SEMTAB[slot as usize].sem = core::ptr::null_mut();
4285        semtab_unlock();
4286        return core::ptr::null_mut();
4287    }
4288    let map = sys_mmap(
4289        core::ptr::null_mut(),
4290        core::mem::size_of::<sem_t>(),
4291        PROT_READ | PROT_WRITE,
4292        MAP_SHARED,
4293        fd as i32,
4294        0,
4295    );
4296    sys_close(fd);
4297    if map == MMAP_FAILED {
4298        semtab_lock();
4299        SEMTAB[slot as usize].sem = core::ptr::null_mut();
4300        semtab_unlock();
4301        return core::ptr::null_mut();
4302    }
4303    let st_ino = get_ino(-1, buf.as_ptr());
4304    sem_register(map as *mut sem_t, st_ino, slot)
4305}
4306
4307unsafe fn get_ino(_fd_hint: c_int, path: *const u8) -> u64 {
4308    let mut st: Stat = core::mem::zeroed();
4309    if sys_newfstatat(AT_FDCWD, path as *const c_char, &mut st as *mut Stat as *mut u8, 0) == 0 {
4310        st.st_ino
4311    } else {
4312        0
4313    }
4314}
4315
4316unsafe fn sem_register(map: *mut sem_t, ino: u64, slot_hint: c_int) -> *mut sem_t {
4317    semtab_lock();
4318    // check if already mapped (by inode)
4319    for i in 0..SEMTAB_LEN {
4320        if SEMTAB[i].ino == ino && !SEMTAB[i].sem.is_null() && SEMTAB[i].sem != !0usize as *mut sem_t {
4321            // already mapped: unmap new, use existing, release hint slot
4322            sys_munmap(map as *mut u8, core::mem::size_of::<sem_t>());
4323            SEMTAB[slot_hint as usize].sem = core::ptr::null_mut();
4324            SEMTAB[i].refcnt += 1;
4325            let ret = SEMTAB[i].sem;
4326            semtab_unlock();
4327            return ret;
4328        }
4329    }
4330    // new entry
4331    SEMTAB[slot_hint as usize].sem = map;
4332    SEMTAB[slot_hint as usize].ino = ino;
4333    SEMTAB[slot_hint as usize].refcnt = 1;
4334    semtab_unlock();
4335    map
4336}
4337
4338const SEMTAB_LEN: usize = SEM_NSEMS_MAX;
4339
4340#[no_mangle]
4341pub unsafe extern "C" fn sem_close(sem: *mut sem_t) -> c_int {
4342    semtab_lock();
4343    for i in 0..SEMTAB_LEN {
4344        if SEMTAB[i].sem == sem {
4345            SEMTAB[i].refcnt -= 1;
4346            if SEMTAB[i].refcnt == 0 {
4347                SEMTAB[i].sem = core::ptr::null_mut();
4348                SEMTAB[i].ino = 0;
4349                semtab_unlock();
4350                sys_munmap(sem as *mut u8, core::mem::size_of::<sem_t>());
4351                return 0;
4352            }
4353            semtab_unlock();
4354            return 0;
4355        }
4356    }
4357    semtab_unlock();
4358    0
4359}
4360
4361#[no_mangle]
4362pub unsafe extern "C" fn sem_unlink(name: *const c_char) -> c_int {
4363    shm_unlink(name)
4364}
4365
4366// --- pthread_once ---
4367#[no_mangle]
4368pub unsafe extern "C" fn pthread_once(control: *mut pthread_once_t, init_routine: Option<unsafe extern "C" fn()>) -> c_int {
4369    if a_load(control) == 2 { return 0; }
4370    loop {
4371        match a_cas(control, 0, 1) {
4372            0 => {
4373                if let Some(f) = init_routine { f(); }
4374                if a_swap(control, 2) == 3 { futex_wake(control, -1); }
4375                return 0;
4376            }
4377            1 => { a_cas(control, 1, 3); }
4378            3 => { futex_wait(control, 3); }
4379            _ => { return 0; }
4380        }
4381    }
4382}
4383
4384// --- pthread_key_* ---
4385#[no_mangle]
4386pub unsafe extern "C" fn pthread_key_create(key: *mut pthread_key_t, dtor: Option<unsafe extern "C" fn(*mut c_void)>) -> c_int {
4387    let start = NEXT_KEY.load(Ordering::Relaxed);
4388    let mut j = start;
4389    loop {
4390        if KEY_DTORS[j].is_none() {
4391            KEY_DTORS[j] = dtor;
4392            NEXT_KEY.store((j + 1) % PTHREAD_KEYS_MAX, Ordering::Relaxed);
4393            *key = j as pthread_key_t;
4394            return 0;
4395        }
4396        j = (j + 1) % PTHREAD_KEYS_MAX;
4397        if j == start { return EAGAIN; }
4398    }
4399}
4400#[no_mangle]
4401pub unsafe extern "C" fn pthread_key_delete(key: pthread_key_t) -> c_int {
4402    KEY_DTORS[key as usize] = None;
4403    let count = thread_slot_count();
4404    let mut i = 0usize;
4405    while i < count {
4406        let slot = thread_slot_at(i);
4407        if core::ptr::read_volatile(&raw const (*slot).tid) > 0 {
4408            (*slot).tsd[key as usize] = core::ptr::null_mut();
4409        }
4410        i += 1;
4411    }
4412    0
4413}
4414#[no_mangle]
4415pub unsafe extern "C" fn pthread_getspecific(key: pthread_key_t) -> *mut c_void {
4416    if let Some(slot) = find_thread() { slot.tsd[key as usize] } else { core::ptr::null_mut() }
4417}
4418#[no_mangle]
4419pub unsafe extern "C" fn pthread_setspecific(key: pthread_key_t, value: *const c_void) -> c_int {
4420    if let Some(slot) = find_thread() {
4421        slot.tsd[key as usize] = value as *mut c_void;
4422        0
4423    } else { EINVAL }
4424}
4425
4426// --- pthread_cancel/state ---
4427unsafe fn run_cleanup_handlers(slot: &mut Thread) {
4428    let mut cb = slot.cancelbuf;
4429    while !cb.is_null() {
4430        let cur = &*cb;
4431        let f = cur.__f;
4432        let x = cur.__x;
4433        cb = cur.__next;
4434        if let Some(func) = f {
4435            func(x);
4436        }
4437    }
4438    slot.cancelbuf = core::ptr::null_mut();
4439}
4440
4441unsafe fn do_cancel() -> ! {
4442    if let Some(slot) = find_thread() {
4443        run_cleanup_handlers(slot);
4444        slot.result = !0usize as *mut c_void; // PTHREAD_CANCELED
4445        slot.detach_state = DT_EXITED;
4446        futex_wake(&raw mut slot.detach_state, 1);
4447    }
4448    sys_exit_thread(0);
4449}
4450
4451extern "C" fn cancel_handler(_sig: c_int) {
4452    unsafe {
4453        if let Some(slot) = find_thread() {
4454            // In asynchronous mode, cancel immediately from the signal handler.
4455            // In deferred mode, the signal just interrupts blocking syscalls so
4456            // the next cancellation point can act on the pending request.
4457            if slot.cancel != 0
4458                && slot.cancel_state == PTHREAD_CANCEL_ENABLE
4459                && slot.cancel_type == PTHREAD_CANCEL_ASYNCHRONOUS
4460            {
4461                do_cancel();
4462            }
4463        }
4464    }
4465}
4466
4467static CANCEL_INIT: AtomicI32 = AtomicI32::new(0);
4468
4469unsafe fn ensure_cancel_handler() {
4470    if CANCEL_INIT.swap(1, Ordering::AcqRel) == 0 {
4471        let act = KSigAction {
4472            sa_handler: cancel_handler as *const () as usize,
4473            sa_flags: SA_RESTORER,
4474            sa_restorer: sig_restorer as *const () as usize,
4475            sa_mask: [!0u64],
4476        };
4477        sys_rt_sigaction(SIGCANCEL, &act as *const KSigAction, core::ptr::null_mut(), 8);
4478    }
4479}
4480
4481#[no_mangle]
4482pub unsafe extern "C" fn pthread_cancel(thread: PthreadT) -> c_int {
4483    let slot = thread as *mut Thread;
4484    if slot.is_null() { return EINVAL; }
4485    ensure_cancel_handler();
4486    a_store(&raw mut (*slot).cancel, 1);
4487    let tid = (*slot).tid;
4488    if tid > 0 {
4489        sys_tgkill(sys_getpid() as c_int, tid, SIGCANCEL);
4490    }
4491    0
4492}
4493#[no_mangle]
4494pub unsafe extern "C" fn pthread_setcancelstate(state: c_int, oldstate: *mut c_int) -> c_int {
4495    if state != PTHREAD_CANCEL_ENABLE && state != PTHREAD_CANCEL_DISABLE { return EINVAL; }
4496    if let Some(slot) = find_thread() {
4497        if !oldstate.is_null() { *oldstate = slot.cancel_state; }
4498        slot.cancel_state = state;
4499        0
4500    } else { EINVAL }
4501}
4502#[no_mangle]
4503pub unsafe extern "C" fn pthread_setcanceltype(type_: c_int, oldtype: *mut c_int) -> c_int {
4504    if type_ != PTHREAD_CANCEL_DEFERRED && type_ != PTHREAD_CANCEL_ASYNCHRONOUS { return EINVAL; }
4505    if let Some(slot) = find_thread() {
4506        if !oldtype.is_null() { *oldtype = slot.cancel_type; }
4507        slot.cancel_type = type_;
4508        0
4509    } else { EINVAL }
4510}
4511#[no_mangle]
4512pub unsafe extern "C" fn pthread_testcancel() {
4513    if let Some(slot) = find_thread() {
4514        if slot.cancel != 0 && slot.cancel_state == PTHREAD_CANCEL_ENABLE {
4515            do_cancel();
4516        }
4517    }
4518}
4519
4520#[no_mangle]
4521pub unsafe extern "C" fn _pthread_cleanup_push(cb: *mut __ptcb, f: Option<unsafe extern "C" fn(*mut c_void)>, x: *mut c_void) {
4522    (*cb).__f = f;
4523    (*cb).__x = x;
4524    if let Some(slot) = find_thread() {
4525        (*cb).__next = slot.cancelbuf;
4526        slot.cancelbuf = cb;
4527    } else {
4528        (*cb).__next = core::ptr::null_mut();
4529    }
4530}
4531
4532#[no_mangle]
4533pub unsafe extern "C" fn _pthread_cleanup_pop(cb: *mut __ptcb, run: c_int) {
4534    if let Some(slot) = find_thread() {
4535        slot.cancelbuf = (*cb).__next;
4536    }
4537    if run != 0 {
4538        if let Some(f) = (*cb).__f {
4539            f((*cb).__x);
4540        }
4541    }
4542}
4543
4544#[no_mangle]
4545pub unsafe extern "C" fn pthread_kill(thread: PthreadT, sig: c_int) -> c_int {
4546    let slot = thread as *mut Thread;
4547    if slot.is_null() { return EINVAL; }
4548    let tid = (*slot).tid;
4549    if tid <= 0 { return EINVAL; }
4550    if sys_tgkill(sys_getpid() as c_int, tid, sig) < 0 { -1 } else { 0 }
4551}
4552
4553#[no_mangle]
4554pub unsafe extern "C" fn pthread_sigmask(how: c_int, set: *const SigSetT, oldset: *mut SigSetT) -> c_int {
4555    // POSIX pthread functions return the error number itself, not -1/errno.
4556    if sigprocmask(how, set, oldset) < 0 { ERRNO!() } else { 0 }
4557}
4558
4559
4560#[repr(C)]
4561pub struct lconv {
4562    pub decimal_point: *mut c_char,
4563    pub thousands_sep: *mut c_char,
4564    pub grouping: *mut c_char,
4565    pub int_curr_symbol: *mut c_char,
4566    pub currency_symbol: *mut c_char,
4567    pub mon_decimal_point: *mut c_char,
4568    pub mon_thousands_sep: *mut c_char,
4569    pub mon_grouping: *mut c_char,
4570    pub positive_sign: *mut c_char,
4571    pub negative_sign: *mut c_char,
4572    pub int_frac_digits: c_char,
4573    pub frac_digits: c_char,
4574    pub p_cs_precedes: c_char,
4575    pub p_sep_by_space: c_char,
4576    pub n_cs_precedes: c_char,
4577    pub n_sep_by_space: c_char,
4578    pub p_sign_posn: c_char,
4579    pub n_sign_posn: c_char,
4580    pub int_p_cs_precedes: c_char,
4581    pub int_p_sep_by_space: c_char,
4582    pub int_n_cs_precedes: c_char,
4583    pub int_n_sep_by_space: c_char,
4584    pub int_p_sign_posn: c_char,
4585    pub int_n_sign_posn: c_char,
4586}
4587
4588static UTF8_NAME: [u8; 6] = [b'U', b'T', b'F', b'-', b'8', 0];
4589static C_NAME: [u8; 2] = [b'C', 0];
4590static mut LOCALE_NAME: *const c_char = C_NAME.as_ptr() as *const c_char;
4591static mut LOCALE_CTYPE_UTF8: bool = true;
4592static mut EMPTY_STR: [c_char; 1] = [0];
4593static mut DECIMAL_POINT: [c_char; 2] = [b'.' as c_char, 0];
4594static mut LCONV: lconv = lconv {
4595    decimal_point: core::ptr::null_mut(),
4596    thousands_sep: core::ptr::null_mut(),
4597    grouping: core::ptr::null_mut(),
4598    int_curr_symbol: core::ptr::null_mut(),
4599    currency_symbol: core::ptr::null_mut(),
4600    mon_decimal_point: core::ptr::null_mut(),
4601    mon_thousands_sep: core::ptr::null_mut(),
4602    mon_grouping: core::ptr::null_mut(),
4603    positive_sign: core::ptr::null_mut(),
4604    negative_sign: core::ptr::null_mut(),
4605    int_frac_digits: (-1i32) as c_char,
4606    frac_digits: (-1i32) as c_char,
4607    p_cs_precedes: (-1i32) as c_char,
4608    p_sep_by_space: (-1i32) as c_char,
4609    n_cs_precedes: (-1i32) as c_char,
4610    n_sep_by_space: (-1i32) as c_char,
4611    p_sign_posn: (-1i32) as c_char,
4612    n_sign_posn: (-1i32) as c_char,
4613    int_p_cs_precedes: (-1i32) as c_char,
4614    int_p_sep_by_space: (-1i32) as c_char,
4615    int_n_cs_precedes: (-1i32) as c_char,
4616    int_n_sep_by_space: (-1i32) as c_char,
4617    int_p_sign_posn: (-1i32) as c_char,
4618    int_n_sign_posn: (-1i32) as c_char,
4619};
4620
4621unsafe fn cstr_contains_ci(s: *const u8, needle: &[u8]) -> bool {
4622    let len = strlen(s as *const c_char) as usize;
4623    let s_slice = core::slice::from_raw_parts(s, len);
4624    if needle.len() > len { return false; }
4625    for i in 0..=len - needle.len() {
4626        if s_slice[i..i + needle.len()].eq_ignore_ascii_case(needle) {
4627            return true;
4628        }
4629    }
4630    false
4631}
4632
4633#[no_mangle]
4634pub unsafe extern "C" fn setlocale(_category: c_int, locale: *const c_char) -> *mut c_char {
4635    if locale.is_null() || *locale == 0 {
4636        return LOCALE_NAME as *mut c_char;
4637    }
4638    let name = locale as *const u8;
4639    if strcmp(name, b"C\0".as_ptr()) == 0 || strcmp(name, b"POSIX\0".as_ptr()) == 0 {
4640        LOCALE_CTYPE_UTF8 = false;
4641        return LOCALE_NAME as *mut c_char;
4642    }
4643    if cstr_contains_ci(name, b"UTF-8") || cstr_contains_ci(name, b"UTF8") {
4644        LOCALE_CTYPE_UTF8 = true;
4645        return LOCALE_NAME as *mut c_char;
4646    }
4647    core::ptr::null_mut()
4648}
4649
4650#[no_mangle]
4651pub unsafe extern "C" fn localeconv() -> *mut lconv {
4652    let empty = core::ptr::addr_of_mut!(EMPTY_STR) as *mut c_char;
4653    let lconv = core::ptr::addr_of_mut!(LCONV);
4654    (*lconv).decimal_point = core::ptr::addr_of_mut!(DECIMAL_POINT) as *mut c_char;
4655    (*lconv).thousands_sep = empty;
4656    (*lconv).grouping = empty;
4657    (*lconv).int_curr_symbol = empty;
4658    (*lconv).currency_symbol = empty;
4659    (*lconv).mon_decimal_point = empty;
4660    (*lconv).mon_thousands_sep = empty;
4661    (*lconv).mon_grouping = empty;
4662    (*lconv).positive_sign = empty;
4663    (*lconv).negative_sign = empty;
4664    lconv
4665}
4666
4667pub type locale_t = *mut c_void;
4668static mut CURRENT_LOCALE: locale_t = LC_GLOBAL_LOCALE;
4669
4670static mut C_LOCALE_STORAGE: c_int = 0;
4671const C_LOCALE: locale_t = core::ptr::addr_of_mut!(C_LOCALE_STORAGE) as locale_t;
4672const LC_GLOBAL_LOCALE: locale_t = usize::MAX as locale_t;
4673
4674#[no_mangle]
4675pub unsafe extern "C" fn newlocale(_mask: c_int, name: *const c_char, base: locale_t) -> locale_t {
4676    if !name.is_null() && *name != 0 {
4677        let n = name as *const u8;
4678        if strcmp(n, b"C\0".as_ptr()) != 0
4679            && strcmp(n, b"POSIX\0".as_ptr()) != 0
4680        {
4681            return core::ptr::null_mut();
4682        }
4683    }
4684    if base.is_null() || base == C_LOCALE || base == LC_GLOBAL_LOCALE {
4685        C_LOCALE
4686    } else {
4687        core::ptr::null_mut()
4688    }
4689}
4690
4691#[no_mangle]
4692pub unsafe extern "C" fn freelocale(_loc: locale_t) {}
4693
4694#[no_mangle]
4695pub unsafe extern "C" fn uselocale(loc: locale_t) -> locale_t {
4696    let old = CURRENT_LOCALE;
4697    if !loc.is_null() {
4698        CURRENT_LOCALE = loc;
4699    }
4700    old
4701}
4702
4703#[no_mangle]
4704pub unsafe extern "C" fn duplocale(loc: locale_t) -> locale_t {
4705    if loc.is_null() {
4706        return core::ptr::null_mut();
4707    }
4708    C_LOCALE
4709}
4710
4711const NL_ITEM_CODESET: c_int = 14;
4712const NL_ITEM_RADIXCHAR: c_int = 0x10000;
4713const NL_ITEM_THOUSEP: c_int = 0x10001;
4714const NL_ITEM_YESEXPR: c_int = 0x50000;
4715const NL_ITEM_NOEXPR: c_int = 0x50001;
4716
4717const C_TIME_STRINGS: &[u8] = b"Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat\0\
4718Sunday\0Monday\0Tuesday\0Wednesday\0Thursday\0Friday\0Saturday\0\
4719Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec\0\
4720January\0February\0March\0April\0May\0June\0July\0August\0\
4721September\0October\0November\0December\0\
4722AM\0PM\0\
4723%a %b %e %T %Y\0%m/%d/%y\0%H:%M:%S\0%I:%M:%S %p\0\
4724\0\0%m/%d/%y\00123456789\0%a %b %e %T %Y\0%H:%M:%S\0";
4725
4726const C_NUMERIC_STRINGS: &[u8] = b".\0\0";
4727const C_MESSAGES_STRINGS: &[u8] = b"^[yY]\0^[nN]\0";
4728
4729unsafe fn langinfo_str(table: *const u8, mut idx: c_int) -> *mut c_char {
4730    let mut p = table;
4731    while idx > 0 {
4732        while *p != 0 { p = p.add(1); }
4733        p = p.add(1);
4734        idx -= 1;
4735    }
4736    p as *mut c_char
4737}
4738
4739#[no_mangle]
4740pub unsafe extern "C" fn nl_langinfo(item: c_int) -> *mut c_char {
4741    if item == NL_ITEM_CODESET {
4742        return if LOCALE_CTYPE_UTF8 {
4743            b"UTF-8\0".as_ptr() as *mut c_char
4744        } else {
4745            b"US-ASCII\0".as_ptr() as *mut c_char
4746        };
4747    }
4748    let cat = item >> 16;
4749    let idx = item & 0xFFFF;
4750    match cat {
4751        1 => {
4752            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
4753            langinfo_str(C_NUMERIC_STRINGS.as_ptr(), idx)
4754        }
4755        2 => {
4756            if idx > 49 { return b"\0".as_ptr() as *mut c_char; }
4757            langinfo_str(C_TIME_STRINGS.as_ptr(), idx)
4758        }
4759        5 => {
4760            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
4761            langinfo_str(C_MESSAGES_STRINGS.as_ptr(), idx)
4762        }
4763        _ => b"\0".as_ptr() as *mut c_char,
4764    }
4765}
4766
4767pub type nl_catd = *mut c_void;
4768
4769#[no_mangle]
4770pub unsafe extern "C" fn catopen(_name: *const c_char, _oflag: c_int) -> nl_catd {
4771    !0usize as nl_catd
4772}
4773
4774#[no_mangle]
4775pub unsafe extern "C" fn catclose(_catd: nl_catd) -> c_int { 0 }
4776
4777#[no_mangle]
4778pub unsafe extern "C" fn catgets(catd: nl_catd, _set_id: c_int, _msg_id: c_int, s: *const c_char) -> *mut c_char {
4779    if catd == !0usize as nl_catd { return s as *mut c_char; }
4780    s as *mut c_char
4781}
4782
4783pub type IconvT = *mut c_void;
4784
4785const ENC_UTF8: i32 = 1;
4786const ENC_UTF16LE: i32 = 2;
4787const ENC_UTF16BE: i32 = 3;
4788const ENC_UTF32LE: i32 = 4;
4789const ENC_UTF32BE: i32 = 5;
4790const ENC_WCHAR_T: i32 = 6;
4791const ENC_ASCII: i32 = 7;
4792const ENC_LATIN1: i32 = 8;
4793const ENC_WIN1252: i32 = 9;
4794const ENC_WIN1251: i32 = 10;
4795const ENC_KOI8R: i32 = 11;
4796const ENC_GBK: i32 = 12;
4797const ENC_GB2312: i32 = 13;
4798const ENC_BIG5: i32 = 14;
4799const ENC_EUCJP: i32 = 15;
4800const ENC_SHIFTJIS: i32 = 16;
4801const ENC_ISO8859_2: i32 = 17;
4802const ENC_ISO8859_3: i32 = 18;
4803const ENC_ISO8859_4: i32 = 19;
4804const ENC_ISO8859_5: i32 = 20;
4805const ENC_ISO8859_6: i32 = 21;
4806const ENC_ISO8859_7: i32 = 22;
4807const ENC_ISO8859_8: i32 = 23;
4808const ENC_ISO8859_9: i32 = 24;
4809const ENC_ISO8859_10: i32 = 25;
4810const ENC_ISO8859_11: i32 = 26;
4811const ENC_ISO8859_13: i32 = 27;
4812const ENC_ISO8859_14: i32 = 28;
4813const ENC_ISO8859_15: i32 = 29;
4814const ENC_ISO8859_16: i32 = 30;
4815
4816include!("iconv_iso8859.rs");
4817
4818fn make_cd(from: i32, to: i32) -> IconvT {
4819    ((from as usize) << 16 | (to as usize) << 1 | 1) as IconvT
4820}
4821fn extract_from(cd: IconvT) -> i32 {
4822    ((cd as usize) >> 16) as i32
4823}
4824fn extract_to(cd: IconvT) -> i32 {
4825    (((cd as usize) >> 1) & 0x7fff) as i32
4826}
4827
4828unsafe fn match_name(input: *const u8, target: &[u8]) -> bool {
4829    let mut i = input;
4830    let mut j = 0;
4831    while *i != 0 && j < target.len() {
4832        let mut c = *i;
4833        if !c.is_ascii_alphanumeric() { i = i.add(1); continue; }
4834        c = c.to_ascii_lowercase();
4835        if c != target[j] { return false; }
4836        i = i.add(1);
4837        j += 1;
4838    }
4839    while *i != 0 && !(*i).is_ascii_alphanumeric() { i = i.add(1); }
4840    *i == 0 && j == target.len()
4841}
4842
4843unsafe fn find_encoding(name: *const u8) -> i32 {
4844    if name.is_null() { return -1; }
4845    if match_name(name, b"utf8") || match_name(name, b"utf-8") || match_name(name, b"char") { return ENC_UTF8; }
4846    if match_name(name, b"utf16le") || match_name(name, b"utf-16le") { return ENC_UTF16LE; }
4847    if match_name(name, b"utf16be") || match_name(name, b"utf-16be") { return ENC_UTF16BE; }
4848    if match_name(name, b"utf32le") || match_name(name, b"utf-32le") || match_name(name, b"ucs4le") { return ENC_UTF32LE; }
4849    if match_name(name, b"utf32be") || match_name(name, b"utf-32be") || match_name(name, b"ucs4be") { return ENC_UTF32BE; }
4850    if match_name(name, b"wchart") || match_name(name, b"wchar-t") { return ENC_WCHAR_T; }
4851    if match_name(name, b"ascii") || match_name(name, b"usascii") || match_name(name, b"iso646") { return ENC_ASCII; }
4852    if match_name(name, b"iso88591") || match_name(name, b"iso-8859-1") || match_name(name, b"latin1") { return ENC_LATIN1; }
4853    if match_name(name, b"iso88592") || match_name(name, b"iso-8859-2") { return ENC_ISO8859_2; }
4854    if match_name(name, b"iso88593") || match_name(name, b"iso-8859-3") { return ENC_ISO8859_3; }
4855    if match_name(name, b"iso88594") || match_name(name, b"iso-8859-4") { return ENC_ISO8859_4; }
4856    if match_name(name, b"iso88595") || match_name(name, b"iso-8859-5") { return ENC_ISO8859_5; }
4857    if match_name(name, b"iso88596") || match_name(name, b"iso-8859-6") { return ENC_ISO8859_6; }
4858    if match_name(name, b"iso88597") || match_name(name, b"iso-8859-7") { return ENC_ISO8859_7; }
4859    if match_name(name, b"iso88598") || match_name(name, b"iso-8859-8") { return ENC_ISO8859_8; }
4860    if match_name(name, b"iso88599") || match_name(name, b"iso-8859-9") { return ENC_ISO8859_9; }
4861    if match_name(name, b"iso885910") || match_name(name, b"iso-8859-10") { return ENC_ISO8859_10; }
4862    if match_name(name, b"iso885911") || match_name(name, b"iso-8859-11") || match_name(name, b"tis620") { return ENC_ISO8859_11; }
4863    if match_name(name, b"iso885913") || match_name(name, b"iso-8859-13") { return ENC_ISO8859_13; }
4864    if match_name(name, b"iso885914") || match_name(name, b"iso-8859-14") { return ENC_ISO8859_14; }
4865    if match_name(name, b"iso885915") || match_name(name, b"iso-8859-15") { return ENC_ISO8859_15; }
4866    if match_name(name, b"iso885916") || match_name(name, b"iso-8859-16") { return ENC_ISO8859_16; }
4867    if match_name(name, b"cp1252") || match_name(name, b"windows1252") || match_name(name, b"windows-1252") { return ENC_WIN1252; }
4868    if match_name(name, b"cp1251") || match_name(name, b"windows1251") || match_name(name, b"windows-1251") { return ENC_WIN1251; }
4869    if match_name(name, b"koi8r") || match_name(name, b"koi8-r") { return ENC_KOI8R; }
4870    if match_name(name, b"gbk") || match_name(name, b"cp936") { return ENC_GBK; }
4871    if match_name(name, b"gb2312") { return ENC_GB2312; }
4872    if match_name(name, b"big5") || match_name(name, b"bigfive") || match_name(name, b"cp950") { return ENC_BIG5; }
4873    if match_name(name, b"eucjp") || match_name(name, b"euc-jp") { return ENC_EUCJP; }
4874    if match_name(name, b"shiftjis") || match_name(name, b"sjis") || match_name(name, b"cp932") { return ENC_SHIFTJIS; }
4875    -1
4876}
4877
4878fn uni_to_jis(c: u32) -> u16 {
4879    let mut b = 0usize;
4880    let mut nel = REV_JIS.len();
4881    loop {
4882        let i = nel / 2;
4883        let j = REV_JIS[b + i] as usize;
4884        let row = j / 256;
4885        let col = j % 256;
4886        let d = JIS0208[row * 94 + col] as u32;
4887        if d == c { return (j as u16) + 0x2121; }
4888        if nel == 1 { return 0; }
4889        if c < d { nel /= 2; }
4890        else { b += i; nel -= nel / 2; }
4891    }
4892}
4893
4894unsafe fn iconv_decode(enc: i32, src: *const u8, src_left: usize) -> (u32, usize, c_int) {
4895    if src_left == 0 { return (0, 0, EINVAL); }
4896    match enc {
4897        ENC_UTF8 => {
4898            let c = *src;
4899            if c < 128 { return (c as u32, 1, 0); }
4900            if c < 0xC2 { return (0, 0, EILSEQ); }
4901            if c < 0xE0 {
4902                if src_left < 2 || (*src.add(1) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
4903                return (((c as u32 & 0x1F) << 6) | (*src.add(1) as u32 & 0x3F), 2, 0);
4904            }
4905            if c < 0xF0 {
4906                if src_left < 3 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
4907                let cp = ((c as u32 & 0x0F) << 12) | ((*src.add(1) as u32 & 0x3F) << 6) | (*src.add(2) as u32 & 0x3F);
4908                if cp < 0x800 { return (0, 0, EILSEQ); }
4909                return (cp, 3, 0);
4910            }
4911            if c < 0xF8 {
4912                if src_left < 4 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 || (*src.add(3) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
4913                let cp = ((c as u32 & 0x07) << 18) | ((*src.add(1) as u32 & 0x3F) << 12) | ((*src.add(2) as u32 & 0x3F) << 6) | (*src.add(3) as u32 & 0x3F);
4914                if cp < 0x10000 || cp >= 0x110000 { return (0, 0, EILSEQ); }
4915                return (cp, 4, 0);
4916            }
4917            (0, 0, EILSEQ)
4918        }
4919        ENC_UTF16LE => {
4920            if src_left < 2 { return (0, 0, EINVAL); }
4921            let c = (*src as u32) | ((*src.add(1) as u32) << 8);
4922            if c >= 0xD800 && c <= 0xDBFF {
4923                if src_left < 4 { return (0, 0, EINVAL); }
4924                let d = (*src.add(2) as u32) | ((*src.add(3) as u32) << 8);
4925                if d < 0xDC00 || d > 0xDFFF { return (0, 0, EILSEQ); }
4926                return (((c - 0xD800) << 10) + (d - 0xDC00) + 0x10000, 4, 0);
4927            }
4928            if c >= 0xDC00 && c <= 0xDFFF { return (0, 0, EILSEQ); }
4929            (c, 2, 0)
4930        }
4931        ENC_UTF16BE => {
4932            if src_left < 2 { return (0, 0, EINVAL); }
4933            let c = ((*src as u32) << 8) | (*src.add(1) as u32);
4934            if c >= 0xD800 && c <= 0xDBFF {
4935                if src_left < 4 { return (0, 0, EINVAL); }
4936                let d = ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
4937                if d < 0xDC00 || d > 0xDFFF { return (0, 0, EILSEQ); }
4938                return (((c - 0xD800) << 10) + (d - 0xDC00) + 0x10000, 4, 0);
4939            }
4940            if c >= 0xDC00 && c <= 0xDFFF { return (0, 0, EILSEQ); }
4941            (c, 2, 0)
4942        }
4943        ENC_UTF32LE => {
4944            if src_left < 4 { return (0, 0, EINVAL); }
4945            let c = (*src as u32) | ((*src.add(1) as u32) << 8) | ((*src.add(2) as u32) << 16) | ((*src.add(3) as u32) << 24);
4946            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
4947            if c >= 0x110000 { return (0, 0, EILSEQ); }
4948            (c, 4, 0)
4949        }
4950        ENC_UTF32BE => {
4951            if src_left < 4 { return (0, 0, EINVAL); }
4952            let c = ((*src as u32) << 24) | ((*src.add(1) as u32) << 16) | ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
4953            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
4954            if c >= 0x110000 { return (0, 0, EILSEQ); }
4955            (c, 4, 0)
4956        }
4957        ENC_WCHAR_T => {
4958            if src_left < 4 { return (0, 0, EINVAL); }
4959            let c = *(src as *const u32);
4960            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
4961            if c >= 0x110000 { return (0, 0, EILSEQ); }
4962            (c, 4, 0)
4963        }
4964        ENC_ASCII => {
4965            let c = *src as u32;
4966            if c >= 128 { return (0, 0, EILSEQ); }
4967            (c, 1, 0)
4968        }
4969        ENC_LATIN1 => (*src as u32, 1, 0),
4970        ENC_ISO8859_2 => (iso8859_to_u(&ISO8859_2_TO_U, *src), 1, 0),
4971        ENC_ISO8859_3 => (iso8859_to_u(&ISO8859_3_TO_U, *src), 1, 0),
4972        ENC_ISO8859_4 => (iso8859_to_u(&ISO8859_4_TO_U, *src), 1, 0),
4973        ENC_ISO8859_5 => (iso8859_to_u(&ISO8859_5_TO_U, *src), 1, 0),
4974        ENC_ISO8859_6 => (iso8859_to_u(&ISO8859_6_TO_U, *src), 1, 0),
4975        ENC_ISO8859_7 => (iso8859_to_u(&ISO8859_7_TO_U, *src), 1, 0),
4976        ENC_ISO8859_8 => (iso8859_to_u(&ISO8859_8_TO_U, *src), 1, 0),
4977        ENC_ISO8859_9 => (iso8859_to_u(&ISO8859_9_TO_U, *src), 1, 0),
4978        ENC_ISO8859_10 => (iso8859_to_u(&ISO8859_10_TO_U, *src), 1, 0),
4979        ENC_ISO8859_11 => (iso8859_to_u(&ISO8859_11_TO_U, *src), 1, 0),
4980        ENC_ISO8859_13 => (iso8859_to_u(&ISO8859_13_TO_U, *src), 1, 0),
4981        ENC_ISO8859_14 => (iso8859_to_u(&ISO8859_14_TO_U, *src), 1, 0),
4982        ENC_ISO8859_15 => (iso8859_to_u(&ISO8859_15_TO_U, *src), 1, 0),
4983        ENC_ISO8859_16 => (iso8859_to_u(&ISO8859_16_TO_U, *src), 1, 0),
4984        ENC_WIN1252 => {
4985            let b = *src;
4986            if b < 128 { return (b as u32, 1, 0); }
4987            (WIN1252_TO_U[b as usize - 128], 1, 0)
4988        }
4989        ENC_WIN1251 => {
4990            let b = *src;
4991            if b < 128 { return (b as u32, 1, 0); }
4992            (WIN1251_TO_U[b as usize - 128], 1, 0)
4993        }
4994        ENC_KOI8R => {
4995            let b = *src;
4996            if b < 128 { return (b as u32, 1, 0); }
4997            (KOI8R_TO_U[b as usize - 128], 1, 0)
4998        }
4999        ENC_GBK | ENC_GB2312 => {
5000            let c = *src;
5001            if c < 128 { return (c as u32, 1, 0); }
5002            if c == 128 { return (0x20AC, 1, 0); }
5003            if src_left < 2 { return (0, 0, EINVAL); }
5004            let d = *src.add(1);
5005            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
5006            let row = (c as usize).wrapping_sub(0x81);
5007            if row >= 126 { return (0, 0, EILSEQ); }
5008            let mut col = (d as usize) - 0x40;
5009            if col > 63 { col -= 1; }
5010            let cp = GB18030_TABLE[row * 190 + col] as u32;
5011            if cp == 0 { return (0, 0, EILSEQ); }
5012            (cp, 2, 0)
5013        }
5014        ENC_BIG5 => {
5015            let c = *src;
5016            if c < 128 { return (c as u32, 1, 0); }
5017            if src_left < 2 { return (0, 0, EINVAL); }
5018            let d = *src.add(1);
5019            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
5020            let mut col = (d as usize) - 0x40;
5021            if col > 0x3E { col -= 0x22; }
5022            if c >= 0xA1 && c < 0xFA {
5023                let row = (c as usize) - 0xA1;
5024                if row >= 89 { return (0, 0, EILSEQ); }
5025                let cp = BIG5_TABLE[row * 157 + col] as u32;
5026                if cp == 0 { return (0, 0, EILSEQ); }
5027                return (cp, 2, 0);
5028            }
5029            (0, 0, EILSEQ)
5030        }
5031        ENC_EUCJP => {
5032            let c = *src;
5033            if c < 128 { return (c as u32, 1, 0); }
5034            if c == 0x8E {
5035                if src_left < 2 { return (0, 0, EINVAL); }
5036                let d = *src.add(1);
5037                if d < 0xA1 || d > 0xDF { return (0, 0, EILSEQ); }
5038                return ((d as u32) + 0xFF61 - 0xA1, 2, 0);
5039            }
5040            if c < 0xA1 { return (0, 0, EILSEQ); }
5041            if src_left < 2 { return (0, 0, EINVAL); }
5042            let d = *src.add(1);
5043            if d < 0xA1 || d > 0xFE { return (0, 0, EILSEQ); }
5044            let row = (c as usize) - 0xA1;
5045            let col = (d as usize) - 0xA1;
5046            if row >= 84 || col >= 94 { return (0, 0, EILSEQ); }
5047            let cp = JIS0208[row * 94 + col] as u32;
5048            if cp == 0 { return (0, 0, EILSEQ); }
5049            (cp, 2, 0)
5050        }
5051        ENC_SHIFTJIS => {
5052            let c = *src;
5053            if c < 128 { return (c as u32, 1, 0); }
5054            if c >= 0xA1 && c <= 0xDF { return ((c as u32) + 0xFF61 - 0xA1, 1, 0); }
5055            if src_left < 2 { return (0, 0, EINVAL); }
5056            let d = *src.add(1);
5057            if d < 0x40 || d == 0x7F || d > 0xFC { return (0, 0, EILSEQ); }
5058            let row = if c >= 129 && c <= 159 { (c as usize) - 129 }
5059                      else if c >= 224 && c <= 239 { (c as usize) - 193 }
5060                      else { return (0, 0, EILSEQ); };
5061            let (col, row_adj) = if d >= 64 && d <= 158 && d != 127 {
5062                let mut dd = d as usize;
5063                if dd > 127 { dd -= 1; }
5064                (dd - 64, row * 2)
5065            } else if d >= 159 && d <= 252 {
5066                ((d as usize) - 159, row * 2 + 1)
5067            } else {
5068                return (0, 0, EILSEQ);
5069            };
5070            if row_adj >= 84 { return (0, 0, EILSEQ); }
5071            let cp = JIS0208[row_adj * 94 + col] as u32;
5072            if cp == 0 { return (0, 0, EILSEQ); }
5073            (cp, 2, 0)
5074        }
5075        _ => (0, 0, EILSEQ),
5076    }
5077}
5078
5079unsafe fn iconv_encode(enc: i32, c: u32, dst: *mut u8, dst_left: usize) -> (usize, c_int) {
5080    match enc {
5081        ENC_UTF8 => {
5082            if c < 0x80 {
5083                if dst_left < 1 { return (0, E2BIG); }
5084                *dst = c as u8; return (1, 0);
5085            }
5086            if c < 0x800 {
5087                if dst_left < 2 { return (0, E2BIG); }
5088                *dst = (0xC0 | (c >> 6)) as u8;
5089                *dst.add(1) = (0x80 | (c & 0x3F)) as u8;
5090                return (2, 0);
5091            }
5092            if c < 0x10000 {
5093                if dst_left < 3 { return (0, E2BIG); }
5094                *dst = (0xE0 | (c >> 12)) as u8;
5095                *dst.add(1) = (0x80 | ((c >> 6) & 0x3F)) as u8;
5096                *dst.add(2) = (0x80 | (c & 0x3F)) as u8;
5097                return (3, 0);
5098            }
5099            if dst_left < 4 { return (0, E2BIG); }
5100            *dst = (0xF0 | (c >> 18)) as u8;
5101            *dst.add(1) = (0x80 | ((c >> 12) & 0x3F)) as u8;
5102            *dst.add(2) = (0x80 | ((c >> 6) & 0x3F)) as u8;
5103            *dst.add(3) = (0x80 | (c & 0x3F)) as u8;
5104            (4, 0)
5105        }
5106        ENC_UTF16LE => {
5107            if c < 0x10000 {
5108                if dst_left < 2 { return (0, E2BIG); }
5109                *dst = (c & 0xFF) as u8;
5110                *dst.add(1) = (c >> 8) as u8;
5111                return (2, 0);
5112            }
5113            if dst_left < 4 { return (0, E2BIG); }
5114            let c = c - 0x10000;
5115            let hi = ((c >> 10) + 0xD800) as u16;
5116            let lo = ((c & 0x3FF) + 0xDC00) as u16;
5117            *dst = (hi & 0xFF) as u8; *dst.add(1) = (hi >> 8) as u8;
5118            *dst.add(2) = (lo & 0xFF) as u8; *dst.add(3) = (lo >> 8) as u8;
5119            (4, 0)
5120        }
5121        ENC_UTF16BE => {
5122            if c < 0x10000 {
5123                if dst_left < 2 { return (0, E2BIG); }
5124                *dst = (c >> 8) as u8;
5125                *dst.add(1) = (c & 0xFF) as u8;
5126                return (2, 0);
5127            }
5128            if dst_left < 4 { return (0, E2BIG); }
5129            let c = c - 0x10000;
5130            let hi = ((c >> 10) + 0xD800) as u16;
5131            let lo = ((c & 0x3FF) + 0xDC00) as u16;
5132            *dst = (hi >> 8) as u8; *dst.add(1) = (hi & 0xFF) as u8;
5133            *dst.add(2) = (lo >> 8) as u8; *dst.add(3) = (lo & 0xFF) as u8;
5134            (4, 0)
5135        }
5136        ENC_UTF32LE => {
5137            if dst_left < 4 { return (0, E2BIG); }
5138            *dst = (c & 0xFF) as u8; *dst.add(1) = ((c >> 8) & 0xFF) as u8;
5139            *dst.add(2) = ((c >> 16) & 0xFF) as u8; *dst.add(3) = (c >> 24) as u8;
5140            (4, 0)
5141        }
5142        ENC_UTF32BE => {
5143            if dst_left < 4 { return (0, E2BIG); }
5144            *dst = (c >> 24) as u8; *dst.add(1) = ((c >> 16) & 0xFF) as u8;
5145            *dst.add(2) = ((c >> 8) & 0xFF) as u8; *dst.add(3) = (c & 0xFF) as u8;
5146            (4, 0)
5147        }
5148        ENC_WCHAR_T => {
5149            if dst_left < 4 { return (0, E2BIG); }
5150            *(dst as *mut u32) = c;
5151            (4, 0)
5152        }
5153        ENC_ASCII => {
5154            if c < 128 {
5155                if dst_left < 1 { return (0, E2BIG); }
5156                *dst = c as u8; return (1, 0);
5157            }
5158            (0, EILSEQ)
5159        }
5160        ENC_LATIN1 => {
5161            if c < 256 {
5162                if dst_left < 1 { return (0, E2BIG); }
5163                *dst = c as u8; return (1, 0);
5164            }
5165            (0, EILSEQ)
5166        }
5167        ENC_ISO8859_2 => {
5168            if let Some(b) = u_to_iso8859(&ISO8859_2_TO_U, c) {
5169                if dst_left < 1 { return (0, E2BIG); }
5170                *dst = b; return (1, 0);
5171            }
5172            (0, EILSEQ)
5173        }
5174        ENC_ISO8859_3 => {
5175            if let Some(b) = u_to_iso8859(&ISO8859_3_TO_U, c) {
5176                if dst_left < 1 { return (0, E2BIG); }
5177                *dst = b; return (1, 0);
5178            }
5179            (0, EILSEQ)
5180        }
5181        ENC_ISO8859_4 => {
5182            if let Some(b) = u_to_iso8859(&ISO8859_4_TO_U, c) {
5183                if dst_left < 1 { return (0, E2BIG); }
5184                *dst = b; return (1, 0);
5185            }
5186            (0, EILSEQ)
5187        }
5188        ENC_ISO8859_5 => {
5189            if let Some(b) = u_to_iso8859(&ISO8859_5_TO_U, c) {
5190                if dst_left < 1 { return (0, E2BIG); }
5191                *dst = b; return (1, 0);
5192            }
5193            (0, EILSEQ)
5194        }
5195        ENC_ISO8859_6 => {
5196            if let Some(b) = u_to_iso8859(&ISO8859_6_TO_U, c) {
5197                if dst_left < 1 { return (0, E2BIG); }
5198                *dst = b; return (1, 0);
5199            }
5200            (0, EILSEQ)
5201        }
5202        ENC_ISO8859_7 => {
5203            if let Some(b) = u_to_iso8859(&ISO8859_7_TO_U, c) {
5204                if dst_left < 1 { return (0, E2BIG); }
5205                *dst = b; return (1, 0);
5206            }
5207            (0, EILSEQ)
5208        }
5209        ENC_ISO8859_8 => {
5210            if let Some(b) = u_to_iso8859(&ISO8859_8_TO_U, c) {
5211                if dst_left < 1 { return (0, E2BIG); }
5212                *dst = b; return (1, 0);
5213            }
5214            (0, EILSEQ)
5215        }
5216        ENC_ISO8859_9 => {
5217            if let Some(b) = u_to_iso8859(&ISO8859_9_TO_U, c) {
5218                if dst_left < 1 { return (0, E2BIG); }
5219                *dst = b; return (1, 0);
5220            }
5221            (0, EILSEQ)
5222        }
5223        ENC_ISO8859_10 => {
5224            if let Some(b) = u_to_iso8859(&ISO8859_10_TO_U, c) {
5225                if dst_left < 1 { return (0, E2BIG); }
5226                *dst = b; return (1, 0);
5227            }
5228            (0, EILSEQ)
5229        }
5230        ENC_ISO8859_11 => {
5231            if let Some(b) = u_to_iso8859(&ISO8859_11_TO_U, c) {
5232                if dst_left < 1 { return (0, E2BIG); }
5233                *dst = b; return (1, 0);
5234            }
5235            (0, EILSEQ)
5236        }
5237        ENC_ISO8859_13 => {
5238            if let Some(b) = u_to_iso8859(&ISO8859_13_TO_U, c) {
5239                if dst_left < 1 { return (0, E2BIG); }
5240                *dst = b; return (1, 0);
5241            }
5242            (0, EILSEQ)
5243        }
5244        ENC_ISO8859_14 => {
5245            if let Some(b) = u_to_iso8859(&ISO8859_14_TO_U, c) {
5246                if dst_left < 1 { return (0, E2BIG); }
5247                *dst = b; return (1, 0);
5248            }
5249            (0, EILSEQ)
5250        }
5251        ENC_ISO8859_15 => {
5252            if let Some(b) = u_to_iso8859(&ISO8859_15_TO_U, c) {
5253                if dst_left < 1 { return (0, E2BIG); }
5254                *dst = b; return (1, 0);
5255            }
5256            (0, EILSEQ)
5257        }
5258        ENC_ISO8859_16 => {
5259            if let Some(b) = u_to_iso8859(&ISO8859_16_TO_U, c) {
5260                if dst_left < 1 { return (0, E2BIG); }
5261                *dst = b; return (1, 0);
5262            }
5263            (0, EILSEQ)
5264        }
5265        ENC_WIN1252 => {
5266            if c < 128 {
5267                if dst_left < 1 { return (0, E2BIG); }
5268                *dst = c as u8; return (1, 0);
5269            }
5270            if c >= 0xA0 && c <= 0xFF && WIN1252_TO_U[c as usize - 128] == c {
5271                if dst_left < 1 { return (0, E2BIG); }
5272                *dst = c as u8; return (1, 0);
5273            }
5274            for i in 0..128usize {
5275                if WIN1252_TO_U[i] == c {
5276                    if dst_left < 1 { return (0, E2BIG); }
5277                    *dst = (i + 128) as u8; return (1, 0);
5278                }
5279            }
5280            (0, EILSEQ)
5281        }
5282        ENC_WIN1251 => {
5283            if c < 128 {
5284                if dst_left < 1 { return (0, E2BIG); }
5285                *dst = c as u8; return (1, 0);
5286            }
5287            for i in 0..128usize {
5288                if WIN1251_TO_U[i] == c {
5289                    if dst_left < 1 { return (0, E2BIG); }
5290                    *dst = (i + 128) as u8; return (1, 0);
5291                }
5292            }
5293            (0, EILSEQ)
5294        }
5295        ENC_KOI8R => {
5296            if c < 128 {
5297                if dst_left < 1 { return (0, E2BIG); }
5298                *dst = c as u8; return (1, 0);
5299            }
5300            for i in 0..128usize {
5301                if KOI8R_TO_U[i] == c {
5302                    if dst_left < 1 { return (0, E2BIG); }
5303                    *dst = (i + 128) as u8; return (1, 0);
5304                }
5305            }
5306            (0, EILSEQ)
5307        }
5308        ENC_GBK | ENC_GB2312 => {
5309            if c < 128 {
5310                if dst_left < 1 { return (0, E2BIG); }
5311                *dst = c as u8; return (1, 0);
5312            }
5313            if c == 0x20AC {
5314                if dst_left < 1 { return (0, E2BIG); }
5315                *dst = 128; return (1, 0);
5316            }
5317            for row in 0..126usize {
5318                for col in 0..190usize {
5319                    if GB18030_TABLE[row * 190 + col] as u32 == c {
5320                        if dst_left < 2 { return (0, E2BIG); }
5321                        *dst = (row + 0x81) as u8;
5322                        *dst.add(1) = if col <= 62 { (col + 0x40) as u8 } else { (col + 0x41) as u8 };
5323                        return (2, 0);
5324                    }
5325                }
5326            }
5327            (0, EILSEQ)
5328        }
5329        ENC_BIG5 => {
5330            if c < 128 {
5331                if dst_left < 1 { return (0, E2BIG); }
5332                *dst = c as u8; return (1, 0);
5333            }
5334            for row in 0..89usize {
5335                for col in 0..157usize {
5336                    if BIG5_TABLE[row * 157 + col] as u32 == c {
5337                        if dst_left < 2 { return (0, E2BIG); }
5338                        *dst = (row + 0xA1) as u8;
5339                        *dst.add(1) = if col <= 0x3E { (col + 0x40) as u8 } else { (col + 0x62) as u8 };
5340                        return (2, 0);
5341                    }
5342                }
5343            }
5344            (0, EILSEQ)
5345        }
5346        ENC_EUCJP => {
5347            if c < 128 {
5348                if dst_left < 1 { return (0, E2BIG); }
5349                *dst = c as u8; return (1, 0);
5350            }
5351            if c >= 0xFF61 && c <= 0xFF9F {
5352                if dst_left < 2 { return (0, E2BIG); }
5353                *dst = 0x8E;
5354                *dst.add(1) = (c - 0xFF61 + 0xA1) as u8;
5355                return (2, 0);
5356            }
5357            let jis = uni_to_jis(c);
5358            if jis == 0 { return (0, EILSEQ); }
5359            if dst_left < 2 { return (0, E2BIG); }
5360            *dst = ((jis >> 8) as u8).wrapping_add(0x80);
5361            *dst.add(1) = ((jis & 0xFF) as u8).wrapping_add(0x80);
5362            (2, 0)
5363        }
5364        ENC_SHIFTJIS => {
5365            if c < 128 {
5366                if dst_left < 1 { return (0, E2BIG); }
5367                *dst = c as u8; return (1, 0);
5368            }
5369            if c >= 0xFF61 && c <= 0xFF9F {
5370                if dst_left < 1 { return (0, E2BIG); }
5371                *dst = (c - 0xFF61 + 0xA1) as u8;
5372                return (1, 0);
5373            }
5374            let jis = uni_to_jis(c);
5375            if jis == 0 { return (0, EILSEQ); }
5376            if dst_left < 2 { return (0, E2BIG); }
5377            let r = (jis >> 8) as usize;
5378            let d = (jis & 0xFF) as usize;
5379            *dst = ((r + 1) / 2 + if r < 95 { 112 } else { 176 }) as u8;
5380            *dst.add(1) = if r % 2 == 1 { (d + 31 + d / 96) as u8 } else { (d + 126) as u8 };
5381            (2, 0)
5382        }
5383        _ => (0, EILSEQ),
5384    }
5385}
5386
5387#[no_mangle]
5388pub unsafe extern "C" fn iconv_open(tocode: *const c_char, fromcode: *const c_char) -> IconvT {
5389    let to = find_encoding(tocode as *const u8);
5390    let from = find_encoding(fromcode as *const u8);
5391    if to < 0 || from < 0 {
5392        ERRNO!() = EINVAL;
5393        return !0usize as IconvT;
5394    }
5395    make_cd(from, to)
5396}
5397
5398#[no_mangle]
5399pub unsafe extern "C" fn iconv(
5400    cd: IconvT,
5401    inbuf: *mut *mut c_char,
5402    inbytesleft: *mut SizeT,
5403    outbuf: *mut *mut c_char,
5404    outbytesleft: *mut SizeT,
5405) -> SizeT {
5406    if cd == !0usize as IconvT {
5407        ERRNO!() = EINVAL;
5408        return !0usize;
5409    }
5410    if inbuf.is_null() || outbuf.is_null() { return 0; }
5411    let from = extract_from(cd);
5412    let to = extract_to(cd);
5413    let mut src = *inbuf as *const u8;
5414    let mut dst = *outbuf as *mut u8;
5415    let mut src_left = *inbytesleft;
5416    let mut dst_left = *outbytesleft;
5417    let mut subst = 0usize;
5418    while src_left > 0 {
5419        let (cp, consumed, err) = iconv_decode(from, src, src_left);
5420        if err != 0 {
5421            if err == EINVAL { break; }
5422            ERRNO!() = err;
5423            return !0usize;
5424        }
5425        let (written, err) = iconv_encode(to, cp, dst, dst_left);
5426        if err != 0 {
5427            if err == E2BIG {
5428                ERRNO!() = E2BIG;
5429                return !0usize;
5430            }
5431            if dst_left < 1 {
5432                ERRNO!() = E2BIG;
5433                return !0usize;
5434            }
5435            *dst = b'*';
5436            dst = dst.add(1);
5437            dst_left -= 1;
5438            subst += 1;
5439        } else {
5440            dst = dst.add(written);
5441            dst_left -= written;
5442        }
5443        src = src.add(consumed);
5444        src_left -= consumed;
5445    }
5446    *inbuf = src as *mut c_char;
5447    *outbuf = dst as *mut c_char;
5448    *inbytesleft = src_left;
5449    *outbytesleft = dst_left;
5450    subst
5451}
5452
5453#[no_mangle]
5454pub unsafe extern "C" fn iconv_close(_cd: IconvT) -> c_int { 0 }
5455
5456// ============================================================
5457// Syscall wrappers as public C ABI
5458// ============================================================
5459
5460#[no_mangle]
5461pub unsafe extern "C" fn write(fd: c_int, buf: *const c_void, count: SizeT) -> SSizeT {
5462    syscall_ret(sys_write(fd as i64, buf as *const u8, count)) as SSizeT
5463}
5464
5465#[no_mangle]
5466pub unsafe extern "C" fn read(fd: c_int, buf: *mut c_void, count: SizeT) -> SSizeT {
5467    syscall_ret(sys_read(fd as i64, buf as *mut u8, count)) as SSizeT
5468}
5469
5470#[no_mangle]
5471pub unsafe extern "C" fn open(path: *const c_char, flags: c_int, mode: c_int) -> c_int {
5472    syscall_ret(sys_open(path as *const u8, flags as i64, mode as i64)) as c_int
5473}
5474
5475#[no_mangle]
5476pub unsafe extern "C" fn close(fd: c_int) -> c_int {
5477    syscall_ret(sys_close(fd as i64)) as c_int
5478}
5479
5480#[no_mangle]
5481pub unsafe extern "C" fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64 {
5482    syscall_ret(sys_lseek(fd as i64, offset, whence as i64))
5483}
5484
5485// ============================================================
5486// Additional syscall wrappers for stdio
5487// ============================================================
5488
5489const O_RDONLY: i32 = 0;
5490const O_WRONLY: i32 = 1;
5491const O_RDWR: i32 = 2;
5492const O_CREAT: i32 = 64;
5493const O_TRUNC: i32 = 512;
5494const O_APPEND: i32 = 1024;
5495const O_EXCL: i32 = 128;
5496const O_NONBLOCK: i32 = 2048;
5497const O_NOFOLLOW: i32 = if cfg!(target_arch = "aarch64") { 0o100000 } else { 0o400000 };
5498const O_DIRECTORY: i32 = if cfg!(target_arch = "aarch64") { 0o40000 } else { 0o200000 };
5499const O_CLOEXEC: i32 = 0x80000;
5500
5501const F_GETFD: i32 = 1;
5502const F_SETFD: i32 = 2;
5503const F_GETFL: i32 = 3;
5504const F_SETFL: i32 = 4;
5505const F_GETLK: i32 = 5;
5506const F_SETLK: i32 = 6;
5507const F_SETLKW: i32 = 7;
5508const F_DUPFD: i32 = 0;
5509const F_DUPFD_CLOEXEC: i32 = 1030;
5510const FD_CLOEXEC: i32 = 1;
5511
5512const TIOCGWINSZ: u32 = 0x5413;
5513
5514#[repr(C)]
5515struct winsize {
5516    ws_row: u16,
5517    ws_col: u16,
5518    ws_xpixel: u16,
5519    ws_ypixel: u16,
5520}
5521
5522#[inline]
5523unsafe fn sys_pipe2(fds: *mut c_int, flags: i32) -> i64 {
5524    <Arch as Syscalls>::syscall2(SYS_PIPE2, fds as i64, flags as i64)
5525}
5526
5527#[inline]
5528unsafe fn sys_dup3(oldfd: i32, newfd: i32, flags: i32) -> i64 {
5529    <Arch as Syscalls>::syscall3(SYS_DUP3, oldfd as i64, newfd as i64, flags as i64)
5530}
5531
5532#[inline]
5533unsafe fn sys_fcntl(fd: i32, cmd: i32, arg: i64) -> i64 {
5534    <Arch as Syscalls>::syscall3(SYS_FCNTL, fd as i64, cmd as i64, arg as i64)
5535}
5536
5537#[inline]
5538unsafe fn sys_ioctl(fd: c_int, request: u32, arg: *mut u8) -> i64 {
5539    <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg as i64)
5540}
5541
5542#[inline]
5543unsafe fn sys_unlinkat(dirfd: i32, path: *const u8, flags: i32) -> i64 {
5544    <Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, path as i64, flags as i64)
5545}
5546
5547#[inline]
5548unsafe fn sys_renameat2(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: u32) -> i64 {
5549    <Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
5550}
5551
5552// ============================================================
5553// FILE / stdio (buffered, musl-compatible layout)
5554// ============================================================
5555
5556const UNGET: usize = 8;
5557const F_PERM: u32 = 1;
5558const F_NORD: u32 = 4;
5559const F_NOWR: u32 = 8;
5560const F_EOF: u32 = 16;
5561const F_ERR: u32 = 32;
5562const F_SVB: u32 = 64;
5563const F_APP: u32 = 128;
5564
5565const BUFSIZ: usize = 1024;
5566
5567const _IOFBF: c_int = 0;
5568const _IOLBF: c_int = 1;
5569const _IONBF: c_int = 2;
5570
5571const SEEK_SET: c_int = 0;
5572const SEEK_CUR: c_int = 1;
5573const SEEK_END: c_int = 2;
5574
5575// ponytail: buffered FILE, musl x86_64 layout subset
5576#[repr(C)]
5577pub struct FILE {
5578    flags: c_uint,
5579    rpos: *mut u8,
5580    rend: *mut u8,
5581    close: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
5582    wend: *mut u8,
5583    wpos: *mut u8,
5584    mustbezero_1: *mut u8,
5585    wbase: *mut u8,
5586    read_fn: Option<unsafe extern "C" fn(*mut FILE, *mut u8, usize) -> usize>,
5587    write_fn: Option<unsafe extern "C" fn(*mut FILE, *const u8, usize) -> usize>,
5588    seek_fn: Option<unsafe extern "C" fn(*mut FILE, i64, c_int) -> i64>,
5589    buf: *mut u8,
5590    buf_size: usize,
5591    prev: *mut FILE,
5592    next: *mut FILE,
5593    fd: c_int,
5594    pipe_pid: c_int,
5595    lockcount: c_long,
5596    mode: c_int,
5597    lock: c_int,
5598    lbf: c_int,
5599    cookie: *mut c_void,
5600    off: i64,
5601    getln_buf: *mut c_char,
5602    mustbezero_2: *mut c_void,
5603    shend: *mut u8,
5604    shlim: i64,
5605    shcnt: i64,
5606    ungotten: [c_int; UNGET],
5607    ungotten_count: c_int,
5608    _eof: c_int,
5609    _err: c_int,
5610}
5611
5612static mut STDIN_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5613static mut STDOUT_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5614static mut STDERR_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5615
5616static mut STDIN_FILE: FILE = FILE {
5617    flags: 0, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5618    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5619    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5620    read_fn: None, write_fn: None, seek_fn: None,
5621    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5622    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5623    fd: 0, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5624    cookie: core::ptr::null_mut(), off: 0,
5625    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5626    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5627    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5628};
5629static mut STDOUT_FILE: FILE = FILE {
5630    flags: F_NOWR as u32 + F_SVB as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5631    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5632    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5633    read_fn: None, write_fn: None, seek_fn: None,
5634    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5635    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5636    fd: 1, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5637    cookie: core::ptr::null_mut(), off: 0,
5638    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5639    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5640    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5641};
5642static mut STDERR_FILE: FILE = FILE {
5643    flags: F_NOWR as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5644    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5645    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5646    read_fn: None, write_fn: None, seek_fn: None,
5647    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5648    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5649    fd: 2, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5650    cookie: core::ptr::null_mut(), off: 0,
5651    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5652    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5653    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5654};
5655
5656#[no_mangle]
5657pub static mut stdin: *mut FILE = &raw mut STDIN_FILE as *mut FILE;
5658#[no_mangle]
5659pub static mut stdout: *mut FILE = &raw mut STDOUT_FILE as *mut FILE;
5660#[no_mangle]
5661pub static mut stderr: *mut FILE = &raw mut STDERR_FILE as *mut FILE;
5662
5663// ============================================================
5664// FILE helpers
5665// ============================================================
5666
5667unsafe fn __stdio_init() {
5668    STDIN_FILE.buf = core::ptr::addr_of_mut!(STDIN_BUF) as *mut u8;
5669    STDIN_FILE.buf_size = BUFSIZ;
5670    STDIN_FILE.read_fn = Some(__stdio_read);
5671    STDIN_FILE.write_fn = Some(__stdio_write);
5672    STDIN_FILE.seek_fn = Some(__stdio_seek);
5673    STDOUT_FILE.buf = core::ptr::addr_of_mut!(STDOUT_BUF) as *mut u8;
5674    STDOUT_FILE.buf_size = BUFSIZ;
5675    STDOUT_FILE.lbf = b'\n' as c_int;
5676    STDOUT_FILE.read_fn = Some(__stdio_read);
5677    STDOUT_FILE.write_fn = Some(__stdio_write);
5678    STDOUT_FILE.seek_fn = Some(__stdio_seek);
5679    STDERR_FILE.buf = core::ptr::addr_of_mut!(STDERR_BUF) as *mut u8;
5680    STDERR_FILE.buf_size = BUFSIZ;
5681    STDERR_FILE.read_fn = Some(__stdio_read);
5682    STDERR_FILE.write_fn = Some(__stdio_write);
5683    STDERR_FILE.seek_fn = Some(__stdio_seek);
5684}
5685
5686unsafe fn buf_ptr(f: *mut FILE) -> *mut u8 {
5687    (f as *mut u8).add(core::mem::size_of::<FILE>())
5688}
5689
5690unsafe extern "C" fn __stdio_read(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
5691    let n = sys_read((*f).fd as i64, buf, len);
5692    if n <= 0 {
5693        if n == 0 { (*f).flags |= F_EOF; } else { (*f).flags |= F_ERR; (*f)._err = 1; }
5694        return 0;
5695    }
5696    n as usize
5697}
5698
5699unsafe extern "C" fn __stdio_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
5700    let l = (*f).wpos as usize - (*f).wbase as usize;
5701    let mut iov = [
5702        ((*f).wbase as *const u8, l),
5703        (buf, len),
5704    ];
5705    if iov[0].1 == 0 { iov = [iov[1], (core::ptr::null(), 0)]; }
5706    if (*f).flags & F_APP != 0 {
5707        let _ = sys_lseek((*f).fd as i64, 0, SEEK_END as i64);
5708    }
5709    let mut rem = iov[0].1 + iov[1].1;
5710    let mut idx = 0usize;
5711    while rem > 0 {
5712        let ptr = iov[idx].0;
5713        let cnt = iov[idx].1;
5714        if cnt == 0 { idx += 1; continue; }
5715        let n = sys_write((*f).fd as i64, ptr, cnt);
5716        if n <= 0 {
5717            (*f).wpos = core::ptr::null_mut();
5718            (*f).wbase = core::ptr::null_mut();
5719            (*f).wend = core::ptr::null_mut();
5720            (*f).flags |= F_ERR;
5721            return if iov[idx].0 == buf { 0 } else { len };
5722        }
5723        rem -= n as usize;
5724        iov[idx].0 = iov[idx].0.add(n as usize);
5725        iov[idx].1 -= n as usize;
5726        if iov[idx].1 == 0 { idx += 1; }
5727    }
5728    (*f).wend = (*f).buf.add((*f).buf_size);
5729    (*f).wbase = (*f).buf;
5730    (*f).wpos = (*f).buf;
5731    len
5732}
5733
5734unsafe extern "C" fn __stdio_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
5735    sys_lseek((*f).fd as i64, off, whence as i64)
5736}
5737
5738unsafe fn init_file(
5739    f: *mut FILE,
5740    fd: c_int,
5741    mode: *const c_char,
5742    close_fn: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
5743    buf_area: *mut u8,
5744    buf_sz: usize,
5745) {
5746    core::ptr::write_bytes(f as *mut u8, 0, core::mem::size_of::<FILE>());
5747    (*f).fd = fd;
5748    (*f).close = close_fn;
5749    (*f).lock = 0;
5750    (*f).lbf = -1;
5751    (*f).buf = buf_area;
5752    (*f).buf_size = buf_sz;
5753    (*f).read_fn = Some(__stdio_read);
5754    (*f).write_fn = Some(__stdio_write);
5755    (*f).seek_fn = Some(__stdio_seek);
5756    let m = *mode;
5757    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
5758    if m == b'r' as c_char && !has_plus {
5759        (*f).flags = F_NORD;
5760    } else if !has_plus {
5761        (*f).flags = F_NOWR;
5762    }
5763}
5764
5765unsafe extern "C" fn __stdio_close(f: *mut FILE) -> c_int {
5766    sys_close((*f).fd as i64);
5767    0
5768}
5769
5770unsafe fn fmodeflags(mode: *const c_char) -> c_int {
5771    let mut flags: c_int;
5772    let m = *mode;
5773    if !strchr(mode as *const u8, b'+' as c_int).is_null() {
5774        flags = O_RDWR;
5775    } else if m == b'r' as c_char {
5776        flags = O_RDONLY;
5777    } else {
5778        flags = O_WRONLY;
5779    }
5780    if !strchr(mode as *const u8, b'x' as c_int).is_null() { flags |= O_EXCL; }
5781    if !strchr(mode as *const u8, b'e' as c_int).is_null() { flags |= O_CLOEXEC; }
5782    if m != b'r' as c_char { flags |= O_CREAT; }
5783    if m == b'w' as c_char { flags |= O_TRUNC; }
5784    if m == b'a' as c_char { flags |= O_APPEND; }
5785    flags
5786}
5787
5788const O_ACCMODE: c_int = O_RDONLY | O_WRONLY | O_RDWR;
5789
5790unsafe fn flush_buf(f: *mut FILE) -> c_int {
5791    if (*f).wpos == (*f).wbase {
5792        if !(*f).wpos.is_null() {
5793            (*f).wend = (*f).buf.add((*f).buf_size);
5794            (*f).wpos = (*f).wbase;
5795        }
5796        return 0;
5797    }
5798    if let Some(wfunc) = (*f).write_fn {
5799        let ret = wfunc(f, core::ptr::null(), 0);
5800        if ret == 0 && (*f).wpos.is_null() { return -1; }
5801        return 0;
5802    }
5803    (*f).flags |= F_ERR;
5804    -1
5805}
5806
5807// ============================================================
5808// fopen / fdopen / freopen / fclose
5809// ============================================================
5810
5811#[no_mangle]
5812pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE {
5813    if filename.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
5814    let m = *mode;
5815    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
5816        ERRNO!() = EINVAL; return core::ptr::null_mut();
5817    }
5818    let flags = fmodeflags(mode);
5819    let fd = sys_open(filename as *const u8, flags as i64, 0o666);
5820    if fd < 0 { ERRNO!() = (-fd) as c_int; return core::ptr::null_mut(); }
5821    fdopen(fd as c_int, mode)
5822}
5823
5824#[no_mangle]
5825pub unsafe extern "C" fn fdopen(fd: c_int, mode: *const c_char) -> *mut FILE {
5826    if fd < 0 || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
5827    let m = *mode;
5828    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
5829        ERRNO!() = EINVAL; return core::ptr::null_mut();
5830    }
5831    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
5832    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
5833    let buf = buf_ptr(f);
5834    init_file(f, fd, mode, Some(__stdio_close), buf, BUFSIZ);
5835    if !strchr(mode as *const u8, b'a' as c_int).is_null() { (*f).flags |= F_APP; }
5836    if !strchr(mode as *const u8, b'e' as c_int).is_null() { sys_fcntl(fd, F_SETFD, FD_CLOEXEC as i64); }
5837    if (*f).flags & F_NOWR == 0 {
5838        let mut ws: winsize = core::mem::zeroed();
5839        if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 {
5840            (*f).lbf = b'\n' as c_int;
5841        }
5842    }
5843    f
5844}
5845
5846#[no_mangle]
5847pub unsafe extern "C" fn freopen(
5848    filename: *const c_char, mode: *const c_char, f: *mut FILE,
5849) -> *mut FILE {
5850    fflush(f);
5851    if (*f).pipe_pid > 0 { let _ = __stdio_close(f); }
5852    if filename.is_null() {
5853        let flags = fmodeflags(mode);
5854        if flags == 0 { return core::ptr::null_mut(); }
5855        let mut fl = flags & !(O_CREAT | O_EXCL | O_CLOEXEC);
5856        if (*f).flags & F_APP != 0 { fl = (fl & !O_ACCMODE) | O_WRONLY | O_APPEND; }
5857        if sys_fcntl((*f).fd, F_SETFL, fl as i64) < 0 { return core::ptr::null_mut(); }
5858        let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
5859        if has_plus {
5860            (*f).flags &= !(F_NORD | F_NOWR);
5861        } else if *mode == b'r' as c_char {
5862            (*f).flags = ((*f).flags & !F_NOWR) | F_NORD;
5863        } else {
5864            (*f).flags = ((*f).flags & !F_NORD) | F_NOWR;
5865        }
5866        return f;
5867    }
5868    let new_f = fopen(filename, mode);
5869    if new_f.is_null() { let _ = __stdio_close(f); return core::ptr::null_mut(); }
5870    if (*new_f).fd == (*f).fd {
5871        (*new_f).fd = -1;
5872    } else {
5873        sys_dup3((*new_f).fd, (*f).fd, 0);
5874        let _ = __stdio_close(new_f);
5875    }
5876    (*f).flags = (*new_f).flags;
5877    (*f).rpos = core::ptr::null_mut();
5878    (*f).rend = core::ptr::null_mut();
5879    (*f).wpos = core::ptr::null_mut();
5880    (*f).wbase = core::ptr::null_mut();
5881    (*f).wend = core::ptr::null_mut();
5882    (*f).lbf = (*new_f).lbf;
5883    (*f).pipe_pid = 0;
5884    free(new_f as *mut c_void);
5885    f
5886}
5887
5888#[no_mangle]
5889pub unsafe extern "C" fn fclose(f: *mut FILE) -> c_int {
5890    if f.is_null() { return -1; }
5891    let r = fflush(f);
5892    if let Some(close_fn) = (*f).close { let _ = close_fn(f); }
5893    if r != 0 { -1 } else { 0 }
5894}
5895
5896// ============================================================
5897// setvbuf / setbuf / setbuffer / fflush
5898// ============================================================
5899
5900#[no_mangle]
5901pub unsafe extern "C" fn setvbuf(f: *mut FILE, buf: *mut c_char, mode: c_int, size: usize) -> c_int {
5902    if mode != _IOFBF && mode != _IOLBF && mode != _IONBF { return -1; }
5903    fflush(f);
5904    (*f).rpos = core::ptr::null_mut();
5905    (*f).rend = core::ptr::null_mut();
5906    (*f).wpos = core::ptr::null_mut();
5907    (*f).wbase = core::ptr::null_mut();
5908    (*f).wend = core::ptr::null_mut();
5909    if mode == _IONBF {
5910        (*f).buf_size = 0;
5911    } else if !buf.is_null() && size > 0 {
5912        (*f).buf = buf as *mut u8;
5913        (*f).buf_size = size;
5914    }
5915    (*f).lbf = if mode == _IOLBF { b'\n' as c_int } else { -1 };
5916    0
5917}
5918
5919#[no_mangle]
5920pub unsafe extern "C" fn setbuf(f: *mut FILE, buf: *mut c_char) {
5921    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
5922    else { setvbuf(f, buf, _IOFBF, BUFSIZ); }
5923}
5924
5925#[no_mangle]
5926pub unsafe extern "C" fn setbuffer(f: *mut FILE, buf: *mut c_char, size: usize) {
5927    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
5928    else { setvbuf(f, buf, _IOFBF, size); }
5929}
5930
5931#[no_mangle]
5932pub unsafe extern "C" fn fflush(f: *mut FILE) -> c_int {
5933    if f.is_null() {
5934        let mut r = 0;
5935        if !stdout.is_null() && !(*stdout).wpos.is_null() && (*stdout).wpos != (*stdout).wbase {
5936            if flush_buf(stdout) != 0 { r = -1; }
5937        }
5938        if !stderr.is_null() && !(*stderr).wpos.is_null() && (*stderr).wpos != (*stderr).wbase {
5939            if flush_buf(stderr) != 0 { r = -1; }
5940        }
5941        return r;
5942    }
5943    if !(*f).wpos.is_null() && (*f).wpos != (*f).wbase {
5944        return flush_buf(f);
5945    }
5946    0
5947}
5948
5949// ============================================================
5950// fwide / feof / ferror / clearerr / fileno
5951// ============================================================
5952
5953#[no_mangle]
5954pub unsafe extern "C" fn fwide(_f: *mut FILE, mode: c_int) -> c_int { mode }
5955
5956#[no_mangle]
5957pub unsafe extern "C" fn feof(f: *mut FILE) -> c_int { if (*f)._eof != 0 { 1 } else { 0 } }
5958
5959#[no_mangle]
5960pub unsafe extern "C" fn ferror(f: *mut FILE) -> c_int { if (*f)._err != 0 { 1 } else { 0 } }
5961
5962#[no_mangle]
5963pub unsafe extern "C" fn clearerr(f: *mut FILE) { (*f)._eof = 0; (*f)._err = 0; }
5964
5965#[no_mangle]
5966pub unsafe extern "C" fn fileno(f: *mut FILE) -> c_int { (*f).fd }
5967
5968// ============================================================
5969// fseek / ftell / rewind / fseeko / ftello / fgetpos / fsetpos
5970// ============================================================
5971
5972#[no_mangle]
5973pub unsafe extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int {
5974    fseeko(stream, offset as i64, whence)
5975}
5976
5977#[no_mangle]
5978pub unsafe extern "C" fn ftell(stream: *mut FILE) -> c_long {
5979    ftello(stream) as c_long
5980}
5981
5982#[no_mangle]
5983pub unsafe extern "C" fn rewind(stream: *mut FILE) {
5984    fseek(stream, 0, SEEK_SET);
5985    (*stream)._eof = 0;
5986    (*stream)._err = 0;
5987}
5988
5989#[no_mangle]
5990pub unsafe extern "C" fn fseeko(stream: *mut FILE, offset: i64, whence: c_int) -> c_int {
5991    if whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END {
5992        ERRNO!() = EINVAL;
5993        return -1;
5994    }
5995    let f = &mut *stream;
5996    let mut adj_offset = offset;
5997    if whence == SEEK_CUR {
5998        if !f.rpos.is_null() {
5999            adj_offset -= f.rend as i64 - f.rpos as i64;
6000        }
6001        adj_offset -= f.ungotten_count as i64;
6002    }
6003    if !f.wpos.is_null() && f.wpos != f.wbase {
6004        if flush_buf(stream) != 0 { return -1; }
6005    }
6006    f.wpos = core::ptr::null_mut();
6007    f.wbase = core::ptr::null_mut();
6008    f.wend = core::ptr::null_mut();
6009    if let Some(sfunc) = f.seek_fn {
6010        let r = sfunc(stream, adj_offset, whence);
6011        if r < 0 { return -1; }
6012    } else {
6013        ERRNO!() = EINVAL;
6014        return -1;
6015    }
6016    f.rpos = core::ptr::null_mut();
6017    f.rend = core::ptr::null_mut();
6018    f._eof = 0;
6019    f.ungotten_count = 0;
6020    0
6021}
6022
6023#[no_mangle]
6024pub unsafe extern "C" fn ftello(stream: *mut FILE) -> i64 {
6025    let f = &mut *stream;
6026    if f.flags & F_APP != 0 && !f.wpos.is_null() && f.wpos != f.wbase {
6027        if fflush(stream) != 0 { return -1; }
6028    }
6029    let sfunc = match f.seek_fn { Some(s) => s, None => return -1 };
6030    let pos = sfunc(stream, 0,
6031        if (f.flags & F_APP) != 0 && !f.wpos.is_null() && f.wpos != f.wbase { SEEK_END } else { SEEK_CUR });
6032    if pos < 0 { return -1; }
6033    let mut pos = pos;
6034    if !f.rpos.is_null() {
6035        pos += f.rpos as i64 - f.rend as i64;
6036    } else if !f.wbase.is_null() {
6037        pos += f.wpos as i64 - f.wbase as i64;
6038    }
6039    pos - f.ungotten_count as i64
6040}
6041
6042#[no_mangle]
6043pub unsafe extern "C" fn fgetpos(stream: *mut FILE, pos: *mut i64) -> c_int {
6044    let off = ftello(stream);
6045    if off < 0 { return -1; }
6046    *pos = off;
6047    0
6048}
6049
6050#[no_mangle]
6051pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const i64) -> c_int {
6052    fseeko(stream, *pos, SEEK_SET)
6053}
6054
6055// ============================================================
6056// fgetc / getc / getchar / ungetc
6057// ============================================================
6058
6059#[no_mangle]
6060pub unsafe extern "C" fn fgetc(stream: *mut FILE) -> c_int {
6061    let f = &mut *stream;
6062    if f.ungotten_count > 0 {
6063        f.ungotten_count -= 1;
6064        return f.ungotten[f.ungotten_count as usize];
6065    }
6066    if !f.rpos.is_null() && f.rpos < f.rend {
6067        let c = *f.rpos;
6068        f.rpos = f.rpos.add(1);
6069        return c as c_int;
6070    }
6071    if f._eof != 0 { return -1; }
6072    if let Some(rfunc) = f.read_fn {
6073        // Fill the stdio buffer in one read. Reading one byte per syscall is
6074        // not only slow, it is wrong for procfs files that only return their
6075        // contents on the first read: a second one-byte read sees EOF.
6076        if !f.buf.is_null() && f.buf_size > 1 {
6077            let n = rfunc(stream, f.buf, f.buf_size);
6078            if n == 0 {
6079                if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
6080                return -1;
6081            }
6082            f.rpos = f.buf;
6083            f.rend = f.buf.add(n);
6084            let c = *f.rpos;
6085            f.rpos = f.rpos.add(1);
6086            return c as c_int;
6087        }
6088        let mut buf = [0u8; 1];
6089        let n = rfunc(stream, buf.as_mut_ptr(), 1);
6090        if n == 0 {
6091            if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
6092            return -1;
6093        }
6094        buf[0] as c_int
6095    } else {
6096        f._eof = 1;
6097        -1
6098    }
6099}
6100
6101#[no_mangle]
6102pub unsafe extern "C" fn getc(stream: *mut FILE) -> c_int { fgetc(stream) }
6103
6104#[no_mangle]
6105pub unsafe extern "C" fn getchar() -> c_int { fgetc(stdin) }
6106
6107#[no_mangle]
6108pub unsafe extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int {
6109    if c == -1 { return -1; }
6110    let f = &mut *stream;
6111    if f.ungotten_count >= UNGET as c_int { return -1; }
6112    f.ungotten[f.ungotten_count as usize] = c;
6113    f.ungotten_count += 1;
6114    f._eof = 0;
6115    c
6116}
6117
6118// ============================================================
6119// fgets / fread
6120// ============================================================
6121
6122#[no_mangle]
6123pub unsafe extern "C" fn fgets(s: *mut c_char, n: c_int, stream: *mut FILE) -> *mut c_char {
6124    if n <= 0 { return null_mut(); }
6125    let max = (n - 1) as usize;
6126    let mut i = 0usize;
6127    while i < max {
6128        let c = fgetc(stream);
6129        if c == -1 { if i == 0 { return null_mut(); } break; }
6130        *s.add(i) = c as c_char;
6131        i += 1;
6132        if c == b'\n' as c_int { break; }
6133    }
6134    *s.add(i) = 0;
6135    s
6136}
6137
6138// ponytail: gets is dangerous, kept for POSIX compliance
6139#[no_mangle]
6140pub unsafe extern "C" fn gets(s: *mut c_char) -> *mut c_char {
6141    let mut i = 0usize;
6142    loop {
6143        let c = fgetc(stdin);
6144        if c == -1 { if i == 0 { return null_mut(); } break; }
6145        if c == b'\n' as c_int { break; }
6146        *s.add(i) = c as c_char;
6147        i += 1;
6148    }
6149    *s.add(i) = 0;
6150    s
6151}
6152
6153#[no_mangle]
6154pub unsafe extern "C" fn fopen64(filename: *const c_char, mode: *const c_char) -> *mut FILE {
6155    fopen(filename, mode)
6156}
6157
6158// ponytail: perror - minimal, just prints "msg: errno\n"
6159const PERROR_BUF_SIZE: usize = 64;
6160static mut PERROR_BUF: [u8; PERROR_BUF_SIZE] = [0; PERROR_BUF_SIZE];
6161
6162#[no_mangle]
6163pub unsafe extern "C" fn perror(msg: *const c_char) {
6164    let fd = (*stderr).fd;
6165    if !msg.is_null() && *msg != 0 {
6166        let len = strlen(msg as *const c_char);
6167        write_str(fd, msg as *const u8, len);
6168        write_str(fd, b": ".as_ptr(), 2);
6169    }
6170    let e = ERRNO!();
6171    let text = strerror(e) as *const u8;
6172    write_str(fd, text, strlen(text as *const c_char));
6173    write_str(fd, b"\n".as_ptr(), 1);
6174}
6175
6176#[no_mangle]
6177pub unsafe extern "C" fn fread(
6178    ptr: *mut c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
6179) -> SizeT {
6180    if size == 0 || nmemb == 0 { return 0; }
6181    let total = size * nmemb;
6182    let mut rd = 0usize;
6183    while rd < total {
6184        let c = fgetc(stream);
6185        if c == -1 { break; }
6186        *(ptr as *mut u8).add(rd) = c as u8;
6187        rd += 1;
6188    }
6189    rd / size
6190}
6191
6192// ============================================================
6193// puts / fputs / fputc / putc / putchar / fwrite
6194// ============================================================
6195
6196unsafe fn write_str(fd: c_int, s: *const u8, len: usize) {
6197    let mut written = 0usize;
6198    while written < len {
6199        let n = sys_write(fd as i64, s.add(written), len - written);
6200        if n <= 0 { break; }
6201        written += n as usize;
6202    }
6203}
6204
6205#[no_mangle]
6206unsafe fn __overflow(f: *mut FILE, c: c_int) -> c_int {
6207    if (*f).wpos.is_null() {
6208        (*f).wbase = (*f).buf;
6209        (*f).wpos = (*f).buf;
6210        (*f).wend = (*f).buf.add((*f).buf_size);
6211    }
6212    if flush_buf(f) == -1 { return -1; }
6213    if (*f).wpos >= (*f).wend {
6214        if let Some(wfunc) = (*f).write_fn {
6215            let byte = c as u8;
6216            let ret = wfunc(f, &byte as *const u8, 1);
6217            if ret == 0 { return -1; }
6218        }
6219        return c;
6220    }
6221    *(*f).wpos = c as u8;
6222    (*f).wpos = (*f).wpos.add(1);
6223    if c == (*f).lbf || (*f).wpos >= (*f).wend { let _ = flush_buf(f); }
6224    c
6225}
6226
6227#[no_mangle]
6228pub unsafe extern "C" fn puts(s: *const c_char) -> c_int {
6229    let len = strlen(s as *const c_char);
6230    let _ = fwrite(s as *const c_void, 1, len, stdout);
6231    let _ = fwrite(b"\n".as_ptr() as *const c_void, 1, 1, stdout);
6232    let f = &mut *stdout;
6233    if f.lbf >= 0 { let _ = flush_buf(stdout); }
6234    (len + 1) as c_int
6235}
6236
6237#[no_mangle]
6238pub unsafe extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int {
6239    let len = strlen(s as *const c_char);
6240    fwrite(s as *const c_void, 1, len, stream) as c_int
6241}
6242
6243#[no_mangle]
6244pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int {
6245    let f = &mut *stream;
6246    if f.wpos.is_null() || f.wpos >= f.wend {
6247        if __overflow(f, c) == -1 { return -1; }
6248        return c;
6249    }
6250    *f.wpos = c as u8;
6251    f.wpos = f.wpos.add(1);
6252    if c == f.lbf || f.wpos >= f.wend { let _ = flush_buf(f); }
6253    c
6254}
6255
6256#[no_mangle]
6257pub unsafe extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int { fputc(c, stream) }
6258
6259#[no_mangle]
6260pub unsafe extern "C" fn putchar(c: c_int) -> c_int { fputc(c, stdout) }
6261
6262#[no_mangle]
6263pub unsafe extern "C" fn fwrite(
6264    ptr: *const c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
6265) -> SizeT {
6266    if size == 0 || nmemb == 0 { return 0; }
6267    let total = size * nmemb;
6268    let f = &mut *stream;
6269    if f.buf_size == 0 {
6270        if let Some(wfunc) = f.write_fn {
6271            let ret = wfunc(stream, ptr as *const u8, total);
6272            return ret / size;
6273        }
6274        return 0;
6275    }
6276    if f.wpos.is_null() {
6277        f.wbase = f.buf;
6278        f.wpos = f.buf;
6279        f.wend = f.buf.add(f.buf_size);
6280    }
6281    let mut remaining = total;
6282    let mut src = ptr as *const u8;
6283    while remaining > 0 {
6284        let space = f.wend as usize - f.wpos as usize;
6285        if space == 0 {
6286            if flush_buf(f as *mut FILE) == -1 { break; }
6287            continue;
6288        }
6289        let n = if remaining < space { remaining } else { space };
6290        core::ptr::copy_nonoverlapping(src, f.wpos, n);
6291        f.wpos = f.wpos.add(n);
6292        src = src.add(n);
6293        remaining -= n;
6294        if f.wpos >= f.wend { let _ = flush_buf(f as *mut FILE); }
6295    }
6296    if f.lbf >= 0 { let _ = flush_buf(f as *mut FILE); }
6297    (total - remaining) / size
6298}
6299
6300// ============================================================
6301// printf / fprintf / vprintf / vfprintf / dprintf / vdprintf
6302// ============================================================
6303
6304unsafe fn wide_to_mb(dst: *mut u8, cap: usize, src: *const wchar_t) -> usize {
6305    let mut o = 0usize;
6306    let mut i = 0usize;
6307    let mut st: c_uint = 0;
6308    while *src.add(i) != 0 {
6309        let mut tmp = [0u8; 8];
6310        let n = wcrtomb(tmp.as_mut_ptr() as *mut c_char, *src.add(i), &mut st);
6311        if n == !0usize || n == 0 { break; }
6312        if o + n > cap { break; }
6313        core::ptr::copy_nonoverlapping(tmp.as_ptr(), dst.add(o), n);
6314        o += n;
6315        i += 1;
6316    }
6317    o
6318}
6319
6320macro_rules! impl_format {
6321    ($fmt:expr, $args:expr, $write_char:expr, $write_str:expr) => {{
6322        let fmt = $fmt;
6323        let args = &mut $args;
6324        let mut count: usize = 0;
6325        let mut i = 0usize;
6326        loop {
6327            let c = *fmt.add(i) as u8;
6328            if c == 0 { break; }
6329            if c != b'%' {
6330                ($write_char)(c);
6331                count += 1; i += 1; continue;
6332            }
6333            i += 1;
6334            // Parse flags
6335            let mut flags: u8 = 0;
6336            loop {
6337                let fc = *fmt.add(i) as u8;
6338                match fc {
6339                    b'-' => { flags |= FLAG_MINUS; i += 1; }
6340                    b'+' => { flags |= FLAG_PLUS; i += 1; }
6341                    b' ' => { flags |= FLAG_SPACE; i += 1; }
6342                    b'0' => { flags |= FLAG_ZERO; i += 1; }
6343                    b'#' => { flags |= FLAG_HASH; i += 1; }
6344                    _ => break,
6345                }
6346            }
6347            // Parse width
6348            let mut width: usize = 0;
6349            if *fmt.add(i) as u8 == b'*' {
6350                width = args.next_arg::<c_int>() as usize; i += 1;
6351            } else {
6352                while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
6353                    width = width * 10 + ((*fmt.add(i) as u8) - b'0') as usize; i += 1;
6354                }
6355            }
6356            // Parse precision
6357            let mut precision: i32 = -1;
6358            if *fmt.add(i) as u8 == b'.' {
6359                i += 1;
6360                if *fmt.add(i) as u8 == b'*' {
6361                    precision = args.next_arg::<c_int>(); i += 1;
6362                } else {
6363                    precision = 0;
6364                    while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
6365                        precision = precision * 10 + ((*fmt.add(i) as u8) - b'0') as i32; i += 1;
6366                    }
6367                }
6368            }
6369            // Parse length modifier
6370            let len_mod = *fmt.add(i) as u8;
6371            let spec: u8;
6372            if len_mod == b'h' || len_mod == b'l' || len_mod == b'j' || len_mod == b'z' || len_mod == b't' || len_mod == b'L' {
6373                i += 1;
6374                let len_mod2 = *fmt.add(i) as u8;
6375                if (len_mod == b'h' && len_mod2 == b'h') || (len_mod == b'l' && len_mod2 == b'l') {
6376                    i += 1;
6377                    spec = *fmt.add(i) as u8;
6378                    // Handle double-length modifiers
6379                    match (len_mod, len_mod2, spec) {
6380                        (b'h', b'h', b'n') => {
6381                            let p = args.next_arg::<*mut c_void>();
6382                            if !p.is_null() { *(p as *mut u8) = count as u8; }
6383                        }
6384                        (b'l', b'l', b'n') => {
6385                            let p = args.next_arg::<*mut c_void>();
6386                            if !p.is_null() { *(p as *mut c_longlong) = count as c_longlong; }
6387                        }
6388                        (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
6389                            let val = args.next_arg::<c_longlong>();
6390                            let neg = val < 0;
6391                            let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
6392                            let b = format_u64(abs);
6393                            let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6394                            let mut fbuf = [0u8; 32];
6395                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6396                            ($write_str)(fbuf.as_ptr(), len); count += len;
6397                        }
6398                        (b'l', b'l', b'u') => {
6399                            let val = args.next_arg::<c_ulonglong>();
6400                            let b = format_u64(val as u64);
6401                            let mut fbuf = [0u8; 32];
6402                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6403                            ($write_str)(fbuf.as_ptr(), len); count += len;
6404                        }
6405                        (b'l', b'l', b'o') => {
6406                            let val = args.next_arg::<c_ulonglong>();
6407                            let b = format_octal(val as u64, flags & FLAG_HASH != 0);
6408                            let mut fbuf = [0u8; 32];
6409                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6410                            ($write_str)(fbuf.as_ptr(), len); count += len;
6411                        }
6412                        (b'l', b'l', b'x') => {
6413                            let val = args.next_arg::<c_ulonglong>();
6414                            let b = format_hex(val as u64, false);
6415                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6416                            let mut fbuf = [0u8; 32];
6417                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6418                            ($write_str)(fbuf.as_ptr(), len); count += len;
6419                        }
6420                        (b'l', b'l', b'X') => {
6421                            let val = args.next_arg::<c_ulonglong>();
6422                            let b = format_hex(val as u64, true);
6423                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6424                            let mut fbuf = [0u8; 32];
6425                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6426                            ($write_str)(fbuf.as_ptr(), len); count += len;
6427                        }
6428                        _ => { ($write_char)(b'%'); ($write_char)(len_mod); ($write_char)(len_mod2); ($write_char)(spec); count += 4; }
6429                    }
6430                } else {
6431                    spec = len_mod2;
6432                    // size_t/ptrdiff_t are 64-bit on all supported targets;
6433                    // treat %z/%t integer conversions like %l.
6434                    let lm = if (len_mod == b'z' || len_mod == b't') && spec != b'n' { b'l' } else { len_mod };
6435                    match (lm, spec) {
6436                        (b'h', b'n') => {
6437                            let p = args.next_arg::<*mut c_void>();
6438                            if !p.is_null() { *(p as *mut u16) = count as u16; }
6439                        }
6440                        (b'l', b'n') => {
6441                            let p = args.next_arg::<*mut c_void>();
6442                            if !p.is_null() { *(p as *mut c_long) = count as c_long; }
6443                        }
6444                        (b'z', b'n') | (b't', b'n') => {
6445                            let p = args.next_arg::<*mut c_void>();
6446                            if !p.is_null() { *(p as *mut usize) = count; }
6447                        }
6448                        (b'j', b'n') => {
6449                            let p = args.next_arg::<*mut c_void>();
6450                            if !p.is_null() { *(p as *mut c_ulonglong) = count as c_ulonglong; }
6451                        }
6452                        (b'l', b'd') | (b'l', b'i') => {
6453                            let val = args.next_arg::<c_long>();
6454                            let neg = val < 0;
6455                            let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
6456                            let b = format_u64(abs);
6457                            let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6458                            let mut fbuf = [0u8; 32];
6459                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6460                            ($write_str)(fbuf.as_ptr(), len); count += len;
6461                        }
6462                        (b'l', b'u') => {
6463                            let val = args.next_arg::<c_ulong>();
6464                            let b = format_u64(val as u64);
6465                            let mut fbuf = [0u8; 32];
6466                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6467                            ($write_str)(fbuf.as_ptr(), len); count += len;
6468                        }
6469                        (b'l', b's') => {
6470                            let p = args.next_arg::<*const wchar_t>();
6471                            if p.is_null() {
6472                                let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
6473                                let pad = width.saturating_sub(slen);
6474                                if flags & FLAG_MINUS != 0 { ($write_str)(b"(null)".as_ptr(), slen); for _ in 0..pad { ($write_char)(b' '); } }
6475                                else { for _ in 0..pad { ($write_char)(b' '); } ($write_str)(b"(null)".as_ptr(), slen); }
6476                                count += slen + pad;
6477                            } else {
6478                                let mut mb = [0u8; 4096];
6479                                let mut n = wide_to_mb(mb.as_mut_ptr(), mb.len(), p);
6480                                if precision >= 0 && (precision as usize) < n { n = precision as usize; }
6481                                let pad = width.saturating_sub(n);
6482                                if flags & FLAG_MINUS != 0 { ($write_str)(mb.as_ptr(), n); for _ in 0..pad { ($write_char)(b' '); } }
6483                                else { for _ in 0..pad { ($write_char)(b' '); } ($write_str)(mb.as_ptr(), n); }
6484                                count += n + pad;
6485                            }
6486                        }
6487                        (b'l', b'c') => {
6488                            let ch = args.next_arg::<c_int>();
6489                            let mut mb = [0u8; 8];
6490                            let mut st: c_uint = 0;
6491                            let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, ch, &mut st);
6492                            if n != !0usize { ($write_str)(mb.as_ptr(), n); count += n; }
6493                        }
6494                        (b'l', b'x') => {
6495                            let val = args.next_arg::<c_ulong>();
6496                            let b = format_hex(val as u64, false);
6497                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6498                            let mut fbuf = [0u8; 32];
6499                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6500                            ($write_str)(fbuf.as_ptr(), len); count += len;
6501                        }
6502                        (b'l', b'X') => {
6503                            let val = args.next_arg::<c_ulong>();
6504                            let b = format_hex(val as u64, true);
6505                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6506                            let mut fbuf = [0u8; 32];
6507                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6508                            ($write_str)(fbuf.as_ptr(), len); count += len;
6509                        }
6510                        (b'l', b'o') => {
6511                            let val = args.next_arg::<c_ulong>();
6512                            let b = format_octal(val as u64, flags & FLAG_HASH != 0);
6513                            let mut fbuf = [0u8; 32];
6514                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6515                            ($write_str)(fbuf.as_ptr(), len); count += len;
6516                        }
6517                        (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
6518                        | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
6519                            let val = args.next_arg::<f64>();
6520                            let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6521                            let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6522                            let mut fbuf = [0u8; 4224];
6523                            let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6524                            let total = apply_width_flags(fbuf.as_mut_ptr().add(4096), fbuf.as_ptr(), flen, width, flags);
6525                            core::ptr::copy_nonoverlapping(fbuf.as_ptr().add(4096), fbuf.as_mut_ptr(), total);
6526                            ($write_str)(fbuf.as_ptr(), total); count += total;
6527                        }
6528                        (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
6529                        | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
6530                            #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
6531                            let val = {
6532                                let lo: u64 = args.next_arg::<u64>();
6533                                let hi: u64 = args.next_arg::<u64>();
6534                                let combined: u128 = ((hi as u128) << 64) | (lo as u128);
6535                                f128::from_bits(combined) as f64
6536                            };
6537                            #[cfg(target_arch = "x86_64")]
6538                            let val = args.next_arg::<f64>();
6539                            let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6540                            let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6541                            let mut fbuf = [0u8; 4224];
6542                            let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6543                            let total = apply_width_flags(fbuf.as_mut_ptr().add(4096), fbuf.as_ptr(), flen, width, flags);
6544                            core::ptr::copy_nonoverlapping(fbuf.as_ptr().add(4096), fbuf.as_mut_ptr(), total);
6545                            ($write_str)(fbuf.as_ptr(), total); count += total;
6546                        }
6547                        _ => { ($write_char)(b'%'); ($write_char)(len_mod); ($write_char)(spec); count += 3; }
6548                    }
6549                }
6550            } else {
6551                spec = *fmt.add(i) as u8;
6552                match spec {
6553                    b's' => {
6554                        let s = args.next_arg::<*const c_char>();
6555                        if s.is_null() {
6556                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
6557                            let padded_len = if width > slen { width } else { slen };
6558                            let pad = padded_len - slen;
6559                            if flags & FLAG_MINUS != 0 {
6560                                ($write_str)(b"(null)".as_ptr(), slen);
6561                                for _ in 0..pad { ($write_char)(b' '); }
6562                            } else {
6563                                for _ in 0..pad { ($write_char)(b' '); }
6564                                ($write_str)(b"(null)".as_ptr(), slen);
6565                            }
6566                            count += padded_len;
6567                        } else {
6568                            let full_len = strlen(s as *const c_char);
6569                            let slen = if precision >= 0 { (precision as usize).min(full_len) } else { full_len };
6570                            let padded_len = if width > slen { width } else { slen };
6571                            let pad = padded_len - slen;
6572                            if flags & FLAG_MINUS != 0 {
6573                                ($write_str)(s as *const u8, slen);
6574                                for _ in 0..pad { ($write_char)(b' '); }
6575                            } else {
6576                                for _ in 0..pad { ($write_char)(b' '); }
6577                                ($write_str)(s as *const u8, slen);
6578                            }
6579                            count += padded_len;
6580                        }
6581                    }
6582                    b'd' | b'i' => {
6583                        let d = args.next_arg::<c_int>();
6584                        let neg = d < 0;
6585                        let abs = if neg { d.wrapping_neg() as u64 } else { d as u64 };
6586                        let b = format_u64(abs);
6587                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6588                        let mut fbuf = [0u8; 32];
6589                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6590                        ($write_str)(fbuf.as_ptr(), len); count += len;
6591                    }
6592                    b'u' => {
6593                        let u = args.next_arg::<c_uint>();
6594                        let b = format_u64(u as u64);
6595                        let mut fbuf = [0u8; 32];
6596                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6597                        ($write_str)(fbuf.as_ptr(), len); count += len;
6598                    }
6599                    b'x' => {
6600                        let x = args.next_arg::<c_uint>();
6601                        let b = format_hex(x as u64, false);
6602                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6603                        let mut fbuf = [0u8; 32];
6604                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6605                        ($write_str)(fbuf.as_ptr(), len); count += len;
6606                    }
6607                    b'X' => {
6608                        let x = args.next_arg::<c_uint>();
6609                        let b = format_hex(x as u64, true);
6610                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6611                        let mut fbuf = [0u8; 32];
6612                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6613                        ($write_str)(fbuf.as_ptr(), len); count += len;
6614                    }
6615                    b'o' => {
6616                        let o = args.next_arg::<c_uint>();
6617                        let b = format_octal(o as u64, flags & FLAG_HASH != 0);
6618                        let mut fbuf = [0u8; 32];
6619                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6620                        ($write_str)(fbuf.as_ptr(), len); count += len;
6621                    }
6622                    b'c' => {
6623                        let ch = args.next_arg::<c_int>();
6624                        if width > 1 {
6625                            let pad = width - 1;
6626                            if flags & FLAG_MINUS != 0 {
6627                                ($write_char)(ch as u8); count += 1;
6628                                for _ in 0..pad { ($write_char)(b' '); count += 1; }
6629                            } else {
6630                                for _ in 0..pad { ($write_char)(b' '); count += 1; }
6631                                ($write_char)(ch as u8); count += 1;
6632                            }
6633                        } else {
6634                            ($write_char)(ch as u8); count += 1;
6635                        }
6636                    }
6637                    b'p' => {
6638                        let p = args.next_arg::<*const c_void>();
6639                        let mut fbuf = [0u8; 20];
6640                        fbuf[0] = b'0'; fbuf[1] = b'x';
6641                        let b = format_hex(p as u64, false);
6642                        core::ptr::copy_nonoverlapping(b.0.as_ptr(), fbuf.as_mut_ptr().add(2), b.1);
6643                        ($write_str)(fbuf.as_ptr(), b.1 + 2); count += b.1 + 2;
6644                    }
6645                    b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
6646                        let val = args.next_arg::<f64>();
6647                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6648                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6649                        let mut fbuf = [0u8; 4224];
6650                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6651                        let total = apply_width_flags(fbuf.as_mut_ptr().add(4096), fbuf.as_ptr(), flen, width, flags);
6652                        core::ptr::copy_nonoverlapping(fbuf.as_ptr().add(4096), fbuf.as_mut_ptr(), total);
6653                        ($write_str)(fbuf.as_ptr(), total); count += total;
6654                    }
6655                    b'%' => { ($write_char)(b'%'); count += 1; }
6656                    b'n' => {
6657                        let p = args.next_arg::<*mut c_void>();
6658                        if !p.is_null() { *(p as *mut c_int) = count as c_int; }
6659                    }
6660                    _ => { ($write_char)(b'%'); ($write_char)(spec); count += 2; }
6661                }
6662            }
6663            i += 1;
6664        }
6665        count as c_int
6666    }};
6667}
6668
6669unsafe fn format_u64(mut val: u64) -> ([u8; 20], usize) {
6670    let mut buf = [0u8; 20];
6671    if val == 0 { buf[0] = b'0'; return (buf, 1); }
6672    let mut tmp = [0u8; 20];
6673    let mut pos = 20;
6674    while val > 0 { pos -= 1; tmp[pos] = b'0' + (val % 10) as u8; val /= 10; }
6675    let len = 20 - pos;
6676    core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6677    (buf, len)
6678}
6679
6680unsafe fn format_i64(val: i64) -> ([u8; 21], usize) {
6681    let mut buf = [0u8; 21];
6682    if val < 0 {
6683        buf[0] = b'-';
6684        let (inner, len) = format_u64((-(val as i128)) as u64);
6685        core::ptr::copy_nonoverlapping(inner.as_ptr(), buf.as_mut_ptr().add(1), len);
6686        (buf, len + 1)
6687    } else {
6688        let (inner, len) = format_u64(val as u64);
6689        core::ptr::copy_nonoverlapping(inner.as_ptr(), buf.as_mut_ptr(), len);
6690        (buf, len)
6691    }
6692}
6693
6694unsafe fn format_hex(mut val: u64, uppercase: bool) -> ([u8; 16], usize) {
6695    let digits = if uppercase { b"0123456789ABCDEF" } else { b"0123456789abcdef" };
6696    let mut buf = [0u8; 16];
6697    if val == 0 { buf[0] = b'0'; return (buf, 1); }
6698    let mut tmp = [0u8; 16];
6699    let mut pos = 16;
6700    while val > 0 { pos -= 1; tmp[pos] = digits[(val & 0xf) as usize]; val >>= 4; }
6701    let len = 16 - pos;
6702    core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6703    (buf, len)
6704}
6705
6706unsafe fn format_octal(mut val: u64, alt: bool) -> ([u8; 24], usize) {
6707    let mut buf = [0u8; 24];
6708    if val == 0 {
6709        buf[0] = b'0';
6710        return (buf, 1);
6711    }
6712    let mut tmp = [0u8; 24];
6713    let mut pos = 24;
6714    while val > 0 {
6715        pos -= 1;
6716        tmp[pos] = b'0' + (val & 7) as u8;
6717        val >>= 3;
6718    }
6719    let len = 24 - pos;
6720    if alt {
6721        tmp[pos - 1] = b'0';
6722        core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos - 1), buf.as_mut_ptr(), len + 1);
6723        (buf, len + 1)
6724    } else {
6725        core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6726        (buf, len)
6727    }
6728}
6729
6730unsafe fn format_int(
6731    dst: *mut u8,
6732    digits: *const u8,
6733    digits_len: usize,
6734    sign: Option<u8>,
6735    prefix: Option<u8>,
6736    precision: i32,
6737    width: usize,
6738    flags: u8,
6739    octal_alt: bool,
6740) -> usize {
6741    let num_digits = if precision == 0 && digits_len == 1 && *digits == b'0' && !octal_alt {
6742        0
6743    } else {
6744        digits_len
6745    };
6746    let prec = precision as usize;
6747    let zero_pad = if precision >= 0 && prec > num_digits { prec - num_digits } else { 0 };
6748
6749    let sign_len = sign.map_or(0, |_| 1);
6750    let prefix_len = prefix.map_or(0, |_| 2);
6751    let content_len = sign_len + prefix_len + zero_pad + num_digits;
6752
6753    let mut buf = [0u8; 32];
6754    let mut pos = 0usize;
6755    if let Some(c) = sign { buf[pos] = c; pos += 1; }
6756    if let Some(c) = prefix { buf[pos] = b'0'; pos += 1; buf[pos] = c; pos += 1; }
6757    for _ in 0..zero_pad { buf[pos] = b'0'; pos += 1; }
6758    if num_digits > 0 {
6759        core::ptr::copy_nonoverlapping(digits, buf.as_mut_ptr().add(pos), num_digits);
6760    }
6761
6762    if content_len >= width {
6763        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, content_len);
6764        return content_len;
6765    }
6766    let pad = width - content_len;
6767    if flags & FLAG_MINUS != 0 {
6768        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, content_len);
6769        for i in 0..pad { *dst.add(content_len + i) = b' '; }
6770    } else if flags & FLAG_ZERO != 0 && precision < 0 {
6771        let fixed = sign_len + prefix_len;
6772        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, fixed);
6773        for i in fixed..width - num_digits { *dst.add(i) = b'0'; }
6774        if num_digits > 0 {
6775            core::ptr::copy_nonoverlapping(digits, dst.add(width - num_digits), num_digits);
6776        }
6777    } else {
6778        for i in 0..pad { *dst.add(i) = b' '; }
6779        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst.add(pad), content_len);
6780    }
6781    width
6782}
6783
6784unsafe fn format_f64(val: f64) -> ([u8; 64], usize) {
6785    let mut buf = [0u8; 64];
6786    let mut pos = 0usize;
6787    let mut v = val;
6788    if v.is_nan() {
6789        let nan = b"nan";
6790        core::ptr::copy_nonoverlapping(nan.as_ptr(), buf.as_mut_ptr(), 3);
6791        return (buf, 3);
6792    }
6793    if v < 0.0 { buf[pos] = b'-'; pos += 1; v = -v; }
6794    if v.is_infinite() {
6795        let inf = b"inf";
6796        core::ptr::copy_nonoverlapping(inf.as_ptr(), buf.as_mut_ptr().add(pos), 3);
6797        return (buf, pos + 3);
6798    }
6799    let int_part = v as u64;
6800    let frac = v - int_part as f64;
6801    let (ibuf, ilen) = format_u64(int_part);
6802    core::ptr::copy_nonoverlapping(ibuf.as_ptr(), buf.as_mut_ptr().add(pos), ilen);
6803    pos += ilen;
6804    buf[pos] = b'.';
6805    pos += 1;
6806    let mut f = frac;
6807    for _ in 0..6 { f *= 10.0; let digit = f as u8; buf[pos] = b'0' + digit; pos += 1; f -= digit as f64; }
6808    (buf, pos)
6809}
6810
6811// Float format specifier type
6812const FMT_F: u8 = 0;
6813const FMT_E: u8 = 1;
6814const FMT_G: u8 = 2;
6815const FMT_A: u8 = 3;
6816
6817const FLAG_HASH: u8 = 1;
6818const FLAG_PLUS: u8 = 2;
6819const FLAG_SPACE: u8 = 4;
6820const FLAG_ZERO: u8 = 8;
6821const FLAG_MINUS: u8 = 16;
6822
6823// === %f formatting helpers ===
6824
6825/// Convert (mant << shift) to decimal string. Returns byte count written to buf.
6826/// mant is a 53-bit significand, shift is the left-shift amount (can be 0..~971).
6827unsafe fn bigint_to_decimal(buf: *mut u8, mant: u64, shift: u32) -> usize {
6828    // Store as little-endian u32 limbs. Max bits: 53 + 971 ≈ 1024 → 32 limbs.
6829    let nlimbs = (2 + (shift + 31) / 32) as usize;
6830    let mut limbs = [0u32; 36];
6831    limbs[0] = mant as u32;
6832    limbs[1] = (mant >> 32) as u32;
6833
6834    let ws = (shift / 32) as usize;
6835    let bs = shift % 32;
6836
6837    // Word-level shift left
6838    if ws > 0 {
6839        let mut i = 1usize;
6840        loop {
6841            limbs[i + ws] = limbs[i];
6842            if i == 0 { break; }
6843            i -= 1;
6844        }
6845        for j in 0..ws { limbs[j] = 0; }
6846    }
6847    // Bit-level shift left
6848    if bs > 0 {
6849        let mut carry = 0u32;
6850        let end = nlimbs.min(ws + 3);
6851        for i in ws..end {
6852            let new_val = (limbs[i] << bs) | carry;
6853            carry = limbs[i] >> (32 - bs);
6854            limbs[i] = new_val;
6855        }
6856    }
6857
6858    // Find highest non-zero limb
6859    let mut used = nlimbs;
6860    while used > 0 && limbs[used - 1] == 0 { used -= 1; }
6861    if used == 0 { *buf = b'0'; return 1; }
6862
6863    // Repeated division by 10 to extract decimal digits
6864    let mut digits = [0u8; 400];
6865    let mut nd = 0usize;
6866    loop {
6867        let mut all_zero = true;
6868        for i in 0..used { if limbs[i] != 0 { all_zero = false; break; } }
6869        if all_zero { break; }
6870        let mut rem = 0u64;
6871        for i in (0..used).rev() {
6872            let val = (rem << 32) | limbs[i] as u64;
6873            limbs[i] = (val / 10) as u32;
6874            rem = val % 10;
6875        }
6876        digits[nd] = rem as u8;
6877        nd += 1;
6878    }
6879    // Write digits in big-endian order
6880    for i in 0..nd { *buf.add(i) = b'0' + digits[nd - 1 - i]; }
6881    nd
6882}
6883
6884/// Compute `count` fractional digits of frac_bits / 2^shift using u128 arithmetic.
6885/// shift must be <= 124. Returns true if any value remains after the last digit.
6886unsafe fn frac_digits_u128(buf: *mut u8, frac_bits: u64, shift: u32, count: usize) -> bool {
6887    let mask: u128 = (1u128 << shift) - 1;
6888    let mut rem = frac_bits as u128;
6889    for i in 0..count {
6890        rem *= 10;
6891        let digit = (rem >> shift) as u8;
6892        rem &= mask;
6893        *buf.add(i) = digit;
6894    }
6895    rem != 0
6896}
6897
6898/// Compute `count` fractional digits of frac_bits / 2^shift using big-integer arithmetic.
6899/// For shift > 124 (up to ~1074). Returns true if any value remains after the last digit.
6900unsafe fn frac_digits_bigint(buf: *mut u8, frac_bits: u64, shift: u32, count: usize) -> bool {
6901    let nlimbs = ((shift + 31) / 32) as usize;
6902    let mut rem = [0u32; 36]; // enough for shift up to 1088
6903    rem[0] = frac_bits as u32;
6904    if nlimbs > 1 { rem[1] = (frac_bits >> 32) as u32; }
6905    // Mask to exactly `shift` bits
6906    let hi_word = (shift / 32) as usize;
6907    let hi_bit = shift % 32;
6908    if hi_bit > 0 && hi_word < nlimbs {
6909        rem[hi_word] &= (1u32 << hi_bit) - 1;
6910    }
6911    // Zero upper limbs beyond shift
6912    let clear_from = if hi_bit > 0 { hi_word + 1 } else { hi_word };
6913    for j in clear_from..nlimbs { rem[j] = 0; }
6914
6915    for i in 0..count {
6916        // Multiply remainder by 10
6917        let mut carry = 0u64;
6918        for j in 0..nlimbs {
6919            let val = rem[j] as u64 * 10 + carry;
6920            rem[j] = val as u32;
6921            carry = val >> 32;
6922        }
6923        // Extract digit from bit position `shift`
6924        let digit: u32;
6925        if hi_bit == 0 {
6926            digit = if hi_word < nlimbs { rem[hi_word] } else { carry as u32 };
6927        } else {
6928            let mut d = if hi_word < nlimbs { rem[hi_word] >> hi_bit } else { 0 };
6929            if hi_word + 1 < nlimbs {
6930                d |= rem[hi_word + 1] << (32 - hi_bit);
6931            } else if carry > 0 {
6932                d |= (carry as u32) << (32 - hi_bit);
6933            }
6934            digit = d;
6935        }
6936        *buf.add(i) = digit.min(9) as u8;
6937        // Clear bits from position `shift` upward (keep remainder < 2^shift)
6938        if hi_bit == 0 {
6939            if hi_word < nlimbs { rem[hi_word] = 0; }
6940        } else {
6941            if hi_word < nlimbs {
6942                rem[hi_word] &= (1u32 << hi_bit) - 1;
6943            }
6944            for j in (hi_word + 1)..nlimbs { rem[j] = 0; }
6945        }
6946    }
6947    // Check if remainder is non-zero
6948    for i in 0..nlimbs { if rem[i] != 0 { return true; } }
6949    false
6950}
6951
6952/// Increment a decimal string stored at buf[0..*len] in-place.
6953unsafe fn increment_decimal(buf: *mut u8, len: &mut usize) {
6954    let mut j = *len;
6955    loop {
6956        if j == 0 {
6957            // Shift right and prepend '1'
6958            let l = *len;
6959            for i in (0..l).rev() { *buf.add(i + 1) = *buf.add(i); }
6960            *buf = b'1';
6961            *len = l + 1;
6962            return;
6963        }
6964        j -= 1;
6965        let d = *buf.add(j);
6966        if d < b'9' { *buf.add(j) = d + 1; return; }
6967        *buf.add(j) = b'0';
6968    }
6969}
6970
6971// Write float to dst. Returns bytes written. Does NOT handle width/flags padding.
6972unsafe fn format_f64_full(
6973    dst: *mut u8, val: f64, fmt_type: u8, precision: i32, flags: u8, uppercase: bool,
6974) -> usize {
6975    let mut pos = 0usize;
6976
6977    // NaN
6978    if val.is_nan() {
6979        let nan_s: &[u8] = if uppercase { b"NAN" } else { b"nan" };
6980        core::ptr::copy_nonoverlapping(nan_s.as_ptr(), dst, 3);
6981        return 3;
6982    }
6983    let neg = val.is_sign_negative();
6984    let v = if neg { -val } else { val };
6985
6986    // Inf
6987    if v.is_infinite() {
6988        if neg { *dst.add(pos) = b'-'; pos += 1; }
6989        else if flags & FLAG_PLUS != 0 { *dst.add(pos) = b'+'; pos += 1; }
6990        else if flags & FLAG_SPACE != 0 { *dst.add(pos) = b' '; pos += 1; }
6991        let inf_s: &[u8] = if uppercase { b"INF" } else { b"inf" };
6992        core::ptr::copy_nonoverlapping(inf_s.as_ptr(), dst.add(pos), 3);
6993        return pos + 3;
6994    }
6995
6996    // Sign
6997    if neg { *dst.add(pos) = b'-'; pos += 1; }
6998    else if flags & FLAG_PLUS != 0 { *dst.add(pos) = b'+'; pos += 1; }
6999    else if flags & FLAG_SPACE != 0 { *dst.add(pos) = b' '; pos += 1; }
7000
7001    // === Hex float ===
7002    if fmt_type == FMT_A {
7003        return pos + fmt_hex_float(dst.add(pos), val, precision, flags, uppercase);
7004    }
7005
7006    // === Decimal formats ===
7007    let p: usize;
7008    let mut exp: i32;
7009    let use_f: bool;
7010
7011    match fmt_type {
7012        FMT_G => {
7013            let gp = if precision < 0 { 6usize } else if precision == 0 { 1usize } else { precision as usize };
7014            exp = if v > 0.0 { compute_exp10(v) } else { 0 };
7015            use_f = exp >= -4 && exp < gp as i32;
7016            if use_f {
7017                p = if exp < 0 { gp + ((-exp) as usize - 1) }
7018                    else if (exp as usize) < gp { gp - exp as usize - 1 }
7019                    else { 0 };
7020            } else {
7021                p = gp - 1;
7022            }
7023        }
7024        FMT_E => {
7025            p = if precision < 0 { 6usize } else { precision as usize };
7026            exp = if v > 0.0 { compute_exp10(v) } else { 0 };
7027            use_f = false;
7028        }
7029        _ => {
7030            p = if precision < 0 { 6usize } else { precision as usize };
7031            exp = 0;
7032            use_f = true;
7033        }
7034    }
7035
7036    if v == 0.0 {
7037        *dst.add(pos) = b'0'; pos += 1;
7038        if !(fmt_type == FMT_G && flags & FLAG_HASH == 0) {
7039            if p > 0 || flags & FLAG_HASH != 0 {
7040                *dst.add(pos) = b'.'; pos += 1;
7041                for _ in 0..p { *dst.add(pos) = b'0'; pos += 1; }
7042            }
7043        }
7044        if !use_f {
7045            let ec = if uppercase { b'E' } else { b'e' };
7046            *dst.add(pos) = ec; pos += 1;
7047            *dst.add(pos) = b'+'; pos += 1;
7048            *dst.add(pos) = b'0'; pos += 1;
7049            *dst.add(pos) = b'0'; pos += 1;
7050        }
7051        return pos;
7052    }
7053
7054    // === %f format: exact bit-based arithmetic, returns early ===
7055    if use_f {
7056        let bits = v.to_bits();
7057        let raw_mant = bits & 0x000FFFFFFFFFFFFF;
7058        let raw_exp_bits = ((bits >> 52) & 0x7FF) as i32;
7059        let (mant_b, bin_exp) = if raw_exp_bits == 0 {
7060            (raw_mant, -1022i32)
7061        } else {
7062            (raw_mant | (1u64 << 52), raw_exp_bits - 1023)
7063        };
7064
7065        // Integer part as decimal string
7066        let mut ibuf = [0u8; 400];
7067        let mut ilen: usize;
7068        if bin_exp < 0 {
7069            ibuf[0] = b'0'; ilen = 1;
7070        } else if bin_exp <= 63 {
7071            let int_val = if bin_exp <= 52 { mant_b >> (52 - bin_exp) }
7072                          else { mant_b << (bin_exp - 52) };
7073            let (buf2, len2) = format_u64(int_val);
7074            ibuf[..len2].copy_from_slice(&buf2[..len2]);
7075            ilen = len2;
7076        } else {
7077            ilen = bigint_to_decimal(ibuf.as_mut_ptr(), mant_b, (bin_exp - 52) as u32);
7078        }
7079
7080        // Fractional digits
7081        let mut fbuf = [0u8; 1100];
7082        let mut has_rest = false;
7083        if p > 0 && bin_exp < 52 {
7084            let shift = (52 - bin_exp) as u32;
7085            let frac_bits = if bin_exp >= 0 { mant_b & ((1u64 << shift) - 1) } else { mant_b };
7086            if shift <= 124 {
7087                has_rest = frac_digits_u128(fbuf.as_mut_ptr(), frac_bits, shift, p + 1);
7088            } else {
7089                has_rest = frac_digits_bigint(fbuf.as_mut_ptr(), frac_bits, shift, p + 1);
7090            }
7091        }
7092
7093        // Rounding
7094        if p > 0 && bin_exp < 52 {
7095            let next_d = fbuf[p];
7096            let last_d = fbuf[p - 1];
7097            if next_d > 5 || (next_d == 5 && (has_rest || last_d & 1 != 0)) {
7098                let mut carry = true;
7099                for j in (0..p).rev() {
7100                    if !carry { break; }
7101                    fbuf[j] += 1;
7102                    if fbuf[j] < 10 { carry = false; break; }
7103                    fbuf[j] = 0;
7104                }
7105                if carry { increment_decimal(ibuf.as_mut_ptr(), &mut ilen); }
7106            }
7107        } else if p == 0 {
7108            // %.0f: round integer based on fractional part
7109            if bin_exp >= 0 && bin_exp < 52 {
7110                let shift = (52 - bin_exp) as u32;
7111                let frac_bits = mant_b & ((1u64 << shift) - 1);
7112                let half = 1u64 << (shift - 1);
7113                let last_d = ibuf[ilen - 1] - b'0';
7114                if frac_bits > half || (frac_bits == half && last_d & 1 != 0) {
7115                    increment_decimal(ibuf.as_mut_ptr(), &mut ilen);
7116                }
7117            }
7118        }
7119
7120        // Output
7121        core::ptr::copy_nonoverlapping(ibuf.as_ptr(), dst.add(pos), ilen);
7122        pos += ilen;
7123        if p > 0 || flags & FLAG_HASH != 0 {
7124            *dst.add(pos) = b'.'; pos += 1;
7125            for i in 0..p { *dst.add(pos) = b'0' + fbuf[i]; pos += 1; }
7126        }
7127        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7128            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7129            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7130        }
7131        return pos;
7132    }
7133
7134    // === %e/%g format: exact big-integer digit extraction ===
7135    // D = floor(v * 10^(p+1-exp)), using v = mant_b * 2^(bin_exp-52)
7136    let mut fbuf = [0u8; 20];
7137    let mut int_part: u64;
7138    {
7139        let bits_v = v.to_bits();
7140        let raw_mant_v = bits_v & 0x000FFFFFFFFFFFFF;
7141        let raw_exp_v = ((bits_v >> 52) & 0x7FF) as i32;
7142        let (mant_b_v, bin_exp_v) = if raw_exp_v == 0 {
7143            (raw_mant_v, -1022i32)
7144        } else {
7145            (raw_mant_v | (1u64 << 52), raw_exp_v - 1023)
7146        };
7147
7148        let s: i32 = (p as i32) + 1 - exp;
7149        let bs: i32 = bin_exp_v - 52 + s;
7150
7151        let mut limbs = [0u32; 40];
7152        limbs[0] = mant_b_v as u32;
7153        limbs[1] = (mant_b_v >> 32) as u32;
7154        let mut nlimbs: usize = if limbs[1] != 0 { 2 } else { 1 };
7155
7156        if s > 0 {
7157            for _ in 0..(s as usize) {
7158                let mut carry = 0u64;
7159                for j in 0..nlimbs {
7160                    let val = limbs[j] as u64 * 5 + carry;
7161                    limbs[j] = val as u32;
7162                    carry = val >> 32;
7163                }
7164                if carry > 0 { limbs[nlimbs] = carry as u32; nlimbs += 1; }
7165            }
7166        }
7167
7168        if bs > 0 {
7169            let ws = (bs as u32 / 32) as usize;
7170            let bit = bs as u32 % 32;
7171            if ws > 0 {
7172                let mut i = nlimbs;
7173                while i > 0 { i -= 1; if i + ws < 40 { limbs[i + ws] = limbs[i]; } limbs[i] = 0; }
7174                nlimbs += ws;
7175            }
7176            if bit > 0 {
7177                let mut carry = 0u32;
7178                for i in ws..nlimbs {
7179                    let new_val = (limbs[i] << bit) | carry;
7180                    carry = limbs[i] >> (32 - bit);
7181                    limbs[i] = new_val;
7182                }
7183                if carry > 0 && nlimbs < 40 { limbs[nlimbs] = carry; nlimbs += 1; }
7184            }
7185        }
7186
7187        let mut has_rest = false;
7188        if s < 0 {
7189            for _ in 0..(-s as usize) {
7190                let mut rem = 0u64;
7191                for i in (0..nlimbs).rev() {
7192                    let val = (rem << 32) | limbs[i] as u64;
7193                    limbs[i] = (val / 5) as u32;
7194                    rem = val % 5;
7195                }
7196                if rem != 0 { has_rest = true; }
7197            }
7198        }
7199
7200        if bs < 0 {
7201            let rshift = (-bs) as u32;
7202            let ws = (rshift / 32) as usize;
7203            let bit = rshift % 32;
7204            if ws > 0 {
7205                for j in 0..ws.min(nlimbs) { if limbs[j] != 0 { has_rest = true; } }
7206                for i in ws..nlimbs { limbs[i - ws] = limbs[i]; }
7207                nlimbs = nlimbs.saturating_sub(ws);
7208            }
7209            if bit > 0 && nlimbs > 0 {
7210                let mask = (1u32 << bit) - 1;
7211                if limbs[0] & mask != 0 { has_rest = true; }
7212                for i in 0..nlimbs - 1 {
7213                    limbs[i] = (limbs[i] >> bit) | (limbs[i + 1] << (32 - bit));
7214                }
7215                limbs[nlimbs - 1] >>= bit;
7216            }
7217        }
7218
7219        while nlimbs > 0 && limbs[nlimbs - 1] == 0 { nlimbs -= 1; }
7220
7221        let ndigits = p + 2;
7222        let mut all_digits = [0u8; 25];
7223        let mut nd = 0usize;
7224        if nlimbs > 0 {
7225            loop {
7226                let mut all_zero = true;
7227                for i in 0..nlimbs { if limbs[i] != 0 { all_zero = false; break; } }
7228                if all_zero { break; }
7229                let mut rem64 = 0u64;
7230                for i in (0..nlimbs).rev() {
7231                    let val = (rem64 << 32) | limbs[i] as u64;
7232                    limbs[i] = (val / 10) as u32;
7233                    rem64 = val % 10;
7234                }
7235                if nd < 25 { all_digits[nd] = rem64 as u8; }
7236                nd += 1;
7237            }
7238        }
7239
7240        if nd >= ndigits {
7241            for i in 0..ndigits { fbuf[ndigits - 1 - i] = all_digits[i]; }
7242        } else {
7243            for i in 0..nd { fbuf[ndigits - 1 - i] = all_digits[i]; }
7244            for i in nd..ndigits { fbuf[ndigits - 1 - i] = 0; }
7245        }
7246
7247        int_part = fbuf[0] as u64;
7248
7249        // Round half to even: next_d is the rounding digit beyond precision
7250        if p > 0 {
7251            let next_d = fbuf[p + 1];
7252            let last_d = fbuf[p];
7253            if next_d > 5 || (next_d == 5 && (has_rest || last_d & 1 != 0)) {
7254                let mut carry = true;
7255                for j in (1..=p).rev() {
7256                    if !carry { break; }
7257                    let d = fbuf[j] + 1;
7258                    if d < 10 { fbuf[j] = d; carry = false; break; }
7259                    fbuf[j] = 0;
7260                }
7261                if carry { int_part += 1; }
7262            }
7263        } else {
7264            let next_d = fbuf[1];
7265            if next_d > 5 || (next_d == 5 && (has_rest || int_part & 1 != 0)) {
7266                int_part += 1;
7267            }
7268        }
7269
7270        // fbuf[1..=p] are now the fractional digits for output
7271        // Shift them to fbuf[0..p] so output code can index fbuf[0..p]
7272        for i in 0..p { fbuf[i] = fbuf[i + 1]; }
7273    }
7274
7275    if !use_f && int_part >= 10 {
7276        exp += 1;
7277        int_part = 1;
7278    }
7279
7280    // Format output
7281    if use_f {
7282        // %f style
7283        let (ibuf, ilen) = format_u64(int_part);
7284        core::ptr::copy_nonoverlapping(ibuf.as_ptr(), dst.add(pos), ilen);
7285        pos += ilen;
7286        if p > 0 || flags & FLAG_HASH != 0 {
7287            *dst.add(pos) = b'.'; pos += 1;
7288            for idx in 0..p { *dst.add(pos) = b'0' + fbuf[idx]; pos += 1; }
7289        }
7290        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7291            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7292            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7293        }
7294    } else {
7295        // %e style
7296        *dst.add(pos) = b'0' + int_part as u8; pos += 1;
7297        if p > 0 || flags & FLAG_HASH != 0 {
7298            *dst.add(pos) = b'.'; pos += 1;
7299            for idx in 0..p { *dst.add(pos) = b'0' + fbuf[idx]; pos += 1; }
7300        }
7301        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7302            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7303            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7304        }
7305        let ec = if uppercase { b'E' } else { b'e' };
7306        *dst.add(pos) = ec; pos += 1;
7307        *dst.add(pos) = if exp < 0 { b'-' } else { b'+' }; pos += 1;
7308        let eabs = if exp < 0 { (-exp) as u32 } else { exp as u32 };
7309        if eabs < 10 { *dst.add(pos) = b'0'; pos += 1; }
7310        let (ebuf, elen) = format_u64(eabs as u64);
7311        core::ptr::copy_nonoverlapping(ebuf.as_ptr(), dst.add(pos), elen);
7312        pos += elen;
7313    }
7314
7315    pos
7316}
7317
7318// Compute decimal exponent: floor(log10(v)) with correction
7319unsafe fn compute_exp10(v: f64) -> i32 {
7320    let e = libm::floor(libm::log10(v)) as i32;
7321    let probe = v / libm::pow(10.0, e as f64);
7322    if probe >= 10.0 { e + 1 }
7323    else if probe < 1.0 { e - 1 }
7324    else { e }
7325}
7326
7327// Write hex float to dst. Returns bytes written.
7328unsafe fn fmt_hex_float(dst: *mut u8, val: f64, precision: i32, _flags: u8, uppercase: bool) -> usize {
7329    // Handle zero (and negative zero) specially
7330    if val.to_bits() & 0x7FFFFFFFFFFFFFFF == 0 {
7331        let lc = !uppercase;
7332        let pfx: &[u8] = if lc { b"0x" } else { b"0X" };
7333        let p = if precision < 0 { 0usize } else { precision as usize };
7334        let mut pos = 0usize;
7335        core::ptr::copy_nonoverlapping(pfx.as_ptr(), dst.add(pos), 2); pos += 2;
7336        *dst.add(pos) = b'0'; pos += 1;
7337        if p > 0 {
7338            *dst.add(pos) = b'.'; pos += 1;
7339            for _ in 0..p { *dst.add(pos) = b'0'; pos += 1; }
7340        }
7341        let pc = if lc { b'p' } else { b'P' };
7342        *dst.add(pos) = pc; pos += 1;
7343        *dst.add(pos) = b'+'; pos += 1;
7344        *dst.add(pos) = b'0'; pos += 1;
7345        return pos;
7346    }
7347    let bits = val.to_bits();
7348    let exp_bits = ((bits >> 52) & 0x7FF) as i32;
7349    let mant_bits = bits & 0x000FFFFFFFFFFFFF;
7350    let (mut e, mut m) = if exp_bits == 0 { (1 - 1023, mant_bits) } else { (exp_bits - 1023, mant_bits | (1u64 << 52)) };
7351    // musl normalizes subnormals so the leading digit is always 1, which
7352    // lets the exponent go below -1022 (e.g. 0x1p-1074 for the smallest).
7353    if exp_bits == 0 && m != 0 {
7354        let shift = m.leading_zeros() as i32 - 11;
7355        m <<= shift;
7356        e -= shift;
7357    }
7358    let explicit = precision >= 0;
7359    let p = if explicit { precision as usize } else { 13usize };
7360    let mut pos = 0usize;
7361    let lc = !uppercase;
7362    let pfx: &[u8] = if lc { b"0x" } else { b"0X" };
7363    core::ptr::copy_nonoverlapping(pfx.as_ptr(), dst.add(pos), 2); pos += 2;
7364
7365    // Leading digit from bit 52 (1 for every normalized value).
7366    let lead_pos = pos;
7367    let mut lead = ((m >> 52) & 0xF) as u8;
7368    *dst.add(pos) = hex_digit_char(lead, lc); pos += 1;
7369    let mut frac_start = pos;
7370    if p > 0 {
7371        *dst.add(pos) = b'.'; pos += 1;
7372        frac_start = pos;
7373    }
7374
7375    // Extract p hex digits from the fraction, most significant nibble first.
7376    let mut rm = m;
7377    for _ in 0..p {
7378        let nib = ((rm >> 48) & 0xF) as u8;
7379        *dst.add(pos) = hex_digit_char(nib, lc); pos += 1;
7380        rm <<= 4;
7381    }
7382
7383    // Round to nearest, ties to even, based on the next nibble.
7384    let round_nib = ((rm >> 48) & 0xF) as u8;
7385    let rest = rm & 0x0000FFFFFFFFFFFF;
7386    let last_nib = if p > 0 {
7387        hex_char_val(*dst.add(pos - 1))
7388    } else {
7389        lead
7390    };
7391    let should_round = round_nib > 8 || (round_nib == 8 && (rest != 0 || (last_nib & 1) != 0));
7392    if should_round {
7393        let mut j = pos;
7394        loop {
7395            if j == frac_start {
7396                // Carry out of the fraction into the leading digit.
7397                lead += 1;
7398                *dst.add(lead_pos) = hex_digit_char(lead, lc);
7399                break;
7400            }
7401            j -= 1;
7402            let v = hex_char_val(*dst.add(j));
7403            if v < 15 {
7404                *dst.add(j) = hex_digit_char(v + 1, lc);
7405                break;
7406            }
7407            *dst.add(j) = b'0';
7408        }
7409    }
7410
7411    // With no explicit precision, print the shortest exact representation:
7412    // trim trailing fractional zeros and drop the radix point if empty.
7413    if !explicit {
7414        while pos > frac_start && *dst.add(pos - 1) == b'0' {
7415            pos -= 1;
7416        }
7417        if pos == frac_start {
7418            pos = frac_start - 1;
7419        }
7420    }
7421
7422    // Exponent
7423    let pc = if lc { b'p' } else { b'P' };
7424    *dst.add(pos) = pc; pos += 1;
7425    *dst.add(pos) = if e < 0 { b'-' } else { b'+' }; pos += 1;
7426    let eabs = if e < 0 { (-e) as u32 } else { e as u32 };
7427    let (ebuf, elen) = format_u64(eabs as u64);
7428    core::ptr::copy_nonoverlapping(ebuf.as_ptr(), dst.add(pos), elen);
7429    pos += elen;
7430    pos
7431}
7432
7433#[inline]
7434fn hex_digit_char(v: u8, lowercase: bool) -> u8 {
7435    if v < 10 { b'0' + v }
7436    else if lowercase { b'a' + v - 10 }
7437    else { b'A' + v - 10 }
7438}
7439
7440#[inline]
7441fn hex_char_val(c: u8) -> u8 {
7442    if c >= b'0' && c <= b'9' { c - b'0' }
7443    else if c >= b'a' && c <= b'f' { c - b'a' + 10 }
7444    else if c >= b'A' && c <= b'F' { c - b'A' + 10 }
7445    else { 0 }
7446}
7447
7448// Apply width and flags padding to a formatted string in buf[0..len].
7449// Writes the final result to dst. Returns total bytes written.
7450unsafe fn apply_width_flags(
7451    dst: *mut u8, buf: *const u8, len: usize, width: usize, flags: u8,
7452) -> usize {
7453    if len >= width {
7454        core::ptr::copy_nonoverlapping(buf, dst, len);
7455        return len;
7456    }
7457    let pad = width - len;
7458    let pad_char = if flags & FLAG_ZERO != 0 && flags & FLAG_MINUS == 0 { b'0' } else { b' ' };
7459    if flags & FLAG_MINUS != 0 {
7460        // Left align
7461        core::ptr::copy_nonoverlapping(buf, dst, len);
7462        for i in 0..pad { *dst.add(len + i) = pad_char; }
7463    } else {
7464        // Right align
7465        // For zero-padded numbers, sign goes before zeros
7466        if flags & FLAG_ZERO != 0 && len > 0 {
7467            let first = *buf;
7468            if first == b'-' || first == b'+' || first == b' ' {
7469                *dst = first;
7470                for i in 0..pad { *dst.add(1 + i) = pad_char; }
7471                core::ptr::copy_nonoverlapping(buf.add(1), dst.add(1 + pad), len - 1);
7472                return width;
7473            }
7474        }
7475        for i in 0..pad { *dst.add(i) = pad_char; }
7476        core::ptr::copy_nonoverlapping(buf, dst.add(pad), len);
7477    }
7478    width
7479}
7480
7481#[no_mangle]
7482pub unsafe extern "C" fn vprintf(fmt: *const c_char, mut args: VaList) -> c_int {
7483    impl_format!(fmt, args,
7484        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stdout); },
7485        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stdout); }
7486    )
7487}
7488
7489#[no_mangle]
7490pub unsafe extern "C" fn vfprintf(stream: *mut FILE, fmt: *const c_char, mut args: VaList) -> c_int {
7491    impl_format!(fmt, args,
7492        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stream); },
7493        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stream); }
7494    )
7495}
7496
7497#[no_mangle]
7498pub unsafe extern "C" fn printf(fmt: *const c_char, mut args: ...) -> c_int {
7499    impl_format!(fmt, args,
7500        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stdout); },
7501        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stdout); }
7502    )
7503}
7504
7505#[no_mangle]
7506pub unsafe extern "C" fn fprintf(stream: *mut FILE, fmt: *const c_char, mut args: ...) -> c_int {
7507    impl_format!(fmt, args,
7508        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stream); },
7509        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stream); }
7510    )
7511}
7512
7513#[no_mangle]
7514unsafe fn format_write_fd(fd: c_int, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
7515    // cgroupfs (and some other pseudo-filesystems) parse one command per
7516    // write() call, so the whole formatted string must go out at once.
7517    let mut stack = [0u8; 4096];
7518    let mut a1 = args.clone();
7519    let n = format_to_buf(stack.as_mut_ptr(), stack.len(), fmt, &mut a1);
7520    if n < 0 { return -1; }
7521    if (n as usize) < stack.len() {
7522        let w = crate::write(fd, stack.as_ptr() as *const c_void, n as usize);
7523        if w < 0 { return -1; }
7524        return n;
7525    }
7526    let heap = crate::malloc(n as usize + 1) as *mut u8;
7527    if heap.is_null() { return -1; }
7528    let mut a2 = args.clone();
7529    let n2 = format_to_buf(heap, n as usize + 1, fmt, &mut a2);
7530    if n2 < 0 { crate::free(heap as *mut c_void); return -1; }
7531    let w = crate::write(fd, heap as *const c_void, n2 as usize);
7532    crate::free(heap as *mut c_void);
7533    if w < 0 { return -1; }
7534    n2
7535}
7536
7537#[no_mangle]
7538pub unsafe extern "C" fn dprintf(fd: c_int, fmt: *const c_char, mut args: ...) -> c_int {
7539    format_write_fd(fd, fmt, &mut args)
7540}
7541
7542#[no_mangle]
7543pub unsafe extern "C" fn vdprintf(fd: c_int, fmt: *const c_char, mut args: VaList) -> c_int {
7544    format_write_fd(fd, fmt, &mut args)
7545}
7546
7547// ============================================================
7548// sprintf / snprintf / vsprintf / vsnprintf
7549// ============================================================
7550
7551unsafe fn format_to_buf(buf: *mut u8, cap: usize, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
7552    let mut pos = 0usize;
7553    let mut i = 0usize;
7554    let mut count = 0usize;
7555    macro_rules! wc {
7556        ($c:expr) => { if pos < cap { *buf.add(pos) = $c; } pos += 1; count += 1; }
7557    }
7558    macro_rules! ws {
7559        ($s:expr, $len:expr) => {{
7560            let __len = $len;
7561            for k in 0..__len { if pos + k < cap { *buf.add(pos + k) = *$s.add(k); } }
7562            pos += __len; count += __len;
7563        }}
7564    }
7565    // Write formatted buffer respecting cap, at current pos
7566    macro_rules! ws_buf {
7567        ($src:expr, $len:expr) => {{
7568            let __len = $len;
7569            for k in 0..__len { if pos + k < cap { *buf.add(pos + k) = *$src.add(k); } }
7570            pos += __len; count += __len;
7571        }}
7572    }
7573    loop {
7574        let c = *fmt.add(i) as u8;
7575        if c == 0 { break; }
7576        if c != b'%' { wc!(c); i += 1; continue; }
7577        i += 1;
7578        // Parse flags
7579        let mut flags: u8 = 0;
7580        loop {
7581            let fc = *fmt.add(i) as u8;
7582            match fc {
7583                b'-' => { flags |= FLAG_MINUS; i += 1; }
7584                b'+' => { flags |= FLAG_PLUS; i += 1; }
7585                b' ' => { flags |= FLAG_SPACE; i += 1; }
7586                b'0' => { flags |= FLAG_ZERO; i += 1; }
7587                b'#' => { flags |= FLAG_HASH; i += 1; }
7588                _ => break,
7589            }
7590        }
7591        // Parse width
7592        let mut width: usize = 0;
7593        if *fmt.add(i) as u8 == b'*' {
7594            width = args.next_arg::<c_int>() as usize; i += 1;
7595        } else {
7596            while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
7597                width = width * 10 + ((*fmt.add(i) as u8) - b'0') as usize; i += 1;
7598            }
7599        }
7600        // Parse precision
7601        let mut precision: i32 = -1;
7602        if *fmt.add(i) as u8 == b'.' {
7603            i += 1;
7604            if *fmt.add(i) as u8 == b'*' {
7605                precision = args.next_arg::<c_int>(); i += 1;
7606            } else {
7607                precision = 0;
7608                while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
7609                    precision = precision * 10 + ((*fmt.add(i) as u8) - b'0') as i32; i += 1;
7610                }
7611            }
7612        }
7613        // Parse length modifier
7614        let len_mod = *fmt.add(i) as u8;
7615        let spec: u8;
7616        if len_mod == b'h' || len_mod == b'l' || len_mod == b'j' || len_mod == b'z' || len_mod == b't' || len_mod == b'L' {
7617            i += 1;
7618            let len_mod2 = *fmt.add(i) as u8;
7619            if (len_mod == b'h' && len_mod2 == b'h') || (len_mod == b'l' && len_mod2 == b'l') {
7620                i += 1;
7621                spec = *fmt.add(i) as u8;
7622                match (len_mod, len_mod2, spec) {
7623                    (b'h', b'h', b'n') => {
7624                        let p = args.next_arg::<*mut c_void>();
7625                        if !p.is_null() { *(p as *mut u8) = count as u8; }
7626                    }
7627                    (b'l', b'l', b'n') => {
7628                        let p = args.next_arg::<*mut c_void>();
7629                        if !p.is_null() { *(p as *mut c_longlong) = count as c_longlong; }
7630                    }
7631                    (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
7632                        let val = args.next_arg::<c_longlong>();
7633                        let neg = val < 0;
7634                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
7635                        let b = format_u64(abs);
7636                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
7637                        let mut fbuf = [0u8; 32];
7638                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
7639                        ws_buf!(fbuf.as_ptr(), len);
7640                    }
7641                    (b'l', b'l', b'u') => {
7642                        let val = args.next_arg::<c_ulonglong>();
7643                        let b = format_u64(val as u64);
7644                        let mut fbuf = [0u8; 32];
7645                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
7646                        ws_buf!(fbuf.as_ptr(), len);
7647                    }
7648                    (b'l', b'l', b'o') => {
7649                        let val = args.next_arg::<c_ulonglong>();
7650                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
7651                        let mut fbuf = [0u8; 32];
7652                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
7653                        ws_buf!(fbuf.as_ptr(), len);
7654                    }
7655                    (b'l', b'l', b'x') | (b'l', b'l', b'X') => {
7656                        let val = args.next_arg::<c_ulonglong>();
7657                        let b = format_hex(val as u64, spec == b'X');
7658                        let pc = if spec == b'X' { b'X' } else { b'x' };
7659                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(pc) } else { None };
7660                        let mut fbuf = [0u8; 32];
7661                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7662                        ws_buf!(fbuf.as_ptr(), len);
7663                    }
7664                    _ => { wc!(b'%'); wc!(len_mod); wc!(len_mod2); wc!(spec); }
7665                }
7666            } else {
7667                spec = len_mod2;
7668                let lm = if (len_mod == b'z' || len_mod == b't') && spec != b'n' { b'l' } else { len_mod };
7669                match (lm, spec) {
7670                    (b'h', b'n') => {
7671                        let p = args.next_arg::<*mut c_void>();
7672                        if !p.is_null() { *(p as *mut u16) = count as u16; }
7673                    }
7674                    (b'l', b'n') => {
7675                        let p = args.next_arg::<*mut c_void>();
7676                        if !p.is_null() { *(p as *mut c_long) = count as c_long; }
7677                    }
7678                    (b'z', b'n') | (b't', b'n') => {
7679                        let p = args.next_arg::<*mut c_void>();
7680                        if !p.is_null() { *(p as *mut usize) = count; }
7681                    }
7682                    (b'j', b'n') => {
7683                        let p = args.next_arg::<*mut c_void>();
7684                        if !p.is_null() { *(p as *mut c_ulonglong) = count as c_ulonglong; }
7685                    }
7686                    (b'l', b'd') | (b'l', b'i') => {
7687                        let val = args.next_arg::<c_long>();
7688                        let neg = val < 0;
7689                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
7690                        let b = format_u64(abs);
7691                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
7692                        let mut fbuf = [0u8; 32];
7693                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
7694                        ws_buf!(fbuf.as_ptr(), len);
7695                    }
7696                    (b'l', b'u') => {
7697                        let val = args.next_arg::<c_ulong>();
7698                        let b = format_u64(val as u64);
7699                        let mut fbuf = [0u8; 32];
7700                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
7701                        ws_buf!(fbuf.as_ptr(), len);
7702                    }
7703                    (b'l', b's') => {
7704                        let p = args.next_arg::<*const wchar_t>();
7705                        if p.is_null() {
7706                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
7707                            let pad = width.saturating_sub(slen);
7708                            if flags & FLAG_MINUS != 0 { ws!(b"(null)".as_ptr(), slen); for _ in 0..pad { wc!(b' '); } }
7709                            else { for _ in 0..pad { wc!(b' '); } ws!(b"(null)".as_ptr(), slen); }
7710                        } else {
7711                            let mut mb = [0u8; 4096];
7712                            let mut n = wide_to_mb(mb.as_mut_ptr(), mb.len(), p);
7713                            if precision >= 0 && (precision as usize) < n { n = precision as usize; }
7714                            let pad = width.saturating_sub(n);
7715                            if flags & FLAG_MINUS != 0 { ws!(mb.as_ptr(), n); for _ in 0..pad { wc!(b' '); } }
7716                            else { for _ in 0..pad { wc!(b' '); } ws!(mb.as_ptr(), n); }
7717                        }
7718                    }
7719                    (b'l', b'c') => {
7720                        let ch = args.next_arg::<c_int>();
7721                        let mut mb = [0u8; 8];
7722                        let mut st: c_uint = 0;
7723                        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, ch, &mut st);
7724                        if n != !0usize { ws!(mb.as_ptr(), n); }
7725                    }
7726                    (b'l', b'x') => {
7727                        let val = args.next_arg::<c_ulong>();
7728                        let b = format_hex(val as u64, false);
7729                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
7730                        let mut fbuf = [0u8; 32];
7731                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7732                        ws_buf!(fbuf.as_ptr(), len);
7733                    }
7734                    (b'l', b'X') => {
7735                        let val = args.next_arg::<c_ulong>();
7736                        let b = format_hex(val as u64, true);
7737                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
7738                        let mut fbuf = [0u8; 32];
7739                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7740                        ws_buf!(fbuf.as_ptr(), len);
7741                    }
7742                    (b'l', b'o') => {
7743                        let val = args.next_arg::<c_ulong>();
7744                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
7745                        let mut fbuf = [0u8; 32];
7746                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
7747                        ws_buf!(fbuf.as_ptr(), len);
7748                    }
7749                    (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
7750                    | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
7751                        let val = args.next_arg::<f64>();
7752                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
7753                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
7754                        let mut fbuf = [0u8; 4224];
7755                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
7756                        let mut wbuf = [0u8; 4224];
7757                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
7758                        ws_buf!(wbuf.as_ptr(), wlen);
7759                    }
7760                    (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
7761                    | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
7762                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
7763                        let val = {
7764                            let lo: u64 = args.next_arg::<u64>();
7765                            let hi: u64 = args.next_arg::<u64>();
7766                            let combined: u128 = ((hi as u128) << 64) | (lo as u128);
7767                            f128::from_bits(combined) as f64
7768                        };
7769                        #[cfg(target_arch = "x86_64")]
7770                        let val = args.next_arg::<f64>();
7771                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
7772                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
7773                        let mut fbuf = [0u8; 4224];
7774                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
7775                        let mut wbuf = [0u8; 4224];
7776                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
7777                        ws_buf!(wbuf.as_ptr(), wlen);
7778                    }
7779                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); }
7780                }
7781            }
7782        } else {
7783            spec = *fmt.add(i) as u8;
7784            match spec {
7785                b's' => {
7786                    let s = args.next_arg::<*const c_char>();
7787                    if s.is_null() {
7788                        let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
7789                        let padded_len = if width > slen { width } else { slen };
7790                        let pad = padded_len - slen;
7791                        if flags & FLAG_MINUS != 0 {
7792                            ws!(b"(null)".as_ptr(), slen);
7793                            for _ in 0..pad { wc!(b' '); }
7794                        } else {
7795                            for _ in 0..pad { wc!(b' '); }
7796                            ws!(b"(null)".as_ptr(), slen);
7797                        }
7798                    } else {
7799                        let full_len = strlen(s as *const c_char);
7800                        let slen = if precision >= 0 { (precision as usize).min(full_len) } else { full_len };
7801                        let padded_len = if width > slen { width } else { slen };
7802                        let pad = padded_len - slen;
7803                        if flags & FLAG_MINUS != 0 {
7804                            ws!(s as *const u8, slen);
7805                            for _ in 0..pad { wc!(b' '); }
7806                        } else {
7807                            for _ in 0..pad { wc!(b' '); }
7808                            ws!(s as *const u8, slen);
7809                        }
7810                    }
7811                }
7812                b'd' | b'i' => {
7813                    let d = args.next_arg::<c_int>();
7814                    let neg = d < 0;
7815                    let abs = if neg { d.wrapping_neg() as u64 } else { d as u64 };
7816                    let b = format_u64(abs);
7817                    let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
7818                    let mut fbuf = [0u8; 32];
7819                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
7820                    ws_buf!(fbuf.as_ptr(), len);
7821                }
7822                b'u' => {
7823                    let u = args.next_arg::<c_uint>();
7824                    let b = format_u64(u as u64);
7825                    let mut fbuf = [0u8; 32];
7826                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
7827                    ws_buf!(fbuf.as_ptr(), len);
7828                }
7829                b'x' => {
7830                    let x = args.next_arg::<c_uint>();
7831                    let b = format_hex(x as u64, false);
7832                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
7833                    let mut fbuf = [0u8; 32];
7834                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7835                    ws_buf!(fbuf.as_ptr(), len);
7836                }
7837                b'X' => {
7838                    let x = args.next_arg::<c_uint>();
7839                    let b = format_hex(x as u64, true);
7840                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
7841                    let mut fbuf = [0u8; 32];
7842                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7843                    ws_buf!(fbuf.as_ptr(), len);
7844                }
7845                b'o' => {
7846                    let o = args.next_arg::<c_uint>();
7847                    let b = format_octal(o as u64, flags & FLAG_HASH != 0);
7848                    let mut fbuf = [0u8; 32];
7849                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
7850                    ws_buf!(fbuf.as_ptr(), len);
7851                }
7852                b'c' => {
7853                    let ch = args.next_arg::<c_int>();
7854                    if width > 1 {
7855                        let pad = width - 1;
7856                        if flags & FLAG_MINUS != 0 {
7857                            wc!(ch as u8);
7858                            for _ in 0..pad { wc!(b' '); }
7859                        } else {
7860                            for _ in 0..pad { wc!(b' '); }
7861                            wc!(ch as u8);
7862                        }
7863                    } else {
7864                        wc!(ch as u8);
7865                    }
7866                }
7867                b'p' => {
7868                    wc!(b'0'); wc!(b'x');
7869                    let p = args.next_arg::<*const c_void>();
7870                    let b = format_hex(p as u64, false);
7871                    ws!(b.0.as_ptr(), b.1);
7872                }
7873                b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
7874                    let val = args.next_arg::<f64>();
7875                    let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
7876                    let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
7877                    let mut fbuf = [0u8; 4224];
7878                    let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
7879                    let mut wbuf = [0u8; 4224];
7880                    let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
7881                    ws_buf!(wbuf.as_ptr(), wlen);
7882                }
7883                b'%' => { wc!(b'%'); }
7884                b'n' => {
7885                    let p = args.next_arg::<*mut c_void>();
7886                    if !p.is_null() { *(p as *mut c_int) = count as c_int; }
7887                }
7888                _ => { wc!(b'%'); wc!(spec); }
7889            }
7890        }
7891        i += 1;
7892    }
7893    if cap > 0 { let null_pos = if pos < cap { pos } else { cap - 1 }; *buf.add(null_pos) = 0; }
7894    count as c_int
7895}
7896
7897#[no_mangle]
7898pub unsafe extern "C" fn vsprintf(buf: *mut c_char, fmt: *const c_char, mut args: VaList) -> c_int {
7899    format_to_buf(buf as *mut u8, usize::MAX, fmt, &mut args)
7900}
7901
7902#[no_mangle]
7903pub unsafe extern "C" fn vsnprintf(buf: *mut c_char, size: usize, fmt: *const c_char, mut args: VaList) -> c_int {
7904    format_to_buf(buf as *mut u8, size, fmt, &mut args)
7905}
7906
7907#[no_mangle]
7908pub unsafe extern "C" fn sprintf(buf: *mut c_char, fmt: *const c_char, mut args: ...) -> c_int {
7909    format_to_buf(buf as *mut u8, usize::MAX, fmt, &mut args)
7910}
7911
7912#[no_mangle]
7913pub unsafe extern "C" fn snprintf(buf: *mut c_char, size: usize, fmt: *const c_char, mut args: ...) -> c_int {
7914    format_to_buf(buf as *mut u8, size, fmt, &mut args)
7915}
7916
7917#[no_mangle]
7918pub unsafe extern "C" fn vasprintf(strp: *mut *mut c_char, fmt: *const c_char, ap: VaList) -> c_int {
7919    let len = vsnprintf(core::ptr::null_mut(), 0, fmt, ap.clone());
7920    if len < 0 {
7921        *strp = core::ptr::null_mut();
7922        return -1;
7923    }
7924    let p = malloc((len as usize) + 1) as *mut c_char;
7925    if p.is_null() {
7926        *strp = core::ptr::null_mut();
7927        return -1;
7928    }
7929    let ret = vsnprintf(p, (len as usize) + 1, fmt, ap.clone());
7930    if ret < 0 {
7931        free(p as *mut c_void);
7932        *strp = core::ptr::null_mut();
7933        return -1;
7934    }
7935    *strp = p;
7936    ret
7937}
7938
7939#[no_mangle]
7940pub unsafe extern "C" fn asprintf(strp: *mut *mut c_char, fmt: *const c_char, args: ...) -> c_int {
7941    vasprintf(strp, fmt, args)
7942}
7943
7944// ============================================================
7945// scanf / vscanf / fscanf / vfscanf / sscanf / vsscanf
7946// ============================================================
7947
7948unsafe fn skip_ws(p: *const u8) -> *const u8 {
7949    let mut q = p;
7950    while *q == b' ' || *q == b'\t' || *q == b'\n' || *q == b'\r' { q = q.add(1); }
7951    q
7952}
7953
7954#[inline]
7955fn is_ws_byte(c: u8) -> bool {
7956    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == 0x0b || c == 0x0c
7957}
7958
7959// Scan integer with position tracking. Returns (value, is_negative, success).
7960// base: 0=auto, 8=octal, 10=decimal, 16=hex
7961unsafe fn scan_int_val(
7962    buf: *const u8, pos: &mut usize, buf_len: usize, base: u32, width: usize,
7963) -> (u64, bool, bool) {
7964    let start = *pos;
7965    let max = if width > 0 { (start + width).min(buf_len) } else { buf_len };
7966    let neg = if *pos < max && *buf.add(*pos) == b'-' { *pos += 1; true }
7967    else if *pos < max && *buf.add(*pos) == b'+' { *pos += 1; false }
7968    else { false };
7969    if *pos >= max { *pos = start; return (0, false, false); }
7970    let mut base = base;
7971    let mut val: u64 = 0;
7972    // Auto-detect base / handle 0x prefix
7973    if (base == 0 || base == 16) && *pos < max && *buf.add(*pos) == b'0' {
7974        *pos += 1;
7975        if *pos < max && (*buf.add(*pos) == b'x' || *buf.add(*pos) == b'X') {
7976            *pos += 1;
7977            if *pos < max {
7978                if let Some(d) = hex_val(*buf.add(*pos)) {
7979                    val = d as u64; *pos += 1;
7980                    while *pos < max { if let Some(d) = hex_val(*buf.add(*pos)) { val = val.wrapping_mul(16).wrapping_add(d as u64); *pos += 1; } else { break; } }
7981                    return (val, neg, true);
7982                }
7983            }
7984            return (0, neg, false);
7985        } else if base == 0 {
7986            while *pos < max { let c = *buf.add(*pos); if c >= b'0' && c <= b'7' { val = val.wrapping_mul(8).wrapping_add((c - b'0') as u64); *pos += 1; } else { break; } }
7987            return (val, neg, true);
7988        } else {
7989            // base 16 with a leading zero ("00000000"): the zero is part of
7990            // the number, not a prefix that ends the conversion.
7991            while *pos < max {
7992                if let Some(d) = hex_val(*buf.add(*pos)) {
7993                    val = val.wrapping_mul(16).wrapping_add(d as u64);
7994                    *pos += 1;
7995                } else {
7996                    break;
7997                }
7998            }
7999            return (val, neg, true);
8000        }
8001    }
8002    if base == 0 { base = 10; }
8003    let mut found = false;
8004    while *pos < max {
8005        let c = *buf.add(*pos);
8006        let d: Option<u64> = match base {
8007            8 => if c >= b'0' && c <= b'7' { Some((c - b'0') as u64) } else { None },
8008            10 => if c >= b'0' && c <= b'9' { Some((c - b'0') as u64) } else { None },
8009            16 => hex_val(c).map(|v| v as u64),
8010            _ => None,
8011        };
8012        match d { Some(digit) => { val = val.wrapping_mul(base as u64).wrapping_add(digit); *pos += 1; found = true; } None => break }
8013    }
8014    if !found { *pos = start; return (0, false, false); }
8015    (val, neg, true)
8016}
8017
8018// Scan float with position tracking. Returns (value, success).
8019unsafe fn scan_float_val(
8020    buf: *const u8, pos: &mut usize, buf_len: usize, width: usize,
8021) -> (f64, bool) {
8022    let start = *pos;
8023    let max = if width > 0 { (start + width).min(buf_len) } else { buf_len };
8024    let neg = if *pos < max && *buf.add(*pos) == b'-' { *pos += 1; true }
8025    else if *pos < max && *buf.add(*pos) == b'+' { *pos += 1; false }
8026    else { false };
8027    // inf/nan
8028    if *pos + 2 < max {
8029        let (c0,c1,c2) = (*buf.add(*pos), *buf.add(*pos+1), *buf.add(*pos+2));
8030        if (c0==b'i'||c0==b'I')&&(c1==b'n'||c1==b'N')&&(c2==b'f'||c2==b'F') { *pos+=3; return (if neg{f64::NEG_INFINITY}else{f64::INFINITY}, true); }
8031        if (c0==b'n'||c0==b'N')&&(c1==b'a'||c1==b'A')&&(c2==b'n'||c2==b'N') { *pos+=3; return (if neg{-f64::NAN}else{f64::NAN}, true); }
8032    }
8033    // hex float
8034    if *pos+1 < max && *buf.add(*pos)==b'0' && (*buf.add(*pos+1)==b'x'||*buf.add(*pos+1)==b'X') {
8035        *pos += 2;
8036        let mut val: f64 = 0.0; let mut found = false; let mut frac_scale = 1.0f64; let mut in_frac = false;
8037        while *pos < max {
8038            if let Some(d) = hex_val(*buf.add(*pos)) {
8039                if in_frac { frac_scale /= 16.0; val += d as f64 * frac_scale; } else { val = val * 16.0 + d as f64; }
8040                *pos += 1; found = true;
8041            } else if *buf.add(*pos)==b'.' && !in_frac { in_frac = true; *pos += 1; } else { break; }
8042        }
8043        if !found { *pos = start; return (0.0, false); }
8044        // p exponent
8045        if *pos < max && (*buf.add(*pos)==b'p'||*buf.add(*pos)==b'P') {
8046            *pos += 1;
8047            let mut eneg = false;
8048            if *pos<max && *buf.add(*pos)==b'-' { eneg=true; *pos+=1; }
8049            else if *pos<max && *buf.add(*pos)==b'+' { *pos+=1; }
8050            let mut ev: i32 = 0; let mut ef = false;
8051            while *pos<max && *buf.add(*pos)>=b'0' && *buf.add(*pos)<=b'9' { ev = ev*10+(*buf.add(*pos)-b'0') as i32; *pos+=1; ef=true; }
8052            if !ef { return (0.0, false); }
8053            if eneg { ev = -ev; }
8054            val *= libm::pow(2.0, ev as f64);
8055        }
8056        return (if neg{-val}else{val}, true);
8057    }
8058    let token_start = start;
8059    let mut i = start;
8060    let mut saw_digit = false;
8061    let mut saw_dot = false;
8062    let mut saw_exp = false;
8063    let mut first = true;
8064    while i < max {
8065        let c = *buf.add(i);
8066        if (c == b'+' || c == b'-') && first {
8067            i += 1; first = false; continue;
8068        }
8069        if c >= b'0' && c <= b'9' {
8070            saw_digit = true; i += 1; first = false; continue;
8071        }
8072        if c == b'.' && !saw_dot && !saw_exp {
8073            saw_dot = true; i += 1; first = false; continue;
8074        }
8075        if (c == b'e' || c == b'E') && !saw_exp && saw_digit {
8076            saw_exp = true; i += 1; first = true; continue;
8077        }
8078        break;
8079    }
8080    if !saw_digit { return (0.0, false); }
8081    let s = core::str::from_utf8_unchecked(core::slice::from_raw_parts(buf.add(token_start), i - token_start));
8082    match <f64 as core::str::FromStr>::from_str(s) {
8083        Ok(v) => { *pos = i; return (v, true); }
8084        Err(_) => { return (0.0, false); }
8085    }
8086}
8087
8088// Comprehensive scanf parser with position tracking.
8089// consumed: if non-null, stores number of bytes consumed from buf.
8090/// Store a scanned integer with the width selected by the length modifier.
8091/// Without this, `%ld`/`%lu` silently truncate to 32 bits.
8092unsafe fn store_scan_int(dest: *mut c_void, len_mod: u8, val: u64, neg: bool) {
8093    let sv: i64 = if neg { (val as i64).wrapping_neg() } else { val as i64 };
8094    match len_mod {
8095        2 => *(dest as *mut i8) = sv as i8,
8096        1 => *(dest as *mut i16) = sv as i16,
8097        3 | 4 => *(dest as *mut i64) = sv,
8098        _ => *(dest as *mut i32) = sv as i32,
8099    }
8100}
8101
8102unsafe fn do_vsscanf(
8103    buf: *const u8, buf_len: usize, fmt: *const c_char, args: &mut VaList<'_>, consumed: *mut usize,
8104) -> c_int {
8105    let mut p = 0usize;
8106    let mut fi = 0usize;
8107    let mut assigned = 0i32;
8108    let mut input_eof = false;
8109    loop {
8110        let fc = *fmt.add(fi) as u8;
8111        if fc == 0 { break; }
8112        if is_ws_byte(fc) {
8113            while is_ws_byte(*fmt.add(fi) as u8) { fi += 1; }
8114            while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8115            continue;
8116        }
8117        if fc != b'%' {
8118            if p >= buf_len { input_eof = true; break; }
8119            if *buf.add(p) != fc { break; }
8120            p += 1; fi += 1; continue;
8121        }
8122        fi += 1;
8123        // %%
8124        if *fmt.add(fi) as u8 == b'%' {
8125            if p >= buf_len { input_eof = true; break; }
8126            if *buf.add(p) != b'%' { break; }
8127            p += 1; fi += 1; continue;
8128        }
8129        let suppress = if *fmt.add(fi) as u8 == b'*' { fi += 1; true } else { false };
8130        let mut width: usize = 0;
8131        while (*fmt.add(fi) as u8) >= b'0' && (*fmt.add(fi) as u8) <= b'9' {
8132            width = width * 10 + ((*fmt.add(fi) as u8) - b'0') as usize; fi += 1;
8133        }
8134        if *fmt.add(fi) as u8 == b'm' { fi += 1; }
8135        let mut len_mod = 0u8;
8136        match *fmt.add(fi) as u8 {
8137            b'h' => { fi += 1; if *fmt.add(fi) as u8 == b'h' { fi += 1; len_mod = 2; } else { len_mod = 1; } }
8138            b'l' => { fi += 1; if *fmt.add(fi) as u8 == b'l' { fi += 1; len_mod = 4; } else { len_mod = 3; } }
8139            b'j' => { fi += 1; len_mod = 4; }
8140            b'z' | b't' => { fi += 1; len_mod = 3; }
8141            b'L' => { fi += 1; len_mod = 5; }
8142            _ => {}
8143        }
8144        let spec = *fmt.add(fi) as u8;
8145        let (real_spec, _real_len) = if spec==b'C' {(b'c',3u8)} else if spec==b'S' {(b's',3u8)} else {(spec,len_mod)};
8146        match real_spec {
8147            b'n' => {
8148                if !suppress {
8149                    let out = args.next_arg::<*mut c_void>();
8150                    if !out.is_null() {
8151                        match len_mod {
8152                            1 => *(out as *mut i16) = p as i16,
8153                            2 => *(out as *mut i8) = p as i8,
8154                            3 | 4 => *(out as *mut i64) = p as i64,
8155                            _ => *(out as *mut c_int) = p as c_int,
8156                        }
8157                    }
8158                }
8159            }
8160            b'd' | b'u' => {
8161                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8162                if p >= buf_len { input_eof = true; break; }
8163                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8164                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 10, width);
8165                if !ok { break; }
8166                if let Some(out) = dest { if !out.is_null() {
8167                    store_scan_int(out, len_mod, val, neg);
8168                }}
8169                if !suppress { assigned += 1; }
8170            }
8171            b'i' => {
8172                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8173                if p >= buf_len { input_eof = true; break; }
8174                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8175                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 0, width);
8176                if !ok { break; }
8177                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8178                if !suppress { assigned += 1; }
8179            }
8180            b'o' => {
8181                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8182                if p >= buf_len { input_eof = true; break; }
8183                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8184                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 8, width);
8185                if !ok { break; }
8186                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8187                if !suppress { assigned += 1; }
8188            }
8189            b'x' | b'X' => {
8190                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8191                if p >= buf_len { input_eof = true; break; }
8192                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8193                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 16, width);
8194                if !ok { break; }
8195                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8196                if !suppress { assigned += 1; }
8197            }
8198            b'p' => {
8199                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8200                if p >= buf_len { input_eof = true; break; }
8201                let dest = if !suppress { Some(args.next_arg::<*mut *mut c_void>()) } else { None };
8202                let (val, _, ok) = scan_int_val(buf, &mut p, buf_len, 16, width);
8203                if !ok { break; }
8204                if let Some(out) = dest { if !out.is_null() { *out = val as usize as *mut c_void; } }
8205                if !suppress { assigned += 1; }
8206            }
8207            b'a' | b'e' | b'f' | b'g' | b'A' | b'E' | b'F' | b'G' => {
8208                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8209                if p >= buf_len { input_eof = true; break; }
8210                let (val, ok) = scan_float_val(buf, &mut p, buf_len, width);
8211                if !ok { break; }
8212                if !suppress {
8213                    if _real_len == 3 {
8214                        let out = args.next_arg::<*mut f64>(); if !out.is_null() { *out = val; }
8215                    } else if _real_len == 5 {
8216                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
8217                        { let out = args.next_arg::<*mut f128>(); if !out.is_null() { *out = val as f128; } }
8218                        #[cfg(target_arch = "x86_64")]
8219                        { let out = args.next_arg::<*mut f64>(); if !out.is_null() { *out = val; } }
8220                    } else {
8221                        let out = args.next_arg::<*mut f32>(); if !out.is_null() { *out = val as f32; }
8222                    }
8223                }
8224                if !suppress { assigned += 1; }
8225            }
8226            b'c' => {
8227                let w = if width > 0 { width } else { 1 };
8228                if p >= buf_len { input_eof = true; break; }
8229                let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8230                let start_p = p;
8231                let mut j = 0usize;
8232                while j < w && p < buf_len {
8233                    if !dest_ptr.is_null() { *dest_ptr.add(j) = *buf.add(p) as c_char; }
8234                    p += 1; j += 1;
8235                }
8236                if j != w { p = start_p; input_eof = true; break; }
8237                if !suppress { assigned += 1; }
8238            }
8239            b's' => {
8240                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8241                if p >= buf_len { input_eof = true; break; }
8242                let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8243                let w = if width > 0 { width } else { usize::MAX };
8244                let mut j = 0usize;
8245                while p < buf_len && *buf.add(p) != 0 && !is_ws_byte(*buf.add(p)) && j < w {
8246                    if !dest_ptr.is_null() { *dest_ptr.add(j) = *buf.add(p) as c_char; }
8247                    p += 1; j += 1;
8248                }
8249                if j == 0 { break; }
8250                if !dest_ptr.is_null() { *dest_ptr.add(j) = 0; }
8251                if !suppress { assigned += 1; }
8252            }
8253            b'[' => {
8254                fi += 1;
8255                let negate = if *fmt.add(fi) as u8 == b'^' { fi += 1; true } else { false };
8256                let mut charset = [0u8; 256];
8257                let mut prev: Option<u8> = None;
8258                if *fmt.add(fi) as u8 == b']' {
8259                    charset[b']' as usize] = 1;
8260                    prev = Some(b']');
8261                    fi += 1;
8262                }
8263                loop {
8264                    let c = *fmt.add(fi) as u8;
8265                    if c == b']' || c == 0 { break; }
8266                    // "a-z" is a range; a '-' next to ']' or at the start/end
8267                    // of the set is a literal.
8268                    if c == b'-' && prev.is_some() {
8269                        let hi = *fmt.add(fi + 1) as u8;
8270                        if hi != b']' && hi != 0 {
8271                            let lo = prev.unwrap();
8272                            let mut k = lo;
8273                            while k <= hi {
8274                                charset[k as usize] = 1;
8275                                if k == 255 { break; }
8276                                k += 1;
8277                            }
8278                            prev = None;
8279                            fi += 2;
8280                            continue;
8281                        }
8282                    }
8283                    charset[c as usize] = 1;
8284                    prev = Some(c);
8285                    fi += 1;
8286                }
8287                if *fmt.add(fi) as u8 == b']' { fi += 1; }
8288                fi -= 1; // common fi += 1 will advance past the closing ]
8289                if p >= buf_len { input_eof = true; break; }
8290                let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8291                let w = if width > 0 { width } else { usize::MAX };
8292                let mut j = 0usize;
8293                while p < buf_len && *buf.add(p) != 0 && j < w {
8294                    let c = *buf.add(p);
8295                    let in_set = charset[c as usize] != 0;
8296                    if negate { if in_set { break; } } else { if !in_set { break; } }
8297                    if !dest_ptr.is_null() { *dest_ptr.add(j) = c as c_char; }
8298                    p += 1; j += 1;
8299                }
8300                if j == 0 { break; }
8301                if !dest_ptr.is_null() { *dest_ptr.add(j) = 0; }
8302                if !suppress { assigned += 1; }
8303            }
8304            _ => break,
8305        }
8306        fi += 1;
8307    }
8308    if !consumed.is_null() { *consumed = p; }
8309    if assigned == 0 && input_eof { -1 } else { assigned }
8310}
8311
8312unsafe fn vsscanf_inner(buf: *const u8, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
8313    let len = strlen(buf as *const c_char);
8314    do_vsscanf(buf, len, fmt, args, core::ptr::null_mut())
8315}
8316
8317#[no_mangle]
8318pub unsafe extern "C" fn vsscanf(buf: *const c_char, fmt: *const c_char, mut args: VaList) -> c_int {
8319    vsscanf_inner(buf as *const u8, fmt, &mut args)
8320}
8321
8322#[no_mangle]
8323pub unsafe extern "C" fn vfscanf(stream: *mut FILE, fmt: *const c_char, mut args: VaList) -> c_int {
8324    let f = &mut *stream;
8325    let start_ungotten_count = f.ungotten_count as usize;
8326    let ungotten_saved = f.ungotten;
8327    let sfunc = f.seek_fn;
8328    // Logical position, not the raw fd offset: fgetc may have read ahead.
8329    let start_pos = if sfunc.is_some() { ftello(stream) } else { -1 };
8330
8331    let mut line = [0u8; 4096];
8332    let mut pos = 0usize;
8333
8334    if start_pos >= 0 {
8335        // Seekable: read via fgetc until \n or EOF (existing behavior)
8336        while pos < line.len() - 1 {
8337            let c = fgetc(stream);
8338            if c == -1 { break; }
8339            line[pos] = c as u8;
8340            pos += 1;
8341            if c == b'\n' as c_int { break; }
8342        }
8343    } else {
8344        // Non-seekable (pipe/socket): drain pushback, then read all available
8345        // data non-blocking so we don't stop at \n boundaries.
8346
8347        // 1. Drain ungotten bytes (LIFO order)
8348        while f.ungotten_count > 0 && pos < line.len() - 1 {
8349            f.ungotten_count -= 1;
8350            line[pos] = f.ungotten[f.ungotten_count as usize] as u8;
8351            pos += 1;
8352        }
8353        // 2. Drain rpos/rend pushback buffer
8354        while !f.rpos.is_null() && f.rpos < f.rend && pos < line.len() - 1 {
8355            line[pos] = *f.rpos;
8356            f.rpos = f.rpos.add(1);
8357            pos += 1;
8358        }
8359        // 3. Wait for the first byte (blocking), then drain whatever else is
8360        // available without waiting. A pure non-blocking read would race with
8361        // a producer such as popen() that has not written yet.
8362        let fd = f.fd;
8363        if pos == 0 {
8364            let n = sys_read(fd as i64, line.as_mut_ptr(), 1);
8365            if n == 1 { pos = 1; }
8366        }
8367        let old_flags = sys_fcntl(fd, F_GETFL, 0);
8368        if old_flags >= 0 {
8369            let _ = sys_fcntl(fd, F_SETFL, old_flags | O_NONBLOCK as i64);
8370        }
8371        while pos < line.len() - 1 {
8372            let n = sys_read(fd as i64, line.as_mut_ptr().add(pos), line.len() - 1 - pos);
8373            if n <= 0 { break; }
8374            pos += n as usize;
8375        }
8376        if old_flags >= 0 {
8377            let _ = sys_fcntl(fd, F_SETFL, old_flags);
8378        }
8379        // Clear flags that the failed non-blocking read may have set
8380        f._eof = 0;
8381        f._err = 0;
8382        f.flags &= !(F_EOF | F_ERR);
8383    }
8384
8385    line[pos] = 0;
8386    if pos == 0 { return 0; }
8387
8388    let mut consumed = 0usize;
8389    let assigned = do_vsscanf(line.as_ptr(), pos, fmt, &mut args, &mut consumed);
8390
8391    if start_pos >= 0 {
8392        // Seek back to the logical position just past the consumed bytes and
8393        // restore any ungetc pushback the scan did not consume.
8394        let remaining = start_ungotten_count.saturating_sub(consumed);
8395        // The restored ungetc bytes will be subtracted by ftello(), so the
8396        // raw fd offset must include them.
8397        let target = start_pos + consumed as i64 + remaining as i64;
8398        if let Some(sfunc) = sfunc {
8399            sfunc(stream, target, SEEK_SET);
8400        }
8401        f.rpos = core::ptr::null_mut();
8402        f.rend = core::ptr::null_mut();
8403        if consumed < pos { f._eof = 0; }
8404        f.ungotten_count = 0;
8405        for i in 0..remaining {
8406            f.ungotten[f.ungotten_count as usize] = ungotten_saved[i];
8407            f.ungotten_count += 1;
8408        }
8409    } else {
8410        // Non-seekable: push back unconsumed bytes into FILE read buffer
8411        let unconsumed = pos.saturating_sub(consumed);
8412        if unconsumed > 0 && !f.buf.is_null() {
8413            let copy_count = core::cmp::min(unconsumed, f.buf_size);
8414            core::ptr::copy(
8415                line.as_ptr().add(consumed),
8416                f.buf,
8417                copy_count,
8418            );
8419            f.rpos = f.buf;
8420            f.rend = f.buf.add(copy_count);
8421        }
8422        f.ungotten_count = 0;
8423        f._eof = 0;
8424        f.flags &= !F_EOF;
8425    }
8426    assigned
8427}
8428
8429#[no_mangle]
8430pub unsafe extern "C" fn vscanf(fmt: *const c_char, args: VaList) -> c_int {
8431    vfscanf(stdin, fmt, args)
8432}
8433
8434#[no_mangle]
8435pub unsafe extern "C" fn sscanf(buf: *const c_char, fmt: *const c_char, mut args: ...) -> c_int {
8436    vsscanf_inner(buf as *const u8, fmt, &mut args)
8437}
8438
8439#[no_mangle]
8440pub unsafe extern "C" fn fscanf(stream: *mut FILE, fmt: *const c_char, args: ...) -> c_int {
8441    vfscanf(stream, fmt, args)
8442}
8443
8444#[no_mangle]
8445pub unsafe extern "C" fn scanf(fmt: *const c_char, args: ...) -> c_int {
8446    vfscanf(stdin, fmt, args)
8447}
8448
8449// ============================================================
8450// getdelim / getline
8451// ============================================================
8452
8453#[no_mangle]
8454pub unsafe extern "C" fn getdelim(
8455    lineptr: *mut *mut c_char, n: *mut usize, delim: c_int, stream: *mut FILE,
8456) -> isize {
8457    if lineptr.is_null() || n.is_null() { return -1; }
8458    let mut cap = *n;
8459    let mut buf = *lineptr;
8460    if buf.is_null() || cap == 0 {
8461        cap = 128;
8462        buf = realloc(buf as *mut c_void, cap) as *mut c_char;
8463        if buf.is_null() { return -1; }
8464        *lineptr = buf;
8465        *n = cap;
8466    }
8467    let mut len = 0usize;
8468    loop {
8469        let c = fgetc(stream);
8470        if c == -1 { if len == 0 { return -1; } break; }
8471        if len + 1 >= cap {
8472            let new_cap = cap.wrapping_mul(2);
8473            let new_buf = realloc(buf as *mut c_void, new_cap) as *mut c_char;
8474            if new_buf.is_null() { return -1; }
8475            buf = new_buf; cap = new_cap;
8476            *lineptr = buf; *n = cap;
8477        }
8478        *buf.add(len) = c as c_char;
8479        len += 1;
8480        if c == delim { break; }
8481    }
8482    *buf.add(len) = 0;
8483    len as isize
8484}
8485
8486#[no_mangle]
8487pub unsafe extern "C" fn getline(lineptr: *mut *mut c_char, n: *mut usize, stream: *mut FILE) -> isize {
8488    getdelim(lineptr, n, b'\n' as c_int, stream)
8489}
8490
8491// ============================================================
8492// popen / pclose
8493// ============================================================
8494
8495#[no_mangle]
8496pub unsafe extern "C" fn popen(cmd: *const c_char, mode: *const c_char) -> *mut FILE {
8497    if cmd.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
8498    let m = *mode;
8499    if m != b'r' as c_char && m != b'w' as c_char { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
8500    let mut p: [c_int; 2] = [0; 2];
8501    if sys_pipe2(p.as_mut_ptr(), O_CLOEXEC) < 0 { return core::ptr::null_mut(); }
8502    let op = if m == b'r' as c_char { 0 } else { 1 };
8503    let child_fd = p[1 - op];
8504    let f = fdopen(p[op], mode);
8505    if f.is_null() { sys_close(p[0] as i64); sys_close(p[1] as i64); return core::ptr::null_mut(); }
8506    let pid = sys_fork();
8507    if pid < 0 { fclose(f); sys_close(child_fd as i64); return core::ptr::null_mut(); }
8508    if pid == 0 {
8509        sys_close(p[op] as i64);
8510        if child_fd != (1 - op) as c_int { sys_dup3(child_fd, (1 - op) as c_int, 0); sys_close(child_fd as i64); }
8511        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
8512        let argv = [b"sh\0".as_ptr() as *const c_char, b"-c\0".as_ptr() as *const c_char, cmd, core::ptr::null()];
8513        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
8514        _exit(127);
8515    }
8516    sys_close(child_fd as i64);
8517    (*f).pipe_pid = pid as c_int;
8518    f
8519}
8520
8521#[no_mangle]
8522pub unsafe extern "C" fn pclose(f: *mut FILE) -> c_int {
8523    let pid = (*f).pipe_pid;
8524    let r = fclose(f);
8525    if pid <= 0 { return -1; }
8526    let mut status: c_int = 0;
8527    let mut w: c_int;
8528    loop {
8529        w = waitpid(pid, &mut status, 0);
8530        if w >= 0 || ERRNO!() != EINTR_VAL { break; }
8531    }
8532    if w < 0 || r != 0 { return -1; }
8533    status
8534}
8535
8536// ============================================================
8537// tmpfile / tmpnam / remove / rename
8538// ============================================================
8539
8540const L_TMPNAM: usize = 20;
8541static mut TMPNAM_COUNTER: c_uint = 0;
8542
8543unsafe fn fill_tmpname(out: *mut c_char, seed: c_uint) {
8544    let prefix = b"/tmp/tmp\0";
8545    let mut k = 0;
8546    while k < prefix.len() - 1 { *out.add(k) = prefix[k] as c_char; k += 1; }
8547    let (buf, len) = format_hex(seed as u64, false);
8548    for j in 0..len.min(L_TMPNAM - k - 1) { *out.add(k + j) = buf[j] as c_char; k += 1; }
8549    *out.add(k) = 0;
8550}
8551
8552#[no_mangle]
8553pub unsafe extern "C" fn tmpfile() -> *mut FILE {
8554    let mut name = [0u8; L_TMPNAM];
8555    let mut ctr: c_uint = 0;
8556    loop {
8557        ctr = ctr.wrapping_add(1);
8558        let mut ts: timespec = core::mem::zeroed();
8559        let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
8560        let seed = (ts.tv_nsec as c_uint).wrapping_add(ctr);
8561        fill_tmpname(name.as_mut_ptr() as *mut c_char, seed);
8562        let fd = sys_open(name.as_ptr(), (O_RDWR | O_CREAT | O_EXCL) as i64, 0o600);
8563        if fd >= 0 {
8564            sys_unlinkat(AT_FDCWD, name.as_ptr(), 0);
8565            let f = fdopen(fd as c_int, b"w+\0".as_ptr() as *const c_char);
8566            if f.is_null() { sys_close(fd); }
8567            return f;
8568        }
8569        if ctr > 100 { return core::ptr::null_mut(); }
8570    }
8571}
8572
8573#[no_mangle]
8574pub unsafe extern "C" fn tmpnam(s: *mut c_char) -> *mut c_char {
8575    static mut BUF: [c_char; L_TMPNAM] = [0; L_TMPNAM];
8576    let out = if s.is_null() { core::ptr::addr_of_mut!(BUF) as *mut c_char } else { s };
8577    TMPNAM_COUNTER = TMPNAM_COUNTER.wrapping_add(1);
8578    let mut ts: timespec = core::mem::zeroed();
8579    let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
8580    let seed = (ts.tv_nsec as c_uint).wrapping_add(TMPNAM_COUNTER);
8581    fill_tmpname(out, seed);
8582    out
8583}
8584
8585#[no_mangle]
8586pub unsafe extern "C" fn remove(path: *const c_char) -> c_int {
8587    if path.is_null() { ERRNO!() = EINVAL; return -1; }
8588    let r = sys_unlinkat(AT_FDCWD, path as *const u8, 0);
8589    if r == 0 {
8590        return 0;
8591    }
8592    // POSIX remove() also removes directories; musl falls back to rmdir only
8593    // when unlink reports EISDIR.
8594    if (-r) as c_int == 21 {
8595        return rmdir(path);
8596    }
8597    ERRNO!() = (-r) as c_int;
8598    -1
8599}
8600
8601#[no_mangle]
8602pub unsafe extern "C" fn rename(old: *const c_char, new_: *const c_char) -> c_int {
8603    if old.is_null() || new_.is_null() { ERRNO!() = EINVAL; return -1; }
8604    let r = sys_renameat2(AT_FDCWD, old as *const u8, AT_FDCWD, new_ as *const u8, 0);
8605    if r == 0 { 0 } else { ERRNO!() = (-r) as c_int; -1 }
8606}
8607
8608// ============================================================
8609// Allocator basics
8610// ============================================================
8611
8612const MMAP_FAILED: *mut u8 = !0usize as *mut u8;
8613const PAGE: usize = 4096;
8614
8615// ============================================================
8616// Process: exit / _exit / _Exit
8617// ============================================================
8618
8619#[no_mangle]
8620pub unsafe extern "C" fn _exit(code: c_int) -> ! {
8621    sys_exit_group(code)
8622}
8623
8624#[inline]
8625unsafe fn sys_exit_group(code: c_int) -> ! {
8626    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT_GROUP, code as i64)
8627}
8628
8629#[inline]
8630unsafe fn sys_exit_thread(code: c_int) -> ! {
8631    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT, code as i64)
8632}
8633
8634#[no_mangle]
8635pub unsafe extern "C" fn _Exit(code: c_int) -> ! {
8636    _exit(code);
8637}
8638
8639#[no_mangle]
8640pub unsafe extern "C" fn exit(code: c_int) -> ! {
8641    fflush(core::ptr::null_mut());
8642    __funcs_on_exit();
8643    _exit(code);
8644}
8645
8646#[no_mangle]
8647pub unsafe extern "C" fn abort() -> ! {
8648    raise(6); // SIGABRT
8649    _exit(128 + 6);
8650}
8651
8652// aarch64 GCC accesses the stack canary via the global __stack_chk_guard
8653// symbol (GOT-based for PIE). Export it so the dynamic linker can resolve it.
8654#[no_mangle]
8655pub static mut __stack_chk_guard: usize = 0;
8656
8657#[no_mangle]
8658pub unsafe extern "C" fn __stack_chk_fail() -> ! {
8659    const MSG: &[u8] = b"*** stack smashing detected ***: terminated\n";
8660    let _ = sys_write(2, MSG.as_ptr(), MSG.len());
8661    abort();
8662}
8663
8664#[no_mangle]
8665pub unsafe extern "C" fn __stack_chk_fail_local() -> ! {
8666    __stack_chk_fail()
8667}
8668
8669// ============================================================
8670// qsort / qsort_r (smoothsort, O(1) aux, adaptive)
8671// ============================================================
8672
8673type CmpRfn = unsafe extern "C" fn(*const c_void, *const c_void, *mut c_void) -> c_int;
8674
8675const AR_LEN: usize = 16 * core::mem::size_of::<usize>();
8676const AR_MASK: usize = AR_LEN - 1;
8677
8678unsafe fn qsort_pntz(p: &[usize; 2]) -> i32 {
8679    if p[0] != 1 {
8680        p[0].wrapping_sub(1).trailing_zeros() as i32
8681    } else if p[1] != 0 {
8682        (8 * core::mem::size_of::<usize>()) as i32 + p[1].trailing_zeros() as i32
8683    } else {
8684        0
8685    }
8686}
8687
8688unsafe fn qsort_cycle(width: usize, ar: &mut [*mut u8; AR_LEN], n: usize) {
8689    if n < 2 { return; }
8690    let mut tmp = [0u8; 256];
8691    ar[n] = tmp.as_mut_ptr();
8692    let mut w = width;
8693    while w > 0 {
8694        let l = if 256 < w { 256 } else { w };
8695        core::ptr::copy_nonoverlapping(ar[0], ar[n], l);
8696        for i in 0..n {
8697            core::ptr::copy_nonoverlapping(ar[i + 1], ar[i], l);
8698            ar[i] = ar[i].add(l);
8699        }
8700        w -= l;
8701    }
8702}
8703
8704unsafe fn qsort_shl(p: &mut [usize; 2], n: i32) {
8705    let bits = (8 * core::mem::size_of::<usize>()) as i32;
8706    if n >= bits {
8707        p[1] = p[0];
8708        p[0] = 0;
8709        let n = n - bits;
8710        if n == 0 { return; }
8711    }
8712    p[1] = (p[1] << n) | (p[0] >> (bits - n));
8713    p[0] <<= n;
8714}
8715
8716unsafe fn qsort_shr(p: &mut [usize; 2], n: i32) {
8717    let bits = (8 * core::mem::size_of::<usize>()) as i32;
8718    if n >= bits {
8719        p[0] = p[1];
8720        p[1] = 0;
8721        let n = n - bits;
8722        if n == 0 { return; }
8723    }
8724    p[0] = (p[0] >> n) | (p[1] << (bits - n));
8725    p[1] >>= n;
8726}
8727
8728unsafe fn qsort_sift(
8729    head: *mut u8, width: usize,
8730    cmp: CmpRfn, arg: *mut c_void,
8731    pshift: i32, lp: &[usize],
8732) {
8733    let mut ar: [*mut u8; AR_LEN] = [core::ptr::null_mut(); AR_LEN];
8734    ar[0] = head;
8735    let mut i = 1usize;
8736    let mut h = head;
8737    let mut ps = pshift;
8738
8739    while ps > 1 {
8740        let rt = h.sub(width);
8741        let lf = h.sub(width + lp[(ps - 2) as usize]);
8742
8743        if cmp(ar[0] as *const c_void, lf as *const c_void, arg) >= 0
8744            && cmp(ar[0] as *const c_void, rt as *const c_void, arg) >= 0
8745        {
8746            break;
8747        }
8748        if cmp(lf as *const c_void, rt as *const c_void, arg) >= 0 {
8749            ar[i & AR_MASK] = lf;
8750            i += 1;
8751            h = lf;
8752            ps -= 1;
8753        } else {
8754            ar[i & AR_MASK] = rt;
8755            i += 1;
8756            h = rt;
8757            ps -= 2;
8758        }
8759    }
8760    qsort_cycle(width, &mut ar, i & AR_MASK);
8761}
8762
8763unsafe fn qsort_trinkle(
8764    head: *mut u8, width: usize,
8765    cmp: CmpRfn, arg: *mut c_void,
8766    pp: &[usize; 2], pshift: i32, trusty: i32,
8767    lp: &[usize],
8768) {
8769    let mut ar: [*mut u8; AR_LEN] = [core::ptr::null_mut(); AR_LEN];
8770    let mut p = *pp;
8771    ar[0] = head;
8772    let mut i = 1usize;
8773    let mut h = head;
8774    let mut ps = pshift;
8775    let mut t = trusty;
8776
8777    while p[0] != 1 || p[1] != 0 {
8778        let stepson = h.sub(lp[ps as usize]);
8779        if cmp(stepson as *const c_void, ar[0] as *const c_void, arg) <= 0 {
8780            break;
8781        }
8782        if t == 0 && ps > 1 {
8783            let rt = h.sub(width);
8784            let lf = h.sub(width + lp[(ps - 2) as usize]);
8785            if cmp(rt as *const c_void, stepson as *const c_void, arg) >= 0
8786                || cmp(lf as *const c_void, stepson as *const c_void, arg) >= 0
8787            {
8788                break;
8789            }
8790        }
8791
8792        ar[i & AR_MASK] = stepson;
8793        i += 1;
8794        h = stepson;
8795        let trail = qsort_pntz(&p);
8796        qsort_shr(&mut p, trail);
8797        ps += trail;
8798        t = 0;
8799    }
8800    if t == 0 {
8801        qsort_cycle(width, &mut ar, i & AR_MASK);
8802        qsort_sift(h, width, cmp, arg, ps, lp);
8803    }
8804}
8805
8806#[no_mangle]
8807pub unsafe extern "C" fn __qsort_r(
8808    base: *mut c_void,
8809    nel: usize,
8810    width: usize,
8811    cmp: CmpRfn,
8812    arg: *mut c_void,
8813) {
8814    let size = width * nel;
8815    if size == 0 { return; }
8816
8817    let mut lp = [0usize; 96];
8818    lp[0] = width;
8819    lp[1] = width;
8820    let mut li = 2;
8821    while {
8822        lp[li] = lp[li - 2] + lp[li - 1] + width;
8823        lp[li] < size
8824    } {
8825        li += 1;
8826    }
8827
8828    let mut head = base as *mut u8;
8829    let high = head.add(size - width);
8830    let mut p: [usize; 2] = [1, 0];
8831    let mut pshift: i32 = 1;
8832
8833    while head < high {
8834        if (p[0] & 3) == 3 {
8835            qsort_sift(head, width, cmp, arg, pshift, &lp);
8836            qsort_shr(&mut p, 2);
8837            pshift += 2;
8838        } else {
8839            if lp[(pshift - 1) as usize] >= (high as usize) - (head as usize) {
8840                qsort_trinkle(head, width, cmp, arg, &p, pshift, 0, &lp);
8841            } else {
8842                qsort_sift(head, width, cmp, arg, pshift, &lp);
8843            }
8844
8845            if pshift == 1 {
8846                qsort_shl(&mut p, 1);
8847                pshift = 0;
8848            } else {
8849                qsort_shl(&mut p, pshift - 1);
8850                pshift = 1;
8851            }
8852        }
8853
8854        p[0] |= 1;
8855        head = head.add(width);
8856    }
8857
8858    qsort_trinkle(head, width, cmp, arg, &p, pshift, 0, &lp);
8859
8860    while pshift != 1 || p[0] != 1 || p[1] != 0 {
8861        if pshift <= 1 {
8862            let trail = qsort_pntz(&p);
8863            qsort_shr(&mut p, trail);
8864            pshift += trail;
8865        } else {
8866            qsort_shl(&mut p, 2);
8867            pshift -= 2;
8868            p[0] ^= 7;
8869            qsort_shr(&mut p, 1);
8870            qsort_trinkle(
8871                head.sub(lp[pshift as usize] + width),
8872                width, cmp, arg, &p, pshift + 1, 1, &lp,
8873            );
8874            qsort_shl(&mut p, 1);
8875            p[0] |= 1;
8876            qsort_trinkle(head.sub(width), width, cmp, arg, &p, pshift, 1, &lp);
8877        }
8878        head = head.sub(width);
8879    }
8880}
8881
8882#[no_mangle]
8883pub unsafe extern "C" fn qsort_r(
8884    base: *mut c_void,
8885    nel: usize,
8886    width: usize,
8887    cmp: CmpRfn,
8888    arg: *mut c_void,
8889) {
8890    __qsort_r(base, nel, width, cmp, arg);
8891}
8892
8893unsafe extern "C" fn qsort_wrap_cmp(
8894    a: *const c_void,
8895    b: *const c_void,
8896    cmp_ctx: *mut c_void,
8897) -> c_int {
8898    let cmp: CmpFn = core::mem::transmute(cmp_ctx);
8899    cmp(a, b)
8900}
8901
8902#[no_mangle]
8903pub unsafe extern "C" fn qsort(
8904    base: *mut c_void,
8905    nel: usize,
8906    width: usize,
8907    cmp: CmpFn,
8908) {
8909    __qsort_r(base, nel, width, qsort_wrap_cmp, cmp as *mut c_void);
8910}
8911
8912// ============================================================
8913// atexit / __cxa_atexit / __funcs_on_exit
8914// ============================================================
8915
8916const ATEXIT_COUNT: usize = 32;
8917
8918#[repr(C)]
8919struct AtExitBlock {
8920    next: *mut AtExitBlock,
8921    f: [Option<unsafe extern "C" fn(*mut c_void)>; ATEXIT_COUNT],
8922    a: [*mut c_void; ATEXIT_COUNT],
8923}
8924
8925static mut ATEXIT_BUILTIN: AtExitBlock = AtExitBlock {
8926    next: core::ptr::null_mut(),
8927    f: [None; ATEXIT_COUNT],
8928    a: [core::ptr::null_mut(); ATEXIT_COUNT],
8929};
8930static mut ATEXIT_HEAD: *mut AtExitBlock = core::ptr::null_mut();
8931static mut ATEXIT_SLOT: usize = 0;
8932static mut ATEXIT_FINISHED: bool = false;
8933
8934#[no_mangle]
8935pub unsafe extern "C" fn __funcs_on_exit() {
8936    while !ATEXIT_HEAD.is_null() {
8937        let head = ATEXIT_HEAD;
8938        while ATEXIT_SLOT > 0 {
8939            ATEXIT_SLOT -= 1;
8940            if let Some(f) = (*head).f[ATEXIT_SLOT] {
8941                let a = (*head).a[ATEXIT_SLOT];
8942                f(a);
8943            }
8944        }
8945        ATEXIT_HEAD = (*head).next;
8946        ATEXIT_SLOT = ATEXIT_COUNT;
8947    }
8948    ATEXIT_FINISHED = true;
8949}
8950
8951#[no_mangle]
8952pub unsafe extern "C" fn __cxa_atexit(
8953    func: unsafe extern "C" fn(*mut c_void),
8954    arg: *mut c_void,
8955    _dso: *mut c_void,
8956) -> c_int {
8957    if ATEXIT_FINISHED {
8958        return -1;
8959    }
8960    if ATEXIT_HEAD.is_null() {
8961        ATEXIT_HEAD = core::ptr::addr_of_mut!(ATEXIT_BUILTIN);
8962    }
8963    if ATEXIT_SLOT == ATEXIT_COUNT {
8964        let new = calloc(1, core::mem::size_of::<AtExitBlock>()) as *mut AtExitBlock;
8965        if new.is_null() {
8966            return -1;
8967        }
8968        (*new).next = ATEXIT_HEAD;
8969        ATEXIT_HEAD = new;
8970        ATEXIT_SLOT = 0;
8971    }
8972    (*ATEXIT_HEAD).f[ATEXIT_SLOT] = Some(func);
8973    (*ATEXIT_HEAD).a[ATEXIT_SLOT] = arg;
8974    ATEXIT_SLOT += 1;
8975    0
8976}
8977
8978unsafe extern "C" fn atexit_caller(arg: *mut c_void) {
8979    let func: unsafe extern "C" fn() = core::mem::transmute(arg);
8980    func();
8981}
8982
8983#[no_mangle]
8984pub unsafe extern "C" fn atexit(func: unsafe extern "C" fn()) -> c_int {
8985    __cxa_atexit(atexit_caller, func as *mut c_void, core::ptr::null_mut())
8986}
8987
8988#[no_mangle]
8989pub unsafe extern "C" fn __cxa_finalize(_dso: *mut c_void) {}
8990
8991// ============================================================
8992// getenv / setenv / putenv / unsetenv / clearenv
8993// ============================================================
8994
8995#[no_mangle]
8996pub static mut __environ: *mut *mut c_char = core::ptr::null_mut();
8997
8998// Growable tracking of strings allocated by setenv/putenv.  Realloc keeps
8999// this unbounded; if it fails the new string is simply left untracked.
9000static mut ENV_ALLOCED: *mut *mut c_char = core::ptr::null_mut();
9001static mut ENV_ALLOCED_N: usize = 0;
9002static mut ENV_ALLOCED_CAP: usize = 0;
9003
9004unsafe fn env_rm_add(old: *mut c_char, mut new: *mut c_char) {
9005    for i in 0..ENV_ALLOCED_N {
9006        if (*ENV_ALLOCED.add(i)) == old {
9007            *ENV_ALLOCED.add(i) = new;
9008            if !old.is_null() {
9009                free(old as *mut c_void);
9010            }
9011            return;
9012        } else if (*ENV_ALLOCED.add(i)).is_null() && !new.is_null() {
9013            *ENV_ALLOCED.add(i) = new;
9014            new = core::ptr::null_mut();
9015        }
9016    }
9017    if !new.is_null() {
9018        if ENV_ALLOCED_N == ENV_ALLOCED_CAP {
9019            let new_cap = if ENV_ALLOCED_CAP == 0 { 16 } else { ENV_ALLOCED_CAP * 2 };
9020            let grown = realloc(
9021                ENV_ALLOCED as *mut c_void,
9022                new_cap * core::mem::size_of::<*mut c_char>(),
9023            ) as *mut *mut c_char;
9024            if grown.is_null() {
9025                return;
9026            }
9027            ENV_ALLOCED = grown;
9028            ENV_ALLOCED_CAP = new_cap;
9029        }
9030        *ENV_ALLOCED.add(ENV_ALLOCED_N) = new;
9031        ENV_ALLOCED_N += 1;
9032    }
9033}
9034
9035unsafe fn strchrnul_u8(s: *const u8, c: u8) -> *const u8 {
9036    let mut p = s;
9037    while *p != 0 && *p != c {
9038        p = p.add(1);
9039    }
9040    p
9041}
9042
9043#[no_mangle]
9044pub unsafe extern "C" fn getenv(name: *const c_char) -> *mut c_char {
9045    if __environ.is_null() || name.is_null() {
9046        return core::ptr::null_mut();
9047    }
9048    let name = name as *const u8;
9049    let l = strchrnul_u8(name, b'=') as usize - name as usize;
9050    if l == 0 || *name.add(l) != 0 {
9051        return core::ptr::null_mut();
9052    }
9053    let mut e = __environ;
9054    while !(*e).is_null() {
9055        let entry = *e as *const u8;
9056        if strncmp(entry, name, l) == 0 && *entry.add(l) == b'=' {
9057            return entry.add(l + 1) as *mut c_char;
9058        }
9059        e = e.add(1);
9060    }
9061    core::ptr::null_mut()
9062}
9063
9064#[no_mangle]
9065pub unsafe extern "C" fn setenv(
9066    var: *const c_char,
9067    value: *const c_char,
9068    overwrite: c_int,
9069) -> c_int {
9070    if var.is_null() || value.is_null() {
9071        ERRNO!() = EINVAL;
9072        return -1;
9073    }
9074    let var = var as *const u8;
9075    let l1 = strchrnul_u8(var, b'=') as usize - var as usize;
9076    if l1 == 0 || *var.add(l1) != 0 {
9077        ERRNO!() = EINVAL;
9078        return -1;
9079    }
9080    if overwrite == 0 && !getenv(var as *const c_char).is_null() {
9081        return 0;
9082    }
9083    let l2 = strlen(value as *const c_char);
9084    let s = malloc(l1 + l2 + 2) as *mut u8;
9085    if s.is_null() {
9086        return -1;
9087    }
9088    core::ptr::copy_nonoverlapping(var, s, l1);
9089    *s.add(l1) = b'=';
9090    core::ptr::copy_nonoverlapping(value as *const u8, s.add(l1 + 1), l2 + 1);
9091    putenv_internal(s as *mut c_char, l1, s as *mut c_char)
9092}
9093
9094unsafe fn putenv_internal(s: *mut c_char, l: usize, r: *mut c_char) -> c_int {
9095    let mut i = 0;
9096    if !__environ.is_null() {
9097        let mut e = __environ;
9098        while !(*e).is_null() {
9099            if strncmp(s as *const u8, *e as *const u8, l + 1) == 0 {
9100                let tmp = *e;
9101                *e = s;
9102                env_rm_add(tmp, r);
9103                return 0;
9104            }
9105            e = e.add(1);
9106            i += 1;
9107        }
9108    }
9109    let newenv = malloc(core::mem::size_of::<*mut c_char>() * (i + 2)) as *mut *mut c_char;
9110    if newenv.is_null() {
9111        if !r.is_null() { free(r as *mut c_void); }
9112        return -1;
9113    }
9114    if i > 0 && !__environ.is_null() {
9115        core::ptr::copy_nonoverlapping(__environ, newenv, i);
9116    }
9117    *newenv.add(i) = s;
9118    *newenv.add(i + 1) = core::ptr::null_mut();
9119    // ponytail: don't free old __environ (may not be from our malloc)
9120    __environ = newenv;
9121    environ = __environ;
9122    if !r.is_null() {
9123        env_rm_add(core::ptr::null_mut(), r);
9124    }
9125    0
9126}
9127
9128#[no_mangle]
9129pub unsafe extern "C" fn putenv(s: *mut c_char) -> c_int {
9130    if s.is_null() { return -1; }
9131    let l = strchrnul_u8(s as *const u8, b'=') as usize - s as *const u8 as usize;
9132    if l == 0 || *s.add(l) as u8 == 0 {
9133        return unsetenv(s);
9134    }
9135    putenv_internal(s, l, core::ptr::null_mut())
9136}
9137
9138#[no_mangle]
9139pub unsafe extern "C" fn unsetenv(name: *const c_char) -> c_int {
9140    if name.is_null() {
9141        ERRNO!() = EINVAL;
9142        return -1;
9143    }
9144    let name = name as *const u8;
9145    let l = strchrnul_u8(name, b'=') as usize - name as usize;
9146    if l == 0 || *name.add(l) != 0 {
9147        ERRNO!() = EINVAL;
9148        return -1;
9149    }
9150    if __environ.is_null() {
9151        return 0;
9152    }
9153    let mut e = __environ;
9154    let mut eo = e;
9155    while !(*e).is_null() {
9156        if strncmp(name, *e as *const u8, l) == 0 && *(*e as *const u8).add(l) == b'=' {
9157            env_rm_add(*e, core::ptr::null_mut());
9158        } else {
9159            if eo != e {
9160                *eo = *e;
9161            }
9162            eo = eo.add(1);
9163        }
9164        e = e.add(1);
9165    }
9166    if eo != e {
9167        *eo = core::ptr::null_mut();
9168    }
9169    environ = __environ;
9170    0
9171}
9172
9173#[no_mangle]
9174pub unsafe extern "C" fn clearenv() -> c_int {
9175    let e = __environ;
9176    __environ = core::ptr::null_mut();
9177    environ = core::ptr::null_mut();
9178    if !e.is_null() {
9179        let mut p = e;
9180        while !(*p).is_null() {
9181            env_rm_add(*p, core::ptr::null_mut());
9182            p = p.add(1);
9183        }
9184    }
9185    0
9186}
9187
9188// ============================================================
9189// random / srandom / initstate / setstate (BSD lagged fibonacci)
9190// ponytail: single-threaded, no locking; add lock if concurrency matters
9191// ============================================================
9192
9193static mut RANDOM_INIT: [u32; 32] = [
9194    0x00000000,0x5851f42d,0xc0b18ccf,0xcbb5f646,
9195    0xc7033129,0x30705b04,0x20fd5db4,0x9a8b7f78,
9196    0x502959d8,0xab894868,0x6c0356a7,0x88cdb7ff,
9197    0xb477d43f,0x70a3a52b,0xa8e4baf1,0xfd8341fc,
9198    0x8ae16fd9,0x742d2f7a,0x0d1f0796,0x76035e09,
9199    0x40f7702c,0x6fa72ca5,0xaaa84157,0x58a0df74,
9200    0xc74a0364,0xae533cc4,0x04185faf,0x6de3b115,
9201    0x0cab8628,0xf043bfa4,0x398150e9,0x37521657,
9202];
9203
9204static mut RANDOM_N: i32 = 31;
9205static mut RANDOM_I: i32 = 3;
9206static mut RANDOM_J: i32 = 0;
9207static mut RANDOM_X: *mut u32 = unsafe { core::ptr::addr_of_mut!(RANDOM_INIT).cast::<u32>().add(1) };
9208
9209unsafe fn random_lcg31(x: u32) -> u32 {
9210    (1103515245u32.wrapping_mul(x).wrapping_add(12345)) & 0x7fffffff
9211}
9212
9213unsafe fn random_lcg64(x: u64) -> u64 {
9214    6364136223846793005u64.wrapping_mul(x).wrapping_add(1)
9215}
9216
9217unsafe fn random_savestate() -> *mut u8 {
9218    (*RANDOM_X.offset(-1)) = ((RANDOM_N as u32) << 16) | ((RANDOM_I as u32) << 8) | (RANDOM_J as u32);
9219    RANDOM_X.offset(-1) as *mut u8
9220}
9221
9222unsafe fn random_loadstate(state: *mut u32) {
9223    RANDOM_X = state.add(1);
9224    RANDOM_N = ((*RANDOM_X.offset(-1)) >> 16) as i32;
9225    RANDOM_I = (((*RANDOM_X.offset(-1)) >> 8) & 0xff) as i32;
9226    RANDOM_J = ((*RANDOM_X.offset(-1)) & 0xff) as i32;
9227}
9228
9229unsafe fn random_srandom_inner(seed: u32) {
9230    let mut s = seed as u64;
9231    if RANDOM_N == 0 {
9232        *RANDOM_X = s as u32;
9233        return;
9234    }
9235    RANDOM_I = if RANDOM_N == 31 || RANDOM_N == 7 { 3 } else { 1 };
9236    RANDOM_J = 0;
9237    for k in 0..RANDOM_N as usize {
9238        s = random_lcg64(s);
9239        *RANDOM_X.add(k) = (s >> 32) as u32;
9240    }
9241    *RANDOM_X |= 1;
9242}
9243
9244#[no_mangle]
9245pub unsafe extern "C" fn srandom(seed: c_uint) {
9246    random_srandom_inner(seed);
9247}
9248
9249#[no_mangle]
9250pub unsafe extern "C" fn initstate(seed: c_uint, state: *mut c_char, size: usize) -> *mut c_char {
9251    if size < 8 { return core::ptr::null_mut(); }
9252    let old = random_savestate();
9253    RANDOM_N = if size < 32 { 0 }
9254        else if size < 64 { 7 }
9255        else if size < 128 { 15 }
9256        else if size < 256 { 31 }
9257        else { 63 };
9258    RANDOM_X = (state as *mut u32).add(1);
9259    random_srandom_inner(seed);
9260    random_savestate();
9261    old as *mut c_char
9262}
9263
9264#[no_mangle]
9265pub unsafe extern "C" fn setstate(state: *mut c_char) -> *mut c_char {
9266    let old = random_savestate();
9267    random_loadstate(state as *mut u32);
9268    old as *mut c_char
9269}
9270
9271#[no_mangle]
9272pub unsafe extern "C" fn random() -> c_long {
9273    let k: c_long;
9274    if RANDOM_N == 0 {
9275        *RANDOM_X = random_lcg31(*RANDOM_X);
9276        k = *RANDOM_X as c_long;
9277    } else {
9278        *RANDOM_X.add(RANDOM_I as usize) = (*RANDOM_X.add(RANDOM_I as usize)).wrapping_add(*RANDOM_X.add(RANDOM_J as usize));
9279        k = (*RANDOM_X.add(RANDOM_I as usize) >> 1) as c_long;
9280        RANDOM_I += 1;
9281        if RANDOM_I == RANDOM_N { RANDOM_I = 0; }
9282        RANDOM_J += 1;
9283        if RANDOM_J == RANDOM_N { RANDOM_J = 0; }
9284    }
9285    k
9286}
9287
9288// ============================================================
9289// multibyte (UTF-8, musl state machine)
9290// ============================================================
9291
9292const SA: u8 = 0xC2;
9293const SB: u8 = 0xF4;
9294
9295const BITTAB: [u32; 51] = [
9296    0xC000_0002, 0xC000_0003, 0xC000_0004, 0xC000_0005, 0xC000_0006, 0xC000_0007,
9297    0xC000_0008, 0xC000_0009, 0xC000_000A, 0xC000_000B, 0xC000_000C, 0xC000_000D,
9298    0xC000_000E, 0xC000_000F, 0xC000_0010, 0xC000_0011, 0xC000_0012, 0xC000_0013,
9299    0xC000_0014, 0xC000_0015, 0xC000_0016, 0xC000_0017, 0xC000_0018, 0xC000_0019,
9300    0xC000_001A, 0xC000_001B, 0xC000_001C, 0xC000_001D, 0xC000_001E, 0xC000_001F,
9301    0xB300_0000, 0xC300_0001, 0xC300_0002, 0xC300_0003, 0xC300_0004, 0xC300_0005,
9302    0xC300_0006, 0xC300_0007, 0xC300_0008, 0xC300_0009, 0xC300_000A, 0xC300_000B,
9303    0xC300_000C, 0xD300_000D, 0xC300_000E, 0xC300_000F, 0xBB0C_0000, 0xC30C_0001,
9304    0xC30C_0002, 0xC30C_0003, 0xDB0C_0004,
9305];
9306
9307#[inline]
9308fn mb_oob(c: u32, b: u8) -> u32 {
9309    let b3 = (b >> 3) as u32;
9310    ((b3.wrapping_sub(0x10)) | (b3.wrapping_add((c as i32 >> 26) as u32))) & !7
9311}
9312
9313static mut MB_STATE: c_uint = 0;
9314
9315const MB_CUR_MAX_VAL_UTF8: usize = 4;
9316const MB_CUR_MAX_VAL_C: usize = 1;
9317
9318#[no_mangle]
9319pub extern "C" fn __ctype_get_mb_cur_max() -> usize {
9320    unsafe { if LOCALE_CTYPE_UTF8 { MB_CUR_MAX_VAL_UTF8 } else { MB_CUR_MAX_VAL_C } }
9321}
9322
9323#[no_mangle]
9324pub unsafe extern "C" fn mbrtowc(
9325    wc: *mut c_int,
9326    src: *const c_char,
9327    n: usize,
9328    st: *mut c_uint,
9329) -> usize {
9330    let s = src as *const u8;
9331    let n0 = n;
9332    let mut dummy: c_int = 0;
9333    let wc = if wc.is_null() { &mut dummy } else { &mut *wc };
9334    let st: &mut c_uint = if st.is_null() { &mut *(&raw mut MB_STATE) } else { &mut *st };
9335
9336    let mut c: u32 = *st;
9337    let mut s = s;
9338    let mut n = n;
9339
9340    if s.is_null() {
9341        if c != 0 { *st = 0; ERRNO!() = EILSEQ; return !0usize; }
9342        return 0;
9343    }
9344
9345    if n == 0 { return !1usize; }
9346
9347    if unsafe { !LOCALE_CTYPE_UTF8 } {
9348        let b = *s;
9349        *wc = b as c_int;
9350        return if b == 0 { 0 } else { 1 };
9351    }
9352
9353    if c == 0 {
9354        if *s < 0x80 {
9355            let r = if *s == 0 { 0 } else { 1 };
9356            *wc = *s as c_int;
9357            return r;
9358        }
9359        if (*s).wrapping_sub(SA) as u32 > (SB - SA) as u32 {
9360            *st = 0; ERRNO!() = EILSEQ; return !0usize;
9361        }
9362        c = BITTAB[*s as usize - SA as usize];
9363        s = s.add(1);
9364        n -= 1;
9365    }
9366
9367    if n > 0 {
9368        if mb_oob(c, *s) != 0 {
9369            *st = 0; ERRNO!() = EILSEQ; return !0usize;
9370        }
9371        loop {
9372            c = (c << 6) | (*s as u32).wrapping_sub(0x80);
9373            s = s.add(1);
9374            n -= 1;
9375            if c & (1u32 << 31) == 0 {
9376                *st = 0;
9377                *wc = c as c_int;
9378                return n0 - n;
9379            }
9380            if n == 0 { break; }
9381            if (*s).wrapping_sub(0x80) >= 0x40 {
9382                *st = 0; ERRNO!() = EILSEQ; return !0usize;
9383            }
9384        }
9385    }
9386
9387    *st = c;
9388    !1usize
9389}
9390
9391#[no_mangle]
9392pub unsafe extern "C" fn wcrtomb(
9393    s: *mut c_char,
9394    wc: c_int,
9395    _st: *mut c_uint,
9396) -> usize {
9397    if s.is_null() { return 1; }
9398    let wc_u = wc as u32;
9399    if unsafe { !LOCALE_CTYPE_UTF8 } {
9400        if wc_u > 0xFF {
9401            ERRNO!() = EILSEQ;
9402            return !0usize;
9403        }
9404        *s = wc as c_char;
9405        return 1;
9406    }
9407    if wc_u < 0x80 {
9408        *s = wc as c_char;
9409        return 1;
9410    }
9411    if wc_u < 0x800 {
9412        *s = (0xC0 | (wc_u >> 6)) as c_char;
9413        *s.add(1) = (0x80 | (wc_u & 0x3F)) as c_char;
9414        return 2;
9415    }
9416    if wc_u < 0xD800 || wc_u.wrapping_sub(0xE000) < 0x2000 {
9417        *s = (0xE0 | (wc_u >> 12)) as c_char;
9418        *s.add(1) = (0x80 | ((wc_u >> 6) & 0x3F)) as c_char;
9419        *s.add(2) = (0x80 | (wc_u & 0x3F)) as c_char;
9420        return 3;
9421    }
9422    if wc_u.wrapping_sub(0x10000) < 0x100000 {
9423        *s = (0xF0 | (wc_u >> 18)) as c_char;
9424        *s.add(1) = (0x80 | ((wc_u >> 12) & 0x3F)) as c_char;
9425        *s.add(2) = (0x80 | ((wc_u >> 6) & 0x3F)) as c_char;
9426        *s.add(3) = (0x80 | (wc_u & 0x3F)) as c_char;
9427        return 4;
9428    }
9429    ERRNO!() = EILSEQ;
9430    !0usize
9431}
9432
9433#[no_mangle]
9434pub unsafe extern "C" fn mblen(s: *const c_char, n: usize) -> c_int {
9435    if s.is_null() { return 0; }
9436    mbtowc(core::ptr::null_mut(), s, n)
9437}
9438
9439#[no_mangle]
9440pub unsafe extern "C" fn mbtowc(
9441    wc: *mut c_int,
9442    src: *const c_char,
9443    n: usize,
9444) -> c_int {
9445    if src.is_null() { return 0; }
9446    if n == 0 { ERRNO!() = EILSEQ; return -1; }
9447    let mut state: c_uint = 0;
9448    let mut w: c_int = 0;
9449    let r = mbrtowc(&mut w, src, n, &mut state);
9450    if r == !0usize { return -1; }
9451    if !wc.is_null() { *wc = w; }
9452    r as c_int
9453}
9454
9455#[no_mangle]
9456pub unsafe extern "C" fn wctomb(s: *mut c_char, wc: c_int) -> c_int {
9457    if s.is_null() { return 0; }
9458    wcrtomb(s, wc, core::ptr::null_mut()) as c_int
9459}
9460
9461#[no_mangle]
9462pub unsafe extern "C" fn mbsrtowcs(
9463    ws: *mut c_int,
9464    src: *mut *const c_char,
9465    wn: usize,
9466    st: *mut c_uint,
9467) -> usize {
9468    let st: &mut c_uint = if st.is_null() { &mut *(&raw mut MB_STATE) } else { &mut *st };
9469    let mut s = *src as *const u8;
9470    let wn0 = wn;
9471    let mut wn = wn;
9472
9473    if ws.is_null() {
9474        while *s != 0 {
9475            if *s < 0x80 {
9476                s = s.add(1);
9477                wn = wn.wrapping_sub(1);
9478                continue;
9479            }
9480            let mut wc: c_int = 0;
9481            let r = mbrtowc(&mut wc, s as *const c_char, 4, st);
9482            if r == !0usize { return !0usize; }
9483            if r == !1usize { return wn0 - wn; }
9484            s = s.add(r);
9485            wn = wn.wrapping_sub(1);
9486        }
9487        wn0 - wn
9488    } else {
9489        let mut w = ws;
9490        while wn > 0 {
9491            if *s < 0x80 {
9492                let c = *s as c_int;
9493                *w = c;
9494                if c == 0 {
9495                    *src = core::ptr::null();
9496                    return wn0 - wn;
9497                }
9498                w = w.add(1);
9499                s = s.add(1);
9500                wn -= 1;
9501                continue;
9502            }
9503            let mut wc: c_int = 0;
9504            let r = mbrtowc(&mut wc, s as *const c_char, 4, st);
9505            if r == !0usize {
9506                *src = s as *const c_char;
9507                return !0usize;
9508            }
9509            if r == !1usize {
9510                *src = s as *const c_char;
9511                return wn0 - wn;
9512            }
9513            *w = wc;
9514            w = w.add(1);
9515            s = s.add(r);
9516            wn -= 1;
9517        }
9518        *src = s as *const c_char;
9519        wn0 - wn
9520    }
9521}
9522
9523#[no_mangle]
9524pub unsafe extern "C" fn wcsrtombs(
9525    s: *mut c_char,
9526    ws: *mut *const c_int,
9527    n: usize,
9528    _st: *mut c_uint,
9529) -> usize {
9530    let mut w = *ws;
9531    let n0 = n;
9532    let mut n = n;
9533
9534    if s.is_null() {
9535        let mut count = 0usize;
9536        while *w != 0 {
9537            if (*w as u32) < 0x80 {
9538                count += 1;
9539            } else {
9540                let mut buf = [0u8; 4];
9541                let r = wcrtomb(buf.as_mut_ptr() as *mut c_char, *w, core::ptr::null_mut());
9542                if r == !0usize { return !0usize; }
9543                count += r;
9544            }
9545            w = w.add(1);
9546        }
9547        return count;
9548    }
9549
9550    let mut dst = s;
9551    while n > 0 {
9552        if (*w as u32) < 0x80 {
9553            *dst = *w as c_char;
9554            if *w == 0 {
9555                *ws = core::ptr::null();
9556                return n0 - n;
9557            }
9558            dst = dst.add(1);
9559            n -= 1;
9560        } else {
9561            let r = wcrtomb(dst, *w, core::ptr::null_mut());
9562            if r == !0usize {
9563                *ws = w;
9564                return !0usize;
9565            }
9566            if r > n {
9567                *ws = w;
9568                return n0 - n;
9569            }
9570            dst = dst.add(r);
9571            n -= r;
9572        }
9573        w = w.add(1);
9574    }
9575    *ws = w;
9576    n0
9577}
9578
9579#[no_mangle]
9580pub unsafe extern "C" fn mbstowcs(
9581    ws: *mut c_int,
9582    src: *const c_char,
9583    wn: usize,
9584) -> usize {
9585    let mut src_ptr = src;
9586    mbsrtowcs(ws, &mut src_ptr, wn, core::ptr::null_mut())
9587}
9588
9589#[no_mangle]
9590pub unsafe extern "C" fn wcstombs(
9591    s: *mut c_char,
9592    ws: *const c_int,
9593    n: usize,
9594) -> usize {
9595    let mut ws_ptr = ws;
9596    wcsrtombs(s, &mut ws_ptr, n, core::ptr::null_mut())
9597}
9598
9599// ============================================================
9600// wchar: btowc / wctob / mbsinit / mbrlen
9601// ============================================================
9602
9603#[no_mangle]
9604pub extern "C" fn btowc(c: c_int) -> wint_t {
9605    if c == -1 { return WEOF; }
9606    unsafe {
9607        if LOCALE_CTYPE_UTF8 {
9608            if (c as u32) < 128 { c as wint_t } else { WEOF }
9609        } else {
9610            (c as u8) as wint_t
9611        }
9612    }
9613}
9614
9615#[no_mangle]
9616pub extern "C" fn wctob(c: wint_t) -> c_int {
9617    unsafe {
9618        if LOCALE_CTYPE_UTF8 {
9619            if c < 128 { c as c_int } else { -1 }
9620        } else {
9621            if c <= 0xFF { c as c_int } else { -1 }
9622        }
9623    }
9624}
9625
9626#[no_mangle]
9627pub unsafe extern "C" fn mbsinit(s: *const c_uint) -> c_int {
9628    if s.is_null() || *s == 0 { 1 } else { 0 }
9629}
9630
9631#[no_mangle]
9632pub unsafe extern "C" fn mbrlen(s: *const c_char, n: usize, ps: *mut c_uint) -> usize {
9633    mbrtowc(core::ptr::null_mut(), s, n, ps)
9634}
9635
9636// ============================================================
9637// wchar: wide string functions
9638// ============================================================
9639
9640#[no_mangle]
9641pub unsafe extern "C" fn wcslen(s: *const wchar_t) -> usize {
9642    let mut len = 0;
9643    while *s.add(len) != 0 { len += 1; }
9644    len
9645}
9646
9647#[no_mangle]
9648pub unsafe extern "C" fn wcschr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
9649    let mut i = 0;
9650    loop {
9651        let ch = *s.add(i);
9652        if ch == c { return s.add(i) as *mut wchar_t; }
9653        if ch == 0 { return null_mut(); }
9654        i += 1;
9655    }
9656}
9657
9658#[no_mangle]
9659pub unsafe extern "C" fn wcsrchr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
9660    let mut i = 0;
9661    let mut last: *mut wchar_t = null_mut();
9662    loop {
9663        let ch = *s.add(i);
9664        if ch == c { last = s.add(i) as *mut wchar_t; }
9665        if ch == 0 { return last; }
9666        i += 1;
9667    }
9668}
9669
9670#[no_mangle]
9671pub unsafe extern "C" fn wcsstr(haystack: *const wchar_t, needle: *const wchar_t) -> *mut wchar_t {
9672    if *needle == 0 { return haystack as *mut wchar_t; }
9673    let mut i = 0;
9674    loop {
9675        let h = *haystack.add(i);
9676        if h == 0 { return null_mut(); }
9677        if h == *needle {
9678            let mut j = 0;
9679            loop {
9680                let n = *needle.add(j);
9681                if n == 0 { return haystack.add(i) as *mut wchar_t; }
9682                if *haystack.add(i + j) != n { break; }
9683                j += 1;
9684            }
9685        }
9686        i += 1;
9687    }
9688}
9689
9690#[no_mangle]
9691pub unsafe extern "C" fn wcscmp(s1: *const wchar_t, s2: *const wchar_t) -> c_int {
9692    let mut i = 0;
9693    loop {
9694        let a = *s1.add(i);
9695        let b = *s2.add(i);
9696        if a != b { return a - b; }
9697        if a == 0 { return 0; }
9698        i += 1;
9699    }
9700}
9701
9702#[no_mangle]
9703pub unsafe extern "C" fn wcsncmp(s1: *const wchar_t, s2: *const wchar_t, n: usize) -> c_int {
9704    let mut i = 0;
9705    while i < n {
9706        let a = *s1.add(i);
9707        let b = *s2.add(i);
9708        if a != b { return a - b; }
9709        if a == 0 { return 0; }
9710        i += 1;
9711    }
9712    0
9713}
9714
9715#[no_mangle]
9716pub unsafe extern "C" fn wcscpy(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
9717    let mut i = 0;
9718    loop {
9719        let c = *src.add(i);
9720        *dst.add(i) = c;
9721        if c == 0 { break; }
9722        i += 1;
9723    }
9724    dst
9725}
9726
9727#[no_mangle]
9728pub unsafe extern "C" fn wcsncpy(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
9729    let mut i = 0;
9730    while i < n && *src.add(i) != 0 { *dst.add(i) = *src.add(i); i += 1; }
9731    while i < n { *dst.add(i) = 0; i += 1; }
9732    dst
9733}
9734
9735#[no_mangle]
9736pub unsafe extern "C" fn wcscat(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
9737    let mut i = 0;
9738    while *dst.add(i) != 0 { i += 1; }
9739    let mut j = 0;
9740    loop {
9741        let c = *src.add(j);
9742        *dst.add(i + j) = c;
9743        if c == 0 { break; }
9744        j += 1;
9745    }
9746    dst
9747}
9748
9749#[no_mangle]
9750pub unsafe extern "C" fn wcsncat(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
9751    let mut i = 0;
9752    while *dst.add(i) != 0 { i += 1; }
9753    let mut j = 0;
9754    while j < n && *src.add(j) != 0 { *dst.add(i + j) = *src.add(j); j += 1; }
9755    *dst.add(i + j) = 0;
9756    dst
9757}
9758
9759#[no_mangle]
9760pub unsafe extern "C" fn wcsdup(s: *const wchar_t) -> *mut wchar_t {
9761    let len = wcslen(s);
9762    let p = malloc((len + 1) * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
9763    if p.is_null() { return null_mut(); }
9764    core::ptr::copy_nonoverlapping(s, p, len + 1);
9765    p
9766}
9767
9768#[no_mangle]
9769pub unsafe extern "C" fn wcsnlen(s: *const wchar_t, maxlen: usize) -> usize {
9770    let mut i = 0;
9771    while i < maxlen && *s.add(i) != 0 { i += 1; }
9772    i
9773}
9774
9775#[no_mangle]
9776pub unsafe extern "C" fn wcsspn(s: *const wchar_t, accept: *const wchar_t) -> usize {
9777    let mut i = 0;
9778    loop {
9779        let c = *s.add(i);
9780        if c == 0 { return i; }
9781        let mut found = false;
9782        let mut j = 0;
9783        loop {
9784            let a = *accept.add(j);
9785            if a == 0 { break; }
9786            if c == a { found = true; break; }
9787            j += 1;
9788        }
9789        if !found { return i; }
9790        i += 1;
9791    }
9792}
9793
9794#[no_mangle]
9795pub unsafe extern "C" fn wcscspn(s: *const wchar_t, reject: *const wchar_t) -> usize {
9796    let mut i = 0;
9797    loop {
9798        let c = *s.add(i);
9799        if c == 0 { return i; }
9800        let mut j = 0;
9801        loop {
9802            let r = *reject.add(j);
9803            if r == 0 { break; }
9804            if c == r { return i; }
9805            j += 1;
9806        }
9807        i += 1;
9808    }
9809}
9810
9811#[no_mangle]
9812pub unsafe extern "C" fn wcspbrk(s: *const wchar_t, accept: *const wchar_t) -> *mut wchar_t {
9813    let mut i = 0;
9814    loop {
9815        let c = *s.add(i);
9816        if c == 0 { return null_mut(); }
9817        let mut j = 0;
9818        loop {
9819            let a = *accept.add(j);
9820            if a == 0 { break; }
9821            if c == a { return s.add(i) as *mut wchar_t; }
9822            j += 1;
9823        }
9824        i += 1;
9825    }
9826}
9827
9828#[no_mangle]
9829pub unsafe extern "C" fn wcsxfrm(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> usize {
9830    let len = wcslen(src);
9831    if !dst.is_null() {
9832        let copy = if len < n { len } else { if n > 0 { n - 1 } else { 0 } };
9833        for i in 0..copy { *dst.add(i) = *src.add(i); }
9834        if n > 0 { *dst.add(copy) = 0; }
9835    }
9836    len
9837}
9838
9839// ============================================================
9840// wchar: wcsto* number conversions
9841// ============================================================
9842
9843unsafe fn wcs_to_bytes(ws: *const wchar_t, buf: *mut u8, bufsz: usize) -> usize {
9844    let mut i = 0;
9845    while i < bufsz - 1 {
9846        let c = *ws.add(i);
9847        if c == 0 { break; }
9848        if (c as u32) > 127 { break; }
9849        *buf.add(i) = c as u8;
9850        i += 1;
9851    }
9852    *buf.add(i) = 0;
9853    i
9854}
9855
9856#[no_mangle]
9857pub unsafe extern "C" fn wcstol(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_long {
9858    let mut buf = [0u8; 256];
9859    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9860    let mut end: *mut c_char = core::ptr::null_mut();
9861    let r = strtol(buf.as_ptr() as *const c_char, &mut end, base);
9862    if !endptr.is_null() {
9863        let offset = end as usize - buf.as_ptr() as usize;
9864        *endptr = s.add(offset) as *mut wchar_t;
9865    }
9866    r
9867}
9868
9869#[no_mangle]
9870pub unsafe extern "C" fn wcstoul(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulong {
9871    let mut buf = [0u8; 256];
9872    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9873    let mut end: *mut c_char = core::ptr::null_mut();
9874    let r = strtoul(buf.as_ptr() as *const c_char, &mut end, base);
9875    if !endptr.is_null() {
9876        let offset = end as usize - buf.as_ptr() as usize;
9877        *endptr = s.add(offset) as *mut wchar_t;
9878    }
9879    r
9880}
9881
9882#[no_mangle]
9883pub unsafe extern "C" fn wcstoll(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_longlong {
9884    let mut buf = [0u8; 256];
9885    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9886    let mut end: *mut c_char = core::ptr::null_mut();
9887    let r = strtoll(buf.as_ptr() as *const c_char, &mut end, base);
9888    if !endptr.is_null() {
9889        let offset = end as usize - buf.as_ptr() as usize;
9890        *endptr = s.add(offset) as *mut wchar_t;
9891    }
9892    r
9893}
9894
9895#[no_mangle]
9896pub unsafe extern "C" fn wcstoull(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulonglong {
9897    let mut buf = [0u8; 256];
9898    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9899    let mut end: *mut c_char = core::ptr::null_mut();
9900    let r = strtoull(buf.as_ptr() as *const c_char, &mut end, base);
9901    if !endptr.is_null() {
9902        let offset = end as usize - buf.as_ptr() as usize;
9903        *endptr = s.add(offset) as *mut wchar_t;
9904    }
9905    r
9906}
9907
9908#[no_mangle]
9909pub unsafe extern "C" fn wcstod(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 {
9910    let mut buf = [0u8; 256];
9911    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9912    let mut end: *mut c_char = core::ptr::null_mut();
9913    let r = strtod(buf.as_ptr() as *const c_char, &mut end);
9914    if !endptr.is_null() {
9915        let offset = end as usize - buf.as_ptr() as usize;
9916        *endptr = s.add(offset) as *mut wchar_t;
9917    }
9918    r
9919}
9920
9921#[no_mangle]
9922pub unsafe extern "C" fn wcstof(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f32 { wcstod(s, endptr) as f32 }
9923
9924#[no_mangle]
9925#[cfg(target_arch = "x86_64")]
9926pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 { wcstod(s, endptr) }
9927
9928#[no_mangle]
9929#[cfg(target_arch = "aarch64")]
9930pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { wcstod(s, endptr) as f128 }
9931
9932#[no_mangle]
9933#[cfg(target_arch = "riscv64")]
9934pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { wcstod(s, endptr) as f128 }
9935
9936#[no_mangle]
9937pub unsafe extern "C" fn wcstoimax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_longlong { wcstoll(s, endptr, base) }
9938
9939#[no_mangle]
9940pub unsafe extern "C" fn wcstoumax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulonglong { wcstoull(s, endptr, base) }
9941
9942// ============================================================
9943// wctype: classification functions
9944// ============================================================
9945
9946const WC_ALPHA: c_int = 1;
9947const WC_DIGIT: c_int = 2;
9948const WC_SPACE: c_int = 4;
9949const WC_UPPER: c_int = 8;
9950const WC_LOWER: c_int = 16;
9951const WC_ALNUM: c_int = WC_ALPHA | WC_DIGIT;
9952const WC_BLANK: c_int = 32;
9953const WC_CNTRL: c_int = 64;
9954const WC_PUNCT: c_int = 128;
9955const WC_GRAPH: c_int = WC_ALNUM | WC_PUNCT;
9956const WC_PRINT: c_int = WC_GRAPH | WC_BLANK;
9957const WC_XDIGIT: c_int = 256;
9958
9959fn wc_flags(c: wint_t) -> c_int {
9960    if c < 128 {
9961        let f = CT_TABLE[c as usize];
9962        let mut r = 0;
9963        if f & (CT_UPPER | CT_LOWER) != 0 { r |= WC_ALPHA; }
9964        if f & CT_DIGIT != 0 { r |= WC_DIGIT; }
9965        if f & CT_SPACE != 0 { r |= WC_SPACE; }
9966        if f & CT_UPPER != 0 { r |= WC_UPPER; }
9967        if f & CT_LOWER != 0 { r |= WC_LOWER; }
9968        if f & CT_BLANK != 0 { r |= WC_BLANK; }
9969        if f & CT_CNTRL != 0 { r |= WC_CNTRL; }
9970        if f & CT_PUNCT != 0 { r |= WC_PUNCT; }
9971        if f & CT_XDIGIT != 0 { r |= WC_XDIGIT; }
9972        r
9973    } else {
9974        if c < 0x100 { 0 }
9975        else { WC_PRINT | WC_ALPHA }
9976    }
9977}
9978
9979#[no_mangle]
9980pub extern "C" fn iswalnum(c: wint_t) -> c_int { (wc_flags(c) & WC_ALNUM != 0) as c_int }
9981#[no_mangle]
9982pub extern "C" fn iswalpha(c: wint_t) -> c_int { (wc_flags(c) & WC_ALPHA != 0) as c_int }
9983#[no_mangle]
9984pub extern "C" fn iswblank(c: wint_t) -> c_int { (wc_flags(c) & WC_BLANK != 0) as c_int }
9985#[no_mangle]
9986pub extern "C" fn iswcntrl(c: wint_t) -> c_int { (wc_flags(c) & WC_CNTRL != 0) as c_int }
9987#[no_mangle]
9988pub extern "C" fn iswdigit(c: wint_t) -> c_int { ((c >= b'0' as wint_t) && (c <= b'9' as wint_t)) as c_int }
9989#[no_mangle]
9990pub extern "C" fn iswgraph(c: wint_t) -> c_int { (wc_flags(c) & WC_GRAPH != 0) as c_int }
9991#[no_mangle]
9992pub extern "C" fn iswlower(c: wint_t) -> c_int { (wc_flags(c) & WC_LOWER != 0) as c_int }
9993#[no_mangle]
9994pub extern "C" fn iswprint(c: wint_t) -> c_int {
9995    if c < 128 { (wc_flags(c) & WC_PRINT != 0) as c_int }
9996    else if c >= 0x100 && c < 0x110000 { 1 }
9997    else { 0 }
9998}
9999#[no_mangle]
10000pub extern "C" fn iswpunct(c: wint_t) -> c_int { (wc_flags(c) & WC_PUNCT != 0) as c_int }
10001#[no_mangle]
10002pub extern "C" fn iswspace(c: wint_t) -> c_int {
10003    if c < 128 { (wc_flags(c) & WC_SPACE != 0) as c_int }
10004    else {
10005        match c {
10006            0x1680 | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000 => 1,
10007            _ => 0,
10008        }
10009    }
10010}
10011#[no_mangle]
10012pub extern "C" fn iswupper(c: wint_t) -> c_int { (wc_flags(c) & WC_UPPER != 0) as c_int }
10013#[no_mangle]
10014pub extern "C" fn iswxdigit(c: wint_t) -> c_int { (wc_flags(c) & WC_XDIGIT != 0) as c_int }
10015
10016static WCTYPE_ALNUM: c_int = WC_ALNUM;
10017static WCTYPE_ALPHA: c_int = WC_ALPHA;
10018static WCTYPE_BLANK: c_int = WC_BLANK;
10019static WCTYPE_CNTRL: c_int = WC_CNTRL;
10020static WCTYPE_DIGIT: c_int = WC_DIGIT;
10021static WCTYPE_GRAPH: c_int = WC_GRAPH;
10022static WCTYPE_LOWER: c_int = WC_LOWER;
10023static WCTYPE_PRINT: c_int = WC_PRINT;
10024static WCTYPE_PUNCT: c_int = WC_PUNCT;
10025static WCTYPE_SPACE: c_int = WC_SPACE;
10026static WCTYPE_UPPER: c_int = WC_UPPER;
10027static WCTYPE_XDIGIT: c_int = WC_XDIGIT;
10028
10029#[no_mangle]
10030pub unsafe extern "C" fn wctype(name: *const c_char) -> wctype_t {
10031    if name.is_null() { return core::ptr::null(); }
10032    let n = name as *const u8;
10033    if strcmp(n, b"alnum\0".as_ptr()) == 0 { return &WCTYPE_ALNUM; }
10034    if strcmp(n, b"alpha\0".as_ptr()) == 0 { return &WCTYPE_ALPHA; }
10035    if strcmp(n, b"blank\0".as_ptr()) == 0 { return &WCTYPE_BLANK; }
10036    if strcmp(n, b"cntrl\0".as_ptr()) == 0 { return &WCTYPE_CNTRL; }
10037    if strcmp(n, b"digit\0".as_ptr()) == 0 { return &WCTYPE_DIGIT; }
10038    if strcmp(n, b"graph\0".as_ptr()) == 0 { return &WCTYPE_GRAPH; }
10039    if strcmp(n, b"lower\0".as_ptr()) == 0 { return &WCTYPE_LOWER; }
10040    if strcmp(n, b"print\0".as_ptr()) == 0 { return &WCTYPE_PRINT; }
10041    if strcmp(n, b"punct\0".as_ptr()) == 0 { return &WCTYPE_PUNCT; }
10042    if strcmp(n, b"space\0".as_ptr()) == 0 { return &WCTYPE_SPACE; }
10043    if strcmp(n, b"upper\0".as_ptr()) == 0 { return &WCTYPE_UPPER; }
10044    if strcmp(n, b"xdigit\0".as_ptr()) == 0 { return &WCTYPE_XDIGIT; }
10045    core::ptr::null()
10046}
10047
10048#[no_mangle]
10049pub unsafe extern "C" fn iswctype(c: wint_t, desc: wctype_t) -> c_int {
10050    if desc.is_null() { return 0; }
10051    (wc_flags(c) & *desc != 0) as c_int
10052}
10053
10054static WCTRANS_LOWER: c_int = 1;
10055static WCTRANS_UPPER: c_int = 2;
10056
10057#[no_mangle]
10058pub unsafe extern "C" fn towlower(c: wint_t) -> wint_t {
10059    if c < 128 { tolower(c as c_int) as wint_t } else { c }
10060}
10061
10062#[no_mangle]
10063pub unsafe extern "C" fn towupper(c: wint_t) -> wint_t {
10064    if c < 128 { toupper(c as c_int) as wint_t } else { c }
10065}
10066
10067#[no_mangle]
10068pub unsafe extern "C" fn wctrans(name: *const c_char) -> wctrans_t {
10069    if name.is_null() { return core::ptr::null(); }
10070    let n = name as *const u8;
10071    if strcmp(n, b"tolower\0".as_ptr()) == 0 { return &WCTRANS_LOWER; }
10072    if strcmp(n, b"toupper\0".as_ptr()) == 0 { return &WCTRANS_UPPER; }
10073    core::ptr::null()
10074}
10075
10076#[no_mangle]
10077pub unsafe extern "C" fn towctrans(c: wint_t, desc: wctrans_t) -> wint_t {
10078    if desc.is_null() { return c; }
10079    match *desc {
10080        1 => towlower(c),
10081        2 => towupper(c),
10082        _ => c,
10083    }
10084}
10085
10086// ============================================================
10087// wchar: wide stdio
10088// ============================================================
10089
10090#[no_mangle]
10091pub unsafe extern "C" fn fgetwc(f: *mut FILE) -> wint_t {
10092    let mut state: c_uint = 0;
10093    let mut wc: wchar_t = 0;
10094    let mut buf = [0u8; 4];
10095    let c = fgetc(f);
10096    if c == -1 { return WEOF; }
10097    buf[0] = c as u8;
10098    if buf[0] < 0x80 { return buf[0] as wint_t; }
10099    let len = if buf[0] < 0xE0 { 2 } else if buf[0] < 0xF0 { 3 } else { 4 };
10100    let mut n = 1usize;
10101    while n < len {
10102        let c2 = fgetc(f);
10103        if c2 == -1 { return WEOF; }
10104        buf[n] = c2 as u8;
10105        n += 1;
10106    }
10107    let r = mbrtowc(&mut wc, buf.as_ptr() as *const c_char, n, &mut state);
10108    if r == !0usize || r == !1usize { WEOF } else { wc as wint_t }
10109}
10110
10111#[no_mangle]
10112pub unsafe extern "C" fn fputwc(c: wchar_t, f: *mut FILE) -> wint_t {
10113    let mut buf = [0u8; 4];
10114    let n = wcrtomb(buf.as_mut_ptr() as *mut c_char, c, core::ptr::null_mut());
10115    if n == !0usize || n == 0 { return WEOF; }
10116    if fwrite(buf.as_ptr() as *const c_void, 1, n, f) != n { return WEOF; }
10117    c as wint_t
10118}
10119
10120#[no_mangle]
10121pub unsafe extern "C" fn fputws(s: *const wchar_t, f: *mut FILE) -> c_int {
10122    let mut i = 0;
10123    while *s.add(i) != 0 {
10124        if fputwc(*s.add(i), f) == WEOF { return -1; }
10125        i += 1;
10126    }
10127    0
10128}
10129
10130#[no_mangle]
10131pub unsafe extern "C" fn ungetwc(c: wint_t, f: *mut FILE) -> wint_t {
10132    if c == WEOF { return WEOF; }
10133    let mut buf = [0u8; 4];
10134    let n = wcrtomb(buf.as_mut_ptr() as *mut c_char, c as wchar_t, core::ptr::null_mut());
10135    if n == !0usize || n == 0 { return WEOF; }
10136    let mut i = n;
10137    while i > 0 {
10138        i -= 1;
10139        if ungetc(buf[i] as c_int, f) == -1 { return WEOF; }
10140    }
10141    c
10142}
10143
10144#[no_mangle]
10145pub unsafe extern "C" fn getwchar() -> wint_t { fgetwc(stdin) }
10146
10147#[no_mangle]
10148pub unsafe extern "C" fn putwchar(c: wchar_t) -> wint_t { fputwc(c, stdout) }
10149
10150// ============================================================
10151// wchar: swprintf / vswprintf / fwprintf / vfwprintf
10152// ============================================================
10153
10154unsafe fn wfmt_write_str(dst: *mut wchar_t, pos: usize, cap: usize, s: *const u8, len: usize) -> usize {
10155    let mut i = 0;
10156    while i < len {
10157        if pos + i < cap { *dst.add(pos + i) = *s.add(i) as wchar_t; }
10158        i += 1;
10159    }
10160    pos + len
10161}
10162
10163#[no_mangle]
10164pub unsafe extern "C" fn vswprintf(s: *mut wchar_t, n: usize, fmt: *const wchar_t, mut args: VaList) -> c_int {
10165    if n == 0 { return -1; }
10166    let cap = n - 1;
10167    let mut pos = 0usize;
10168    // ponytail: format specifiers are ASCII; narrow buffer suffices for parsing
10169    let mut fmt_narrow = [0u8; 256];
10170    let mut flen = 0usize;
10171    loop {
10172        let ch = *fmt.add(flen) as u32;
10173        if ch == 0 || flen >= 255 { break; }
10174        fmt_narrow[flen] = if ch < 128 { ch as u8 } else { b'?' };
10175        flen += 1;
10176    }
10177    fmt_narrow[flen] = 0;
10178    let mut fi = 0usize;
10179    macro_rules! wc {
10180        ($c:expr) => { if pos < cap { *s.add(pos) = $c as wchar_t; } pos += 1; }
10181    }
10182    loop {
10183        let c = fmt_narrow[fi];
10184        if c == 0 { break; }
10185        if c != b'%' { wc!(c); fi += 1; continue; }
10186        fi += 1;
10187        let mut flags: u8 = 0;
10188        loop {
10189            match fmt_narrow[fi] {
10190                b'-' => { flags |= FLAG_MINUS; fi += 1; }
10191                b'+' => { flags |= FLAG_PLUS; fi += 1; }
10192                b' ' => { flags |= FLAG_SPACE; fi += 1; }
10193                b'0' => { flags |= FLAG_ZERO; fi += 1; }
10194                b'#' => { flags |= FLAG_HASH; fi += 1; }
10195                _ => break,
10196            }
10197        }
10198        let mut width: usize = 0;
10199        if fmt_narrow[fi] == b'*' {
10200            let w = args.next_arg::<c_int>();
10201            if w < 0 { flags |= FLAG_MINUS; width = (-w) as usize; } else { width = w as usize; }
10202            fi += 1;
10203        } else {
10204            while fmt_narrow[fi] >= b'0' && fmt_narrow[fi] <= b'9' {
10205                width = width * 10 + (fmt_narrow[fi] - b'0') as usize; fi += 1;
10206            }
10207        }
10208        let mut precision: i32 = -1;
10209        if fmt_narrow[fi] == b'.' {
10210            fi += 1;
10211            if fmt_narrow[fi] == b'*' {
10212                let p = args.next_arg::<c_int>();
10213                precision = if p < 0 { -1 } else { p }; fi += 1;
10214            } else {
10215                precision = 0;
10216                while fmt_narrow[fi] >= b'0' && fmt_narrow[fi] <= b'9' {
10217                    precision = precision * 10 + (fmt_narrow[fi] - b'0') as i32; fi += 1;
10218                }
10219            }
10220        }
10221        let len_mod = fmt_narrow[fi];
10222        if len_mod == b'h' || len_mod == b'l' || len_mod == b'j' || len_mod == b'z' || len_mod == b't' || len_mod == b'L' {
10223            fi += 1;
10224            let spec = fmt_narrow[fi];
10225            if (len_mod == b'h' && spec == b'h') || (len_mod == b'l' && spec == b'l') {
10226                fi += 1;
10227                let spec2 = fmt_narrow[fi];
10228                match (len_mod, spec, spec2) {
10229                    (b'h', b'h', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut u8) = pos as u8; } }
10230                    (b'l', b'l', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut c_longlong) = pos as c_longlong; } }
10231                    (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
10232                        let val = args.next_arg::<c_longlong>();
10233                        let neg = val < 0;
10234                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
10235                        let b = format_u64(abs);
10236                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10237                        let mut fbuf = [0u8; 32];
10238                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10239                        for k in 0..len { wc!(fbuf[k]); }
10240                    }
10241                    (b'l', b'l', b'u') => {
10242                        let val = args.next_arg::<c_ulonglong>();
10243                        let b = format_u64(val as u64);
10244                        let mut fbuf = [0u8; 32];
10245                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10246                        for k in 0..len { wc!(fbuf[k]); }
10247                    }
10248                    (b'l', b'l', b'x') => {
10249                        let val = args.next_arg::<c_ulonglong>();
10250                        let b = format_hex(val as u64, false);
10251                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10252                        let mut fbuf = [0u8; 32];
10253                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10254                        for k in 0..len { wc!(fbuf[k]); }
10255                    }
10256                    (b'l', b'l', b'X') => {
10257                        let val = args.next_arg::<c_ulonglong>();
10258                        let b = format_hex(val as u64, true);
10259                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10260                        let mut fbuf = [0u8; 32];
10261                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10262                        for k in 0..len { wc!(fbuf[k]); }
10263                    }
10264                    (b'l', b'l', b'o') => {
10265                        let val = args.next_arg::<c_ulonglong>();
10266                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
10267                        let mut fbuf = [0u8; 32];
10268                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10269                        for k in 0..len { wc!(fbuf[k]); }
10270                    }
10271                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); wc!(spec2); }
10272                }
10273            } else {
10274                let lm = if (len_mod == b'z' || len_mod == b't') && spec != b'n' { b'l' } else { len_mod };
10275                match (lm, spec) {
10276                    (b'h', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut u16) = pos as u16; } }
10277                    (b'l', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut c_long) = pos as c_long; } }
10278                    (b'z', b'n') | (b't', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut usize) = pos; } }
10279                    (b'j', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut c_ulonglong) = pos as c_ulonglong; } }
10280                    (b'l', b'd') | (b'l', b'i') => {
10281                        let val = args.next_arg::<c_long>();
10282                        let neg = val < 0;
10283                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
10284                        let b = format_u64(abs);
10285                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10286                        let mut fbuf = [0u8; 32];
10287                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10288                        for k in 0..len { wc!(fbuf[k]); }
10289                    }
10290                    (b'l', b'u') => {
10291                        let val = args.next_arg::<c_ulong>();
10292                        let b = format_u64(val as u64);
10293                        let mut fbuf = [0u8; 32];
10294                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10295                        for k in 0..len { wc!(fbuf[k]); }
10296                    }
10297                    (b'l', b'x') => {
10298                        let val = args.next_arg::<c_ulong>();
10299                        let b = format_hex(val as u64, false);
10300                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10301                        let mut fbuf = [0u8; 32];
10302                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10303                        for k in 0..len { wc!(fbuf[k]); }
10304                    }
10305                    (b'l', b'X') => {
10306                        let val = args.next_arg::<c_ulong>();
10307                        let b = format_hex(val as u64, true);
10308                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10309                        let mut fbuf = [0u8; 32];
10310                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10311                        for k in 0..len { wc!(fbuf[k]); }
10312                    }
10313                    (b'l', b'o') => {
10314                        let val = args.next_arg::<c_ulong>();
10315                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
10316                        let mut fbuf = [0u8; 32];
10317                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10318                        for k in 0..len { wc!(fbuf[k]); }
10319                    }
10320                    (b'l', b'c') => {
10321                        let ch = args.next_arg::<wint_t>();
10322                        wc!(ch);
10323                    }
10324                    (b'l', b's') => {
10325                        let ws_arg = args.next_arg::<*const wchar_t>();
10326                        if ws_arg.is_null() {
10327                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
10328                            if flags & FLAG_MINUS != 0 {
10329                                for k in 0..slen { wc!(b"(null)"[k]); }
10330                                for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10331                            } else {
10332                                for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10333                                for k in 0..slen { wc!(b"(null)"[k]); }
10334                            }
10335                        } else {
10336                            let mut wlen = 0usize;
10337                            loop {
10338                                let ch = *ws_arg.add(wlen);
10339                                if ch == 0 { break; }
10340                                if precision >= 0 && wlen >= precision as usize { break; }
10341                                wlen += 1;
10342                            }
10343                            if flags & FLAG_MINUS != 0 {
10344                                for k in 0..wlen { wc!(*ws_arg.add(k)); }
10345                                for _ in 0..width.saturating_sub(wlen) { wc!(b' '); }
10346                            } else {
10347                                for _ in 0..width.saturating_sub(wlen) { wc!(b' '); }
10348                                for k in 0..wlen { wc!(*ws_arg.add(k)); }
10349                            }
10350                        }
10351                    }
10352                    (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
10353                    | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
10354                        let val = args.next_arg::<f64>();
10355                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10356                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10357                        let mut fbuf = [0u8; 4224];
10358                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10359                        let mut wbuf = [0u8; 4224];
10360                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10361                        for k in 0..wlen { wc!(wbuf[k]); }
10362                    }
10363                    (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
10364                    | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
10365                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
10366                        let val = {
10367                            let lo: u64 = args.next_arg::<u64>();
10368                            let hi: u64 = args.next_arg::<u64>();
10369                            let combined: u128 = ((hi as u128) << 64) | (lo as u128);
10370                            f128::from_bits(combined) as f64
10371                        };
10372                        #[cfg(target_arch = "x86_64")]
10373                        let val = args.next_arg::<f64>();
10374                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10375                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10376                        let mut fbuf = [0u8; 4224];
10377                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10378                        let mut wbuf = [0u8; 4224];
10379                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10380                        for k in 0..wlen { wc!(wbuf[k]); }
10381                    }
10382                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); }
10383                }
10384            }
10385        } else {
10386            let spec = fmt_narrow[fi];
10387            match spec {
10388                b'd' | b'i' => {
10389                    let d = args.next_arg::<c_int>();
10390                    let neg = d < 0;
10391                    let abs = if neg { d.wrapping_neg() as u64 } else { d as u64 };
10392                    let b = format_u64(abs);
10393                    let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10394                    let mut fbuf = [0u8; 32];
10395                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10396                    for k in 0..len { wc!(fbuf[k]); }
10397                }
10398                b'u' => {
10399                    let u = args.next_arg::<c_uint>();
10400                    let b = format_u64(u as u64);
10401                    let mut fbuf = [0u8; 32];
10402                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10403                    for k in 0..len { wc!(fbuf[k]); }
10404                }
10405                b'x' => {
10406                    let x = args.next_arg::<c_uint>();
10407                    let b = format_hex(x as u64, false);
10408                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10409                    let mut fbuf = [0u8; 32];
10410                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10411                    for k in 0..len { wc!(fbuf[k]); }
10412                }
10413                b'X' => {
10414                    let x = args.next_arg::<c_uint>();
10415                    let b = format_hex(x as u64, true);
10416                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10417                    let mut fbuf = [0u8; 32];
10418                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10419                    for k in 0..len { wc!(fbuf[k]); }
10420                }
10421                b'o' => {
10422                    let o = args.next_arg::<c_uint>();
10423                    let b = format_octal(o as u64, flags & FLAG_HASH != 0);
10424                    let mut fbuf = [0u8; 32];
10425                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10426                    for k in 0..len { wc!(fbuf[k]); }
10427                }
10428                b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
10429                    let val = args.next_arg::<f64>();
10430                    let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10431                    let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10432                    let mut fbuf = [0u8; 4224];
10433                    let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10434                    let mut wbuf = [0u8; 4224];
10435                    let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10436                    for k in 0..wlen { wc!(wbuf[k]); }
10437                }
10438                b'c' => {
10439                    let ch = args.next_arg::<c_int>();
10440                    wc!(ch as u8);
10441                }
10442                b's' => {
10443                    let p = args.next_arg::<*const c_char>();
10444                    if p.is_null() {
10445                        let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
10446                        if flags & FLAG_MINUS != 0 {
10447                            for k in 0..slen { wc!(b"(null)"[k]); }
10448                            for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10449                        } else {
10450                            for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10451                            for k in 0..slen { wc!(b"(null)"[k]); }
10452                        }
10453                    } else {
10454                        let mut wbuf_local = [0i32; 256];
10455                        let mut wcount = 0usize;
10456                        let mut byte_pos = 0usize;
10457                        let pbytes = p as *const u8;
10458                        loop {
10459                            if precision >= 0 && wcount >= precision as usize { break; }
10460                            if wcount >= 256 { break; }
10461                            let mut wc_val: c_int = 0;
10462                            let consumed = mbrtowc(&mut wc_val as *mut c_int, p.add(byte_pos) as *const c_char, 256, core::ptr::null_mut());
10463                            if consumed == !0usize || consumed == !1usize {
10464                                wbuf_local[wcount] = *pbytes.add(byte_pos) as c_int;
10465                                byte_pos += 1;
10466                                wcount += 1;
10467                            } else if consumed == 0 {
10468                                break;
10469                            } else {
10470                                wbuf_local[wcount] = wc_val;
10471                                byte_pos += consumed;
10472                                wcount += 1;
10473                            }
10474                        }
10475                        if flags & FLAG_MINUS != 0 {
10476                            for k in 0..wcount { wc!(wbuf_local[k]); }
10477                            for _ in 0..width.saturating_sub(wcount) { wc!(b' '); }
10478                        } else {
10479                            for _ in 0..width.saturating_sub(wcount) { wc!(b' '); }
10480                            for k in 0..wcount { wc!(wbuf_local[k]); }
10481                        }
10482                    }
10483                }
10484                b'p' => {
10485                    wc!(b'0'); wc!(b'x');
10486                    let p = args.next_arg::<*const c_void>();
10487                    let b = format_hex(p as u64, false);
10488                    for k in 0..b.1 { wc!(b.0[k]); }
10489                }
10490                b'n' => {
10491                    let p = args.next_arg::<*mut c_void>();
10492                    if !p.is_null() { *(p as *mut c_int) = pos as c_int; }
10493                }
10494                b'%' => { wc!(b'%'); }
10495                _ => { wc!(b'%'); wc!(spec); }
10496            }
10497        }
10498        fi += 1;
10499    }
10500    let null_pos = if pos < cap { pos } else { cap };
10501    *s.add(null_pos) = 0;
10502    if pos > cap { -1 } else { pos as c_int }
10503}
10504
10505#[no_mangle]
10506pub unsafe extern "C" fn swprintf(s: *mut wchar_t, n: usize, fmt: *const wchar_t, args: ...) -> c_int {
10507    vswprintf(s, n, fmt, args)
10508}
10509
10510#[no_mangle]
10511pub unsafe extern "C" fn vfwprintf(f: *mut FILE, fmt: *const wchar_t, args: VaList) -> c_int {
10512    let mut buf = [0i32; 4096];
10513    let r = vswprintf(buf.as_mut_ptr(), 4096, fmt, args);
10514    if r < 0 { return r; }
10515    let mut i = 0;
10516    while i < r as usize {
10517        let mut mb = [0u8; 4];
10518        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, buf[i], core::ptr::null_mut());
10519        if n == !0usize { return -1; }
10520        if fwrite(mb.as_ptr() as *const c_void, 1, n, f) != n { return -1; }
10521        i += 1;
10522    }
10523    r
10524}
10525
10526#[no_mangle]
10527pub unsafe extern "C" fn fwprintf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int {
10528    vfwprintf(f, fmt, args)
10529}
10530
10531// ============================================================
10532// wchar: vswscanf / swscanf / vfwscanf / fwscanf / vwscanf / wscanf
10533// ============================================================
10534
10535// Convert wchar_t format to byte format (ASCII cast, format specifiers are ASCII)
10536unsafe fn wcsfmt_to_mbs(dst: *mut u8, dst_len: usize, src: *const wchar_t) {
10537    let mut i = 0usize;
10538    loop {
10539        let ch = *src.add(i) as u32;
10540        if ch == 0 || i >= dst_len - 1 { break; }
10541        *dst.add(i) = if ch < 128 { ch as u8 } else { b'?' };
10542        i += 1;
10543    }
10544    *dst.add(i) = 0;
10545}
10546
10547#[no_mangle]
10548pub unsafe extern "C" fn vswscanf(s: *const wchar_t, fmt: *const wchar_t, mut args: VaList) -> c_int {
10549    let mut mbs_buf = [0u8; 4096];
10550    let mut i = 0usize;
10551    let mut mb_pos = 0usize;
10552    loop {
10553        let wc = *s.add(i) as c_int;
10554        if wc == 0 { break; }
10555        let mut mb = [0u8; 4];
10556        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, wc, core::ptr::null_mut());
10557        if n == !0usize || n == 0 { break; }
10558        if mb_pos + n >= mbs_buf.len() { break; }
10559        let mut k = 0usize;
10560        while k < n { mbs_buf[mb_pos + k] = mb[k]; k += 1; }
10561        mb_pos += n;
10562        i += 1;
10563    }
10564    mbs_buf[mb_pos] = 0;
10565    let mut mbs_fmt = [0u8; 4096];
10566    wcsfmt_to_mbs(mbs_fmt.as_mut_ptr(), mbs_fmt.len(), fmt);
10567    do_vsscanf(mbs_buf.as_ptr(), mb_pos, mbs_fmt.as_ptr() as *const c_char, &mut args, core::ptr::null_mut())
10568}
10569
10570#[no_mangle]
10571pub unsafe extern "C" fn swscanf(s: *const wchar_t, fmt: *const wchar_t, args: ...) -> c_int {
10572    vswscanf(s, fmt, args)
10573}
10574
10575#[no_mangle]
10576pub unsafe extern "C" fn vfwscanf(f: *mut FILE, fmt: *const wchar_t, mut args: VaList) -> c_int {
10577    let start_pos = ftello(f);
10578    if start_pos < 0 { return -1; }
10579    let mut buf = [0u8; 4096];
10580    let mut n = 0usize;
10581    loop {
10582        if n >= buf.len() - 1 { break; }
10583        let c = fgetc(f);
10584        if c == -1 { break; }
10585        buf[n] = c as u8;
10586        n += 1;
10587    }
10588    buf[n] = 0;
10589    let mut mbs_fmt = [0u8; 4096];
10590    wcsfmt_to_mbs(mbs_fmt.as_mut_ptr(), mbs_fmt.len(), fmt);
10591    let mut consumed = 0usize;
10592    let hit_eof = (*f)._eof != 0;
10593    let result = do_vsscanf(buf.as_ptr(), n, mbs_fmt.as_ptr() as *const c_char, &mut args, &mut consumed);
10594    let _ = fseeko(f, start_pos + consumed as i64, SEEK_SET);
10595    if hit_eof && consumed == n {
10596        (*f)._eof = 1;
10597    }
10598    result
10599}
10600
10601#[no_mangle]
10602pub unsafe extern "C" fn fwscanf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int {
10603    vfwscanf(f, fmt, args)
10604}
10605
10606#[no_mangle]
10607pub unsafe extern "C" fn vwscanf(fmt: *const wchar_t, args: VaList) -> c_int {
10608    vfwscanf(stdin, fmt, args)
10609}
10610
10611#[no_mangle]
10612pub unsafe extern "C" fn wscanf(fmt: *const wchar_t, args: ...) -> c_int {
10613    vfwscanf(stdin, fmt, args)
10614}
10615
10616// ============================================================
10617// Time: internal helpers
10618// ============================================================
10619
10620const LEAPOCH: i64 = 946684800 + 86400 * (31 + 29);
10621const DAYS_PER_400Y: i64 = 365 * 400 + 97;
10622const DAYS_PER_100Y: i64 = 365 * 100 + 24;
10623const DAYS_PER_4Y: i64 = 365 * 4 + 1;
10624
10625const SECS_THROUGH_MONTH: [i32; 12] = [
10626    0, 31*86400, 59*86400, 90*86400, 120*86400, 151*86400,
10627    181*86400, 212*86400, 243*86400, 273*86400, 304*86400, 334*86400,
10628];
10629
10630const DAYS_IN_MONTH: [i32; 12] = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29];
10631
10632unsafe fn year_to_secs(year: i64, is_leap: &mut bool) -> i64 {
10633    // musl compares (year-2) as unsigned: the small-year fast path is only
10634    // valid for 1902..2038.  A signed comparison miscomputes negative years.
10635    if (year.wrapping_sub(2) as u64) <= 136 {
10636        let y = year as i32;
10637        let mut leaps = (y - 68) >> 2;
10638        if (y - 68) & 3 == 0 { leaps -= 1; *is_leap = true; } else { *is_leap = false; }
10639        return 31536000 * (y as i64 - 70) + 86400 * leaps as i64;
10640    }
10641    let mut cycles = ((year - 100) / 400) as i32;
10642    let mut rem = ((year - 100) % 400) as i32;
10643    if rem < 0 { cycles -= 1; rem += 400; }
10644    let (centuries, leaps);
10645    if rem == 0 { *is_leap = true; centuries = 0; leaps = 0; }
10646    else {
10647        let c;
10648        if rem >= 200 { if rem >= 300 { c = 3; rem -= 300; } else { c = 2; rem -= 200; } }
10649        else { if rem >= 100 { c = 1; rem -= 100; } else { c = 0; } }
10650        centuries = c;
10651        if rem == 0 { *is_leap = false; leaps = 0; }
10652        else { leaps = rem / 4; rem %= 4; *is_leap = rem == 0; }
10653    }
10654    let total_leaps = leaps + 97 * cycles + 24 * centuries - (*is_leap as i32);
10655    (year - 100) * 31536000 + total_leaps as i64 * 86400 + 946684800 + 86400
10656}
10657
10658fn month_to_secs(month: i32, is_leap: bool) -> i32 {
10659    let mut t = SECS_THROUGH_MONTH[month as usize];
10660    if is_leap && month >= 2 { t += 86400; }
10661    t
10662}
10663
10664unsafe fn secs_to_tm(t: i64, tm: &mut tm) -> bool {
10665    if t < (i32::MIN as i64) * 31622400 || t > (i32::MAX as i64) * 31622400 { return false; }
10666    let secs = t - LEAPOCH;
10667    let mut days = secs / 86400;
10668    let mut remsecs = (secs % 86400) as i32;
10669    if remsecs < 0 { remsecs += 86400; days -= 1; }
10670    let mut wday = ((3 + days) % 7) as i32;
10671    if wday < 0 { wday += 7; }
10672    let mut qc_cycles = (days / DAYS_PER_400Y) as i32;
10673    let mut remdays = (days % DAYS_PER_400Y) as i32;
10674    if remdays < 0 { remdays += DAYS_PER_400Y as i32; qc_cycles -= 1; }
10675    let mut c_cycles = remdays / DAYS_PER_100Y as i32;
10676    if c_cycles == 4 { c_cycles -= 1; }
10677    remdays -= c_cycles * DAYS_PER_100Y as i32;
10678    let mut q_cycles = remdays / DAYS_PER_4Y as i32;
10679    if q_cycles == 25 { q_cycles -= 1; }
10680    remdays -= q_cycles * DAYS_PER_4Y as i32;
10681    let mut remyears = remdays / 365;
10682    if remyears == 4 { remyears -= 1; }
10683    remdays -= remyears * 365;
10684    let leap = remyears == 0 && (q_cycles != 0 || c_cycles == 0);
10685    let mut yday = remdays + 31 + 28 + leap as i32;
10686    if yday >= 365 + leap as i32 { yday -= 365 + leap as i32; }
10687    let years = remyears as i64 + 4 * q_cycles as i64 + 100 * c_cycles as i64 + 400 * qc_cycles as i64;
10688    let mut months = 0i32;
10689    let mut rd = remdays;
10690    for m in 0..12 {
10691        if DAYS_IN_MONTH[m] <= rd { rd -= DAYS_IN_MONTH[m]; } else { months = m as i32; break; }
10692    }
10693    let mut adj_years = years;
10694    if months >= 10 { months -= 12; adj_years += 1; }
10695    if adj_years + 100 > i32::MAX as i64 || adj_years + 100 < i32::MIN as i64 { return false; }
10696    tm.tm_year = (adj_years + 100) as c_int;
10697    tm.tm_mon = months + 2;
10698    tm.tm_mday = rd + 1;
10699    tm.tm_wday = wday;
10700    tm.tm_yday = yday;
10701    tm.tm_hour = remsecs / 3600;
10702    tm.tm_min = remsecs / 60 % 60;
10703    tm.tm_sec = remsecs % 60;
10704    true
10705}
10706
10707unsafe fn tm_to_secs(tm: *const tm) -> i64 {
10708    let mut year = (*tm).tm_year as i64;
10709    let mut month = (*tm).tm_mon;
10710    if month >= 12 || month < 0 {
10711        let adj = month / 12;
10712        month %= 12;
10713        if month < 0 { month += 12; }
10714        year += adj as i64;
10715    }
10716    let mut is_leap = false;
10717    let mut t = year_to_secs(year, &mut is_leap);
10718    t += month_to_secs(month, is_leap) as i64;
10719    t += 86400 * ((*tm).tm_mday - 1) as i64;
10720    t += 3600 * (*tm).tm_hour as i64;
10721    t += 60 * (*tm).tm_min as i64;
10722    t += (*tm).tm_sec as i64;
10723    t
10724}
10725
10726static mut TM_BUF: tm = tm {
10727    tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0,
10728    tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0,
10729    tm_gmtoff: 0, tm_zone: core::ptr::null(),
10730};
10731
10732static mut UTC_STR: [c_char; 4] = [b'U' as c_char, b'T' as c_char, b'C' as c_char, 0];
10733
10734const CLOCK_PROCESS_CPUTIME_ID: c_int = 2;
10735
10736// ============================================================
10737// Time: core functions
10738// ============================================================
10739
10740#[no_mangle]
10741pub unsafe extern "C" fn time(t: *mut TimeT) -> TimeT {
10742    let mut ts: timespec = core::mem::zeroed();
10743    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
10744    if !t.is_null() { *t = ts.tv_sec; }
10745    ts.tv_sec
10746}
10747
10748#[no_mangle]
10749pub unsafe extern "C" fn difftime(t1: TimeT, t0: TimeT) -> f64 {
10750    (t1 as i64 - t0 as i64) as f64
10751}
10752
10753#[no_mangle]
10754pub unsafe extern "C" fn clock() -> ClockT {
10755    let mut ts: timespec = core::mem::zeroed();
10756    let _ = sys_clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut ts);
10757    ts.tv_sec * 1000000 + ts.tv_nsec / 1000
10758}
10759
10760#[no_mangle]
10761pub unsafe extern "C" fn gmtime(t: *const TimeT) -> *mut tm {
10762    gmtime_r(t, &raw mut TM_BUF)
10763}
10764
10765#[no_mangle]
10766pub unsafe extern "C" fn gmtime_r(t: *const TimeT, tm: *mut tm) -> *mut tm {
10767    if !secs_to_tm(*t as i64, &mut *tm) { ERRNO!() = EOVERFLOW; return core::ptr::null_mut(); }
10768    (*tm).tm_isdst = 0;
10769    (*tm).tm_gmtoff = 0;
10770    (*tm).tm_zone = core::ptr::addr_of!(UTC_STR).cast::<c_char>();
10771    tm
10772}
10773
10774#[no_mangle]
10775pub unsafe extern "C" fn localtime(t: *const TimeT) -> *mut tm {
10776    tz_localtime_r(t, &raw mut TM_BUF)
10777}
10778
10779#[no_mangle]
10780pub unsafe extern "C" fn localtime_r(t: *const TimeT, tm: *mut tm) -> *mut tm {
10781    tz_localtime_r(t, tm)
10782}
10783
10784#[no_mangle]
10785pub unsafe extern "C" fn mktime(tm: *mut tm) -> TimeT {
10786    tz_mktime(tm)
10787}
10788
10789#[no_mangle]
10790pub unsafe extern "C" fn timegm(tm: *mut tm) -> TimeT {
10791    let t = tm_to_secs(tm as *const tm);
10792    if !secs_to_tm(t, &mut *tm) { ERRNO!() = EOVERFLOW; return -1; }
10793    (*tm).tm_isdst = 0;
10794    (*tm).tm_gmtoff = 0;
10795    (*tm).tm_zone = core::ptr::addr_of!(UTC_STR).cast::<c_char>();
10796    t as TimeT
10797}
10798
10799static mut ASCTIME_BUF: [c_char; 26] = [0; 26];
10800
10801const DAY_NAMES: [&[u8]; 7] = [b"Sun\0", b"Mon\0", b"Tue\0", b"Wed\0", b"Thu\0", b"Fri\0", b"Sat\0"];
10802const MON_NAMES: [&[u8]; 12] = [b"Jan\0", b"Feb\0", b"Mar\0", b"Apr\0", b"May\0", b"Jun\0", b"Jul\0", b"Aug\0", b"Sep\0", b"Oct\0", b"Nov\0", b"Dec\0"];
10803
10804#[no_mangle]
10805pub unsafe extern "C" fn asctime(tm: *const tm) -> *mut c_char {
10806    asctime_r(tm, core::ptr::addr_of_mut!(ASCTIME_BUF).cast::<c_char>())
10807}
10808
10809#[no_mangle]
10810pub unsafe extern "C" fn asctime_r(tm: *const tm, buf: *mut c_char) -> *mut c_char {
10811    let wday = if (*tm).tm_wday >= 0 && (*tm).tm_wday < 7 { (*tm).tm_wday as usize } else { 0 };
10812    let mon = if (*tm).tm_mon >= 0 && (*tm).tm_mon < 12 { (*tm).tm_mon as usize } else { 0 };
10813    let dn = DAY_NAMES[wday];
10814    let mn = MON_NAMES[mon];
10815    let mut p = 0;
10816    for k in 0..3 { *buf.add(p) = *dn.as_ptr().add(k) as c_char; p += 1; }
10817    *buf.add(p) = b' ' as c_char; p += 1;
10818    for k in 0..3 { *buf.add(p) = *mn.as_ptr().add(k) as c_char; p += 1; }
10819    *buf.add(p) = b' ' as c_char; p += 1;
10820    // %.3s %.3s%3d: the day is right-aligned in a three-column field.
10821    let v = (*tm).tm_mday;
10822    if v < 10 {
10823        *buf.add(p) = b' ' as c_char; p += 1;
10824        *buf.add(p) = b' ' as c_char; p += 1;
10825        *buf.add(p) = (b'0' + v as u8) as c_char; p += 1;
10826    } else if v < 100 {
10827        *buf.add(p) = b' ' as c_char; p += 1;
10828        *buf.add(p) = (b'0' + (v / 10) as u8) as c_char; p += 1;
10829        *buf.add(p) = (b'0' + (v % 10) as u8) as c_char; p += 1;
10830    } else {
10831        *buf.add(p) = (b'0' + (v / 100) as u8) as c_char; p += 1;
10832        *buf.add(p) = (b'0' + ((v / 10) % 10) as u8) as c_char; p += 1;
10833        *buf.add(p) = (b'0' + (v % 10) as u8) as c_char; p += 1;
10834    }
10835    *buf.add(p) = b' ' as c_char; p += 1;
10836    let hh = (*tm).tm_hour;
10837    *buf.add(p) = (b'0' + (hh / 10) as u8) as c_char; p += 1;
10838    *buf.add(p) = (b'0' + (hh % 10) as u8) as c_char; p += 1;
10839    *buf.add(p) = b':' as c_char; p += 1;
10840    let mm = (*tm).tm_min;
10841    *buf.add(p) = (b'0' + (mm / 10) as u8) as c_char; p += 1;
10842    *buf.add(p) = (b'0' + (mm % 10) as u8) as c_char; p += 1;
10843    *buf.add(p) = b':' as c_char; p += 1;
10844    let ss = (*tm).tm_sec;
10845    *buf.add(p) = (b'0' + (ss / 10) as u8) as c_char; p += 1;
10846    *buf.add(p) = (b'0' + (ss % 10) as u8) as c_char; p += 1;
10847    *buf.add(p) = b' ' as c_char; p += 1;
10848    // %d: negative and >4-digit years are valid in musl asctime.
10849    let yr = (*tm).tm_year as i64 + 1900;
10850    let mut tmp = [0u8; 16];
10851    let mut n = 0usize;
10852    let mut v2 = if yr < 0 { -yr } else { yr };
10853    if v2 == 0 {
10854        tmp[n] = b'0';
10855        n += 1;
10856    } else {
10857        while v2 > 0 && n < tmp.len() {
10858            tmp[n] = b'0' + (v2 % 10) as u8;
10859            v2 /= 10;
10860            n += 1;
10861        }
10862    }
10863    if yr < 0 {
10864        *buf.add(p) = b'-' as c_char;
10865        p += 1;
10866    }
10867    for k in (0..n).rev() {
10868        *buf.add(p) = tmp[k] as c_char;
10869        p += 1;
10870    }
10871    *buf.add(p) = b'\n' as c_char; p += 1;
10872    *buf.add(p) = 0;
10873    buf
10874}
10875
10876#[no_mangle]
10877pub unsafe extern "C" fn ctime(t: *const TimeT) -> *mut c_char {
10878    let tm = localtime(t);
10879    if tm.is_null() { core::ptr::null_mut() } else { asctime(tm) }
10880}
10881
10882#[no_mangle]
10883pub unsafe extern "C" fn ctime_r(t: *const TimeT, buf: *mut c_char) -> *mut c_char {
10884    let mut tmp: tm = core::mem::zeroed();
10885    if localtime_r(t, &mut tmp).is_null() { core::ptr::null_mut() } else { asctime_r(&tmp, buf) }
10886}
10887
10888// ============================================================
10889// Time: clock_getres / clock_settime / clock_nanosleep / gettimeofday
10890// ============================================================
10891
10892unsafe fn sys_clock_getres(clockid: c_int, ts: *mut timespec) -> i64 {
10893    <Arch as Syscalls>::syscall2(SYS_CLOCK_GETRES, clockid as i64, ts as i64)
10894}
10895
10896unsafe fn sys_clock_settime(clockid: c_int, ts: *const timespec) -> i64 {
10897    <Arch as Syscalls>::syscall2(SYS_CLOCK_SETTIME, clockid as i64, ts as i64)
10898}
10899
10900unsafe fn sys_clock_nanosleep(clockid: c_int, flags: c_int, req: *const timespec, rem: *mut timespec) -> i64 {
10901    <Arch as Syscalls>::syscall4(SYS_CLOCK_NANOSLEEP, clockid as i64, flags as i64, req as i64, rem as i64)
10902}
10903
10904#[no_mangle]
10905pub unsafe extern "C" fn clock_getres(clockid: c_int, ts: *mut timespec) -> c_int {
10906    let r = sys_clock_getres(clockid, ts);
10907    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
10908}
10909
10910#[no_mangle]
10911pub unsafe extern "C" fn clock_settime(clockid: c_int, ts: *const timespec) -> c_int {
10912    let r = sys_clock_settime(clockid, ts);
10913    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
10914}
10915
10916#[no_mangle]
10917pub unsafe extern "C" fn clock_nanosleep(clockid: c_int, flags: c_int, req: *const timespec, rem: *mut timespec) -> c_int {
10918    let r = sys_clock_nanosleep(clockid, flags, req, rem);
10919    if r < 0 {
10920        let e = (-r) as c_int;
10921        // The kernel returns EOPNOTSUPP for CLOCK_THREAD_CPUTIME_ID;
10922        // POSIX/musl report EINVAL instead.
10923        if clockid == 3 && e == 95 { return 22; }
10924        e
10925    } else {
10926        0
10927    }
10928}
10929
10930#[no_mangle]
10931pub unsafe extern "C" fn gettimeofday(tv: *mut timeval, _tz: *mut c_void) -> c_int {
10932    if tv.is_null() { return 0; }
10933    let mut ts: timespec = core::mem::zeroed();
10934    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
10935    (*tv).tv_sec = ts.tv_sec;
10936    (*tv).tv_usec = ts.tv_nsec / 1000;
10937    0
10938}
10939
10940// ============================================================
10941// Time: strftime
10942// ============================================================
10943
10944fn is_leap_year(y: i32) -> bool {
10945    let yr = if y > i32::MAX - 1900 { y - 2000 } else { y + 1900 };
10946    yr % 4 == 0 && (yr % 100 != 0 || yr % 400 == 0)
10947}
10948
10949fn week_num(tm: &tm) -> i32 {
10950    let mut val = (tm.tm_yday + 7 - ((tm.tm_wday + 6) % 7)) / 7;
10951    if (tm.tm_wday + 371 - tm.tm_yday - 2).rem_euclid(7) <= 2 { val += 1; }
10952    if val == 0 {
10953        val = 52;
10954        let dec31 = (tm.tm_wday + 7 - tm.tm_yday - 1).rem_euclid(7);
10955        if dec31 == 4 || (dec31 == 5 && is_leap_year(tm.tm_year % 400 - 1)) { val += 1; }
10956    } else if val == 53 {
10957        let jan1 = (tm.tm_wday + 371 - tm.tm_yday).rem_euclid(7);
10958        if jan1 != 4 && (jan1 != 3 || !is_leap_year(tm.tm_year)) { val = 1; }
10959    }
10960    val
10961}
10962
10963// Langinfo constants for strftime
10964const ABDAY_1: c_int = 0x20000;
10965const DAY_1: c_int = 0x20007;
10966const ABMON_1: c_int = 0x2000E;
10967const MON_1: c_int = 0x2001A;
10968const AM_STR_LI: c_int = 0x20026;
10969const PM_STR_LI: c_int = 0x20027;
10970const D_T_FMT: c_int = 0x20028;
10971const D_FMT: c_int = 0x20029;
10972const T_FMT: c_int = 0x2002A;
10973const T_FMT_AMPM: c_int = 0x2002B;
10974
10975// Format an i64 into buf as decimal with zero/sign padding. Returns (ptr_to_start, length).
10976// pad: '-' = no pad, '_' = space pad, '0' or 0 = zero pad. width: minimum digits (excluding sign).
10977unsafe fn num_fmt(buf: &mut [u8; 100], val: i64, pad: u8, width: usize) -> (*const u8, usize) {
10978    let negative = val < 0;
10979    let mut v = if negative { -val as u64 } else { val as u64 };
10980    let mut tmp = [0u8; 24];
10981    let mut pos = 24usize;
10982    if v == 0 { pos -= 1; tmp[pos] = b'0'; }
10983    while v > 0 { pos -= 1; tmp[pos] = b'0' + (v % 10) as u8; v /= 10; }
10984    let digits = 24 - pos;
10985    let sign_chars = if negative { 1 } else { 0 };
10986    let needed = sign_chars + digits;
10987    let fill = if width > needed { width - needed } else { 0 };
10988    let total = fill + needed;
10989    let mut p = 0usize;
10990    match pad {
10991        b'-' => { /* no fill */ }
10992        b'_' => {
10993            for _ in 0..fill { buf[p] = b' '; p += 1; }
10994            if negative { buf[p] = b'-'; p += 1; }
10995        }
10996        _ => {
10997            if negative { buf[p] = b'-'; p += 1; }
10998            for _ in 0..fill { buf[p] = b'0'; p += 1; }
10999        }
11000    }
11001    for i in 0..digits { buf[p] = tmp[pos + i]; p += 1; }
11002    (buf.as_ptr(), total)
11003}
11004
11005// Copy a null-terminated C string into buf. Returns (ptr, len).
11006unsafe fn str_to_buf(buf: &mut [u8; 100], s: *const c_char) -> (*const u8, usize) {
11007    let mut k = 0usize;
11008    while *s.add(k) != 0 {
11009        buf[k] = *s.add(k) as u8;
11010        k += 1;
11011    }
11012    (buf.as_ptr(), k)
11013}
11014
11015// Core format dispatcher. Returns (ptr, len) where ptr points into buf or a static string.
11016// pad=0 means use default; returns (null, 0) for unknown specifiers.
11017unsafe fn __strftime_fmt_1(buf: &mut [u8; 100], f: u8, tm: *const tm, pad: u8) -> (*const u8, usize) {
11018    let mut val: i64;
11019    let mut width: usize = 2;
11020    let mut def_pad: u8 = b'0';
11021    let fmt: *const c_char;
11022
11023    match f {
11024        b'a' => {
11025            if (*tm).tm_wday as u32 > 6 { return (b"\0".as_ptr(), 0); }
11026            let p = nl_langinfo(ABDAY_1 + (*tm).tm_wday);
11027            return str_to_buf(buf, p);
11028        }
11029        b'A' => {
11030            if (*tm).tm_wday as u32 > 6 { return (b"\0".as_ptr(), 0); }
11031            let p = nl_langinfo(DAY_1 + (*tm).tm_wday);
11032            return str_to_buf(buf, p);
11033        }
11034        b'h' | b'b' => {
11035            if (*tm).tm_mon as u32 > 11 { return (b"\0".as_ptr(), 0); }
11036            let p = nl_langinfo(ABMON_1 + (*tm).tm_mon);
11037            return str_to_buf(buf, p);
11038        }
11039        b'B' => {
11040            if (*tm).tm_mon as u32 > 11 { return (b"\0".as_ptr(), 0); }
11041            let p = nl_langinfo(MON_1 + (*tm).tm_mon);
11042            return str_to_buf(buf, p);
11043        }
11044        b'c' => {
11045            let p = nl_langinfo(D_T_FMT);
11046            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11047            return (buf.as_ptr(), l);
11048        }
11049        b'C' => {
11050            val = (1900i64 + (*tm).tm_year as i64) / 100;
11051            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11052        }
11053        b'e' => { def_pad = b'_'; }
11054        b'd' => {
11055            val = (*tm).tm_mday as i64;
11056            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11057        }
11058        b'D' => {
11059            fmt = b"%m/%d/%y\0".as_ptr() as *const c_char;
11060            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11061            return (buf.as_ptr(), l);
11062        }
11063        b'F' => {
11064            fmt = b"%Y-%m-%d\0".as_ptr() as *const c_char;
11065            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11066            return (buf.as_ptr(), l);
11067        }
11068        b'g' | b'G' => {
11069            val = (*tm).tm_year as i64 + 1900;
11070            if (*tm).tm_yday < 3 && week_num(&*tm) != 1 { val -= 1; }
11071            else if (*tm).tm_yday > 360 && week_num(&*tm) == 1 { val += 1; }
11072            if f == b'g' { val %= 100; }
11073            else { width = 4; }
11074            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11075        }
11076        b'H' => {
11077            val = (*tm).tm_hour as i64;
11078            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11079        }
11080        b'I' => {
11081            val = (*tm).tm_hour as i64;
11082            if val == 0 { val = 12; }
11083            else if val > 12 { val -= 12; }
11084            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11085        }
11086        b'j' => {
11087            val = (*tm).tm_yday as i64 + 1;
11088            width = 3;
11089            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11090        }
11091        b'm' => {
11092            val = (*tm).tm_mon as i64 + 1;
11093            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11094        }
11095        b'M' => {
11096            val = (*tm).tm_min as i64;
11097            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11098        }
11099        b'n' => { buf[0] = b'\n'; return (buf.as_ptr(), 1); }
11100        b'p' => {
11101            let p = if (*tm).tm_hour >= 12 { nl_langinfo(PM_STR_LI) } else { nl_langinfo(AM_STR_LI) };
11102            return str_to_buf(buf, p);
11103        }
11104        b'r' => {
11105            let p = nl_langinfo(T_FMT_AMPM);
11106            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11107            return (buf.as_ptr(), l);
11108        }
11109        b'R' => {
11110            fmt = b"%H:%M\0".as_ptr() as *const c_char;
11111            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11112            return (buf.as_ptr(), l);
11113        }
11114        b's' => {
11115            val = tm_to_secs(tm) - (*tm).tm_gmtoff as i64;
11116            width = 1;
11117            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11118        }
11119        b'S' => {
11120            val = (*tm).tm_sec as i64;
11121            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11122        }
11123        b't' => { buf[0] = b'\t'; return (buf.as_ptr(), 1); }
11124        b'T' => {
11125            fmt = b"%H:%M:%S\0".as_ptr() as *const c_char;
11126            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11127            return (buf.as_ptr(), l);
11128        }
11129        b'u' => {
11130            val = if (*tm).tm_wday != 0 { (*tm).tm_wday as i64 } else { 7 };
11131            width = 1;
11132            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11133        }
11134        b'U' => {
11135            val = ((*tm).tm_yday as u64 + 7 - (*tm).tm_wday as u64) as i64 / 7;
11136            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11137        }
11138        b'W' => {
11139            val = ((*tm).tm_yday as u64 + 7 - ((*tm).tm_wday as u64 + 6) % 7) as i64 / 7;
11140            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11141        }
11142        b'V' => {
11143            val = week_num(&*tm) as i64;
11144            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11145        }
11146        b'w' => {
11147            val = (*tm).tm_wday as i64;
11148            width = 1;
11149            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11150        }
11151        b'x' => {
11152            let p = nl_langinfo(D_FMT);
11153            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11154            return (buf.as_ptr(), l);
11155        }
11156        b'X' => {
11157            let p = nl_langinfo(T_FMT);
11158            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11159            return (buf.as_ptr(), l);
11160        }
11161        b'y' => {
11162            val = (1900i64 + (*tm).tm_year as i64) % 100;
11163            if val < 0 { val = -val; }
11164            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11165        }
11166        b'Y' => {
11167            val = (*tm).tm_year as i64 + 1900;
11168            if val >= 10000 {
11169                let mut tmp = [0u8; 100];
11170                let (_, k) = num_fmt(&mut tmp, val, b'-', 1);
11171                buf[0] = b'+';
11172                for i in 0..k { buf[1 + i] = tmp[i]; }
11173                return (buf.as_ptr(), 1 + k);
11174            }
11175            width = 4;
11176            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11177        }
11178        b'z' => {
11179            if (*tm).tm_isdst < 0 { return (b"\0".as_ptr(), 0); }
11180            let gmtoff = (*tm).tm_gmtoff as i64;
11181            let sign = if gmtoff >= 0 { b'+' } else { b'-' };
11182            let off = if gmtoff < 0 { -gmtoff } else { gmtoff };
11183            let hh = (off / 3600) as i32;
11184            let mm = ((off % 3600) / 60) as i32;
11185            buf[0] = sign;
11186            buf[1] = b'0' + (hh / 10) as u8;
11187            buf[2] = b'0' + (hh % 10) as u8;
11188            buf[3] = b'0' + (mm / 10) as u8;
11189            buf[4] = b'0' + (mm % 10) as u8;
11190            return (buf.as_ptr(), 5);
11191        }
11192        b'Z' => {
11193            if (*tm).tm_isdst < 0 || (*tm).tm_zone.is_null() { return (b"\0".as_ptr(), 0); }
11194            return str_to_buf(buf, (*tm).tm_zone);
11195        }
11196        b'%' => { buf[0] = b'%'; return (buf.as_ptr(), 1); }
11197        _ => { return (core::ptr::null(), 0); }
11198    }
11199    // fallthrough for 'e' (def_pad='_', same logic as 'd')
11200    val = (*tm).tm_mday as i64;
11201    num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width)
11202}
11203
11204unsafe fn __strftime_l(s: *mut c_char, n: usize, f: *const c_char, tm: *const tm) -> usize {
11205    let mut l: usize = 0;
11206    let mut fi: usize = 0;
11207    while l < n {
11208        let ch = *f.add(fi) as u8;
11209        if ch == 0 {
11210            *s.add(l) = 0;
11211            return l;
11212        }
11213        if ch != b'%' {
11214            *s.add(l) = ch as c_char;
11215            l += 1;
11216            fi += 1;
11217            continue;
11218        }
11219        fi += 1;
11220        // Parse flags
11221        let mut pad: u8 = 0;
11222        let fc = *f.add(fi) as u8;
11223        if fc == b'-' || fc == b'_' || fc == b'0' { pad = fc; fi += 1; }
11224        let plus = *f.add(fi) as u8 == b'+';
11225        if plus { fi += 1; }
11226        // Parse width
11227        let mut width: usize = 0;
11228        let mut p_idx = fi;
11229        {
11230            let fc2 = *f.add(fi) as u8;
11231            if fc2 >= b'0' && fc2 <= b'9' {
11232                let mut w: usize = 0;
11233                while { let c = *f.add(p_idx) as u8; c >= b'0' && c <= b'9' } {
11234                    w = w * 10 + (*f.add(p_idx) as usize - b'0' as usize);
11235                    p_idx += 1;
11236                }
11237                width = w;
11238            }
11239        }
11240        let spec_ch = *f.add(p_idx) as u8;
11241        if spec_ch == b'C' || spec_ch == b'F' || spec_ch == b'G' || spec_ch == b'Y' {
11242            if width == 0 && p_idx != fi { width = 1; }
11243        } else {
11244            width = 0;
11245        }
11246        fi = p_idx;
11247        // Skip E/O modifier
11248        let fc3 = *f.add(fi) as u8;
11249        if fc3 == b'E' || fc3 == b'O' { fi += 1; }
11250        let fch = *f.add(fi) as u8;
11251        // Call formatter
11252        let mut buf = [0u8; 100];
11253        let (t, k) = __strftime_fmt_1(&mut buf, fch, tm, pad);
11254        if t.is_null() { break; }
11255        let mut k = k;
11256        let mut t = t;
11257        if width != 0 {
11258            // Strip sign and leading zeros, count remaining digits
11259            if *t == b'+' || *t == b'-' { t = t.add(1); k -= 1; }
11260            while k > 0 && *t == b'0' && k > 1 && *t.add(1) >= b'0' && *t.add(1) <= b'9' {
11261                t = t.add(1); k -= 1;
11262            }
11263            if width < k { width = k; }
11264            let mut d: usize = 0;
11265            while d < k && *t.add(d) >= b'0' && *t.add(d) <= b'9' { d += 1; }
11266            if (*tm).tm_year < -1900 {
11267                if l < n { *s.add(l) = b'-' as c_char; }
11268                l += 1;
11269                width -= 1;
11270            } else if plus && d + (width - k) >= (if spec_ch == b'C' { 3 } else { 5 }) {
11271                if l < n { *s.add(l) = b'+' as c_char; }
11272                l += 1;
11273                width -= 1;
11274            }
11275            while width > k && l < n {
11276                *s.add(l) = b'0' as c_char;
11277                l += 1;
11278                width -= 1;
11279            }
11280        }
11281        let copy = if k > n - l { n - l } else { k };
11282        core::ptr::copy_nonoverlapping(t, s.add(l) as *mut u8, copy);
11283        l += copy;
11284        fi += 1;
11285    }
11286    if n > 0 {
11287        if l == n { l = n - 1; }
11288        *s.add(l) = 0;
11289    }
11290    0
11291}
11292
11293#[no_mangle]
11294pub unsafe extern "C" fn strftime(s: *mut c_char, maxsize: usize, fmt: *const c_char, tm: *const tm) -> usize {
11295    __strftime_l(s, maxsize, fmt, tm)
11296}
11297
11298// ============================================================
11299// Time: strptime
11300// ============================================================
11301
11302unsafe fn match_prefix(s: *const u8, prefix: &[u8]) -> bool {
11303    for i in 0..prefix.len() {
11304        if *s.add(i) == 0 || *s.add(i) != prefix[i] { return false; }
11305    }
11306    true
11307}
11308
11309unsafe fn match_ci_prefix(s: *const u8, prefix: &[u8]) -> bool {
11310    for i in 0..prefix.len() {
11311        let c = *s.add(i);
11312        if c == 0 { return false; }
11313        if c.to_ascii_lowercase() != prefix[i].to_ascii_lowercase() { return false; }
11314    }
11315    true
11316}
11317
11318unsafe fn parse_int(p: *const u8, max_digits: usize) -> (i32, *const u8) {
11319    let mut val = 0i32;
11320    let mut np = p;
11321    let mut count = 0;
11322    while *np >= b'0' && *np <= b'9' && count < max_digits {
11323        val = val * 10 + (*np - b'0') as i32;
11324        np = np.add(1);
11325        count += 1;
11326    }
11327    if count == 0 { (0, p) } else { (val, np) }
11328}
11329
11330unsafe fn parse_range(p: *const u8, min: i32, max: i32) -> (i32, *const u8) {
11331    let (val, np) = parse_int(p, 4);
11332    if np == p || val < min || val > max { (0, p) } else { (val, np) }
11333}
11334
11335fn is_ascii_space(c: u8) -> bool {
11336    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == 0x0c || c == 0x0b
11337}
11338
11339#[no_mangle]
11340pub unsafe extern "C" fn strptime(s: *const c_char, fmt: *const c_char, tm: *mut tm) -> *mut c_char {
11341    let mut p = s as *const u8;
11342    let mut f = fmt as *const u8;
11343    let mut want_century = 0i32;
11344    let mut century = 0i32;
11345    let mut relyear = 0i32;
11346    while *f != 0 {
11347        if *f != b'%' {
11348            if is_ascii_space(*f) {
11349                while *p != 0 && is_ascii_space(*p) { p = p.add(1); }
11350            } else {
11351                if *p != *f { return core::ptr::null_mut(); }
11352                p = p.add(1);
11353            }
11354            f = f.add(1);
11355            continue;
11356        }
11357        f = f.add(1);
11358        if *f == b'+' { f = f.add(1); }
11359        while *f >= b'0' && *f <= b'9' { f = f.add(1); }
11360        if *f == b'E' || *f == b'O' { f = f.add(1); }
11361        match *f {
11362            b'a' | b'A' => {
11363                let mut found = false;
11364                for i in 0..7 {
11365                    let names: [&[u8]; 7] = [b"Sunday", b"Monday", b"Tuesday", b"Wednesday", b"Thursday", b"Friday", b"Saturday"];
11366                    let snames: [&[u8]; 7] = [b"Sun", b"Mon", b"Tue", b"Wed", b"Thu", b"Fri", b"Sat"];
11367                    if match_prefix(p, names[i]) { (*tm).tm_wday = i as c_int; p = p.add(names[i].len()); found = true; break; }
11368                    if match_prefix(p, snames[i]) { (*tm).tm_wday = i as c_int; p = p.add(snames[i].len()); found = true; break; }
11369                }
11370                if !found { return core::ptr::null_mut(); }
11371            }
11372            b'b' | b'B' | b'h' => {
11373                let mut found = false;
11374                for i in 0..12 {
11375                    let names: [&[u8]; 12] = [b"January", b"February", b"March", b"April", b"May", b"June", b"July", b"August", b"September", b"October", b"November", b"December"];
11376                    let snames: [&[u8]; 12] = [b"Jan", b"Feb", b"Mar", b"Apr", b"May", b"Jun", b"Jul", b"Aug", b"Sep", b"Oct", b"Nov", b"Dec"];
11377                    if match_prefix(p, names[i]) { (*tm).tm_mon = i as c_int; p = p.add(names[i].len()); found = true; break; }
11378                    if match_prefix(p, snames[i]) { (*tm).tm_mon = i as c_int; p = p.add(snames[i].len()); found = true; break; }
11379                }
11380                if !found { return core::ptr::null_mut(); }
11381            }
11382            b'C' => {
11383                let (v, np) = parse_int(p, 2);
11384                if np == p { return core::ptr::null_mut(); }
11385                century = v;
11386                want_century |= 2;
11387                p = np;
11388            }
11389            b'd' | b'e' => {
11390                let (v, np) = parse_range(p, 1, 31);
11391                if np == p { return core::ptr::null_mut(); }
11392                (*tm).tm_mday = v;
11393                p = np;
11394            }
11395            b'D' => {
11396                let r = strptime(p as *const c_char, b"%m/%d/%y\0".as_ptr() as *const c_char, tm);
11397                if r.is_null() { return core::ptr::null_mut(); }
11398                p = r as *const u8;
11399            }
11400            b'F' => {
11401                let (yv, ynp) = parse_int(p, 4);
11402                if ynp == p { return core::ptr::null_mut(); }
11403                (*tm).tm_year = yv - 1900;
11404                p = ynp;
11405                if *p != b'-' { return core::ptr::null_mut(); }
11406                p = p.add(1);
11407                let (mv, mnp) = parse_range(p, 1, 12);
11408                if mnp == p { return core::ptr::null_mut(); }
11409                (*tm).tm_mon = mv - 1;
11410                p = mnp;
11411                if *p != b'-' { return core::ptr::null_mut(); }
11412                p = p.add(1);
11413                let (dv, dnp) = parse_range(p, 1, 31);
11414                if dnp == p { return core::ptr::null_mut(); }
11415                (*tm).tm_mday = dv;
11416                p = dnp;
11417            }
11418            b'H' | b'I' => {
11419                let (v, np) = parse_range(p, 0, 23);
11420                if np == p { return core::ptr::null_mut(); }
11421                (*tm).tm_hour = v;
11422                p = np;
11423            }
11424            b'j' => {
11425                let (v, np) = parse_range(p, 1, 366);
11426                if np == p { return core::ptr::null_mut(); }
11427                (*tm).tm_yday = v - 1;
11428                p = np;
11429            }
11430            b'm' => {
11431                let (v, np) = parse_range(p, 1, 12);
11432                if np == p { return core::ptr::null_mut(); }
11433                (*tm).tm_mon = v - 1;
11434                p = np;
11435            }
11436            b'M' => {
11437                let (v, np) = parse_range(p, 0, 59);
11438                if np == p { return core::ptr::null_mut(); }
11439                (*tm).tm_min = v;
11440                p = np;
11441            }
11442            b'n' | b't' => {
11443                while *p != 0 && is_ascii_space(*p) { p = p.add(1); }
11444            }
11445            b'p' => {
11446                if match_ci_prefix(p, b"AM") {
11447                    if (*tm).tm_hour == 12 { (*tm).tm_hour = 0; }
11448                    p = p.add(2);
11449                } else if match_ci_prefix(p, b"PM") {
11450                    if (*tm).tm_hour < 12 { (*tm).tm_hour += 12; }
11451                    p = p.add(2);
11452                } else { return core::ptr::null_mut(); }
11453            }
11454            b'r' => {
11455                let r = strptime(p as *const c_char, b"%I:%M:%S %p\0".as_ptr() as *const c_char, tm);
11456                if r.is_null() { return core::ptr::null_mut(); }
11457                p = r as *const u8;
11458            }
11459            b'R' => {
11460                let r = strptime(p as *const c_char, b"%H:%M\0".as_ptr() as *const c_char, tm);
11461                if r.is_null() { return core::ptr::null_mut(); }
11462                p = r as *const u8;
11463            }
11464            b's' => {
11465                let neg = if *p == b'-' { p = p.add(1); true } else { false };
11466                if *p < b'0' || *p > b'9' { return core::ptr::null_mut(); }
11467                let mut val = 0i64;
11468                while *p >= b'0' && *p <= b'9' {
11469                    val = val * 10 + (*p - b'0') as i64;
11470                    p = p.add(1);
11471                }
11472                if neg { val = -val; }
11473                secs_to_tm(val, &mut *tm);
11474            }
11475            b'S' => {
11476                let (v, np) = parse_range(p, 0, 60);
11477                if np == p { return core::ptr::null_mut(); }
11478                (*tm).tm_sec = v;
11479                p = np;
11480            }
11481            b'T' => {
11482                let r = strptime(p as *const c_char, b"%H:%M:%S\0".as_ptr() as *const c_char, tm);
11483                if r.is_null() { return core::ptr::null_mut(); }
11484                p = r as *const u8;
11485            }
11486            b'U' | b'W' => {
11487                let (_, np) = parse_range(p, 0, 53);
11488                if np == p { return core::ptr::null_mut(); }
11489                p = np;
11490            }
11491            b'V' => {
11492                let (_, np) = parse_range(p, 1, 53);
11493                if np == p { return core::ptr::null_mut(); }
11494                p = np;
11495            }
11496            b'w' => {
11497                let (v, np) = parse_range(p, 0, 6);
11498                if np == p { return core::ptr::null_mut(); }
11499                (*tm).tm_wday = v;
11500                p = np;
11501            }
11502            b'y' => {
11503                let (v, np) = parse_int(p, 2);
11504                if np == p { return core::ptr::null_mut(); }
11505                relyear = v;
11506                want_century |= 1;
11507                p = np;
11508            }
11509            b'Y' => {
11510                let neg = if *p == b'-' { p = p.add(1); true } else { false };
11511                let (v, np) = parse_int(p, 4);
11512                if np == p { return core::ptr::null_mut(); }
11513                (*tm).tm_year = if neg { -(v + 1900) } else { v - 1900 };
11514                want_century = 0;
11515                p = np;
11516            }
11517            b'z' => {
11518                if *p != b'+' && *p != b'-' { return core::ptr::null_mut(); }
11519                let neg = *p == b'-';
11520                p = p.add(1);
11521                let mut off = 0i64;
11522                let mut digits = 0;
11523                while digits < 4 && *p >= b'0' && *p <= b'9' {
11524                    off = off * 10 + (*p - b'0') as i64;
11525                    p = p.add(1);
11526                    digits += 1;
11527                }
11528                if digits == 0 { return core::ptr::null_mut(); }
11529                let (hh, mm) = if digits <= 2 { (off, 0i64) } else { (off / 100, off % 100) };
11530                (*tm).tm_gmtoff = (hh * 3600 + mm * 60) * if neg { -1 } else { 1 };
11531            }
11532            b'%' => {
11533                if *p != b'%' { return core::ptr::null_mut(); }
11534                p = p.add(1);
11535            }
11536            _ => { return core::ptr::null_mut(); }
11537        }
11538        f = f.add(1);
11539    }
11540    if want_century != 0 {
11541        (*tm).tm_year = relyear;
11542        if want_century & 2 != 0 { (*tm).tm_year += century * 100 - 1900; }
11543        else if (*tm).tm_year <= 68 { (*tm).tm_year += 100; }
11544    }
11545    p as *mut c_char
11546}
11547
11548// ============================================================
11549// Time: tzset / daylight / timezone / tzname
11550// ============================================================
11551
11552#[no_mangle]
11553pub static mut daylight: c_int = 0;
11554#[no_mangle]
11555pub static mut timezone: c_long = 0;
11556#[no_mangle]
11557pub static mut tzname: [*mut c_char; 2] = [b"UTC\0".as_ptr() as *mut c_char, b"UTC\0".as_ptr() as *mut c_char];
11558
11559#[no_mangle]
11560pub unsafe extern "C" fn tzset() {
11561    tz_set();
11562}
11563
11564// ============================================================
11565// system()
11566// ============================================================
11567
11568#[no_mangle]
11569pub unsafe extern "C" fn system(cmd: *const c_char) -> c_int {
11570    if cmd.is_null() {
11571        // ponytail: test shell availability via fork+exec
11572        let pid = sys_fork();
11573        if pid == 0 {
11574            let sh = b"/bin/sh\0".as_ptr() as *const c_char;
11575            let dash_c = b"-c\0".as_ptr() as *const c_char;
11576            let exit0 = b"exit 0\0".as_ptr() as *const c_char;
11577            let argv = [b"sh\0".as_ptr() as *const c_char, dash_c, exit0, core::ptr::null()];
11578            sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
11579            _exit(127);
11580        }
11581        if pid < 0 { return -1; }
11582        let mut status: c_int = 0;
11583        loop {
11584            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
11585            if r >= 0 { return status; }
11586            if r != -4 { return -1; } // not EINTR
11587        }
11588    }
11589
11590    let sa_ignore = KSigAction {
11591        sa_handler: SIG_IGN,
11592        sa_flags: SA_RESTORER,
11593        sa_restorer: sig_restorer as *const () as usize,
11594        sa_mask: [0],
11595    };
11596    let mut oldint: KSigAction = core::mem::zeroed();
11597    let mut oldquit: KSigAction = core::mem::zeroed();
11598
11599    sys_rt_sigaction(SIGINT, &sa_ignore, &mut oldint, 8);
11600    sys_rt_sigaction(SIGQUIT, &sa_ignore, &mut oldquit, 8);
11601
11602    let mut block_set: SigSetT = 0;
11603    block_set |= 1u64 << (SIGCHLD - 1);
11604    let mut oldmask: SigSetT = 0;
11605    sys_rt_sigprocmask(SIG_BLOCK, &block_set, &mut oldmask, 8);
11606
11607    let pid = sys_fork();
11608
11609    if pid == 0 {
11610        sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
11611        sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
11612        sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
11613
11614        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
11615        let argv = [
11616            b"sh\0".as_ptr() as *const c_char,
11617            b"-c\0".as_ptr() as *const c_char,
11618            cmd,
11619            core::ptr::null(),
11620        ];
11621        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
11622        _exit(127);
11623    }
11624
11625    let mut status: c_int = -1;
11626    if pid > 0 {
11627        loop {
11628            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
11629            if r >= 0 { break; }
11630            if r != -4 { break; } // not EINTR
11631        }
11632    }
11633
11634    sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
11635    sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
11636    sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
11637
11638    status
11639}
11640
11641// ============================================================
11642// errno: strerror / strerror_r / environ alias
11643// ============================================================
11644
11645const EPERM_VAL: c_int = 1;
11646const ENOENT_VAL: c_int = 2;
11647const ESRCH_VAL: c_int = 3;
11648const EINTR_VAL: c_int = 4;
11649const EIO_VAL: c_int = 5;
11650const ENXIO_VAL: c_int = 6;
11651const E2BIG_VAL: c_int = 7;
11652const ENOEXEC_VAL: c_int = 8;
11653const EBADF_VAL: c_int = 9;
11654const ECHILD_VAL: c_int = 10;
11655const EAGAIN_VAL: c_int = 11;
11656const ENOMEM_VAL: c_int = 12;
11657const EACCES_VAL: c_int = 13;
11658const EFAULT_VAL: c_int = 14;
11659const ENOTBLK_VAL: c_int = 15;
11660const EBUSY_VAL: c_int = 16;
11661const EEXIST_VAL: c_int = 17;
11662const EXDEV_VAL: c_int = 18;
11663const ENODEV_VAL: c_int = 19;
11664const ENOTDIR_VAL: c_int = 20;
11665const EISDIR_VAL: c_int = 21;
11666const EINVAL_VAL: c_int = 22;
11667const ENFILE_VAL: c_int = 23;
11668const EMFILE_VAL: c_int = 24;
11669const ENOTTY_VAL: c_int = 25;
11670const ETXTBSY_VAL: c_int = 26;
11671const EFBIG_VAL: c_int = 27;
11672const ENOSPC_VAL: c_int = 28;
11673const ESPIPE_VAL: c_int = 29;
11674const EROFS_VAL: c_int = 30;
11675const EMLINK_VAL: c_int = 31;
11676const EPIPE_VAL: c_int = 32;
11677const EDOM_VAL: c_int = 33;
11678const ERANGE_VAL: c_int = 34;
11679const EDEADLK_VAL: c_int = 35;
11680const ENAMETOOLONG_VAL: c_int = 36;
11681const ENOLCK_VAL: c_int = 37;
11682const ENOSYS_VAL: c_int = 38;
11683const ENOTEMPTY_VAL: c_int = 39;
11684const ELOOP_VAL: c_int = 40;
11685const EWOULDBLOCK_VAL: c_int = 11;
11686const ENOMSG_VAL: c_int = 42;
11687const EIDRM_VAL: c_int = 43;
11688const ECHRNG_VAL: c_int = 44;
11689const EL2NSYNC_VAL: c_int = 45;
11690const EL3HLT_VAL: c_int = 46;
11691const EL3RST_VAL: c_int = 47;
11692const ELNRNG_VAL: c_int = 48;
11693const EUNATCH_VAL: c_int = 49;
11694const ENOCSI_VAL: c_int = 50;
11695const EL2HLT_VAL: c_int = 51;
11696const EBADE_VAL: c_int = 52;
11697const EBADR_VAL: c_int = 53;
11698const EXFULL_VAL: c_int = 54;
11699const ENOANO_VAL: c_int = 55;
11700const EBADRQC_VAL: c_int = 56;
11701const EBADSLT_VAL: c_int = 57;
11702const EBFONT_VAL: c_int = 59;
11703const ENOSTR_VAL: c_int = 60;
11704const ENODATA_VAL: c_int = 61;
11705const ETIME_VAL: c_int = 62;
11706const ENOSR_VAL: c_int = 63;
11707const ENONET_VAL: c_int = 64;
11708const ENOPKG_VAL: c_int = 65;
11709const EREMOTE_VAL: c_int = 66;
11710const ENOLINK_VAL: c_int = 67;
11711const EADV_VAL: c_int = 68;
11712const ESRMNT_VAL: c_int = 69;
11713const ECOMM_VAL: c_int = 70;
11714const EPROTO_VAL: c_int = 71;
11715const EMULTIHOP_VAL: c_int = 72;
11716const EDOTDOT_VAL: c_int = 73;
11717const EBADMSG_VAL: c_int = 74;
11718const EOVERFLOW_VAL: c_int = 75;
11719const ENOTUNIQ_VAL: c_int = 76;
11720const EBADFD_VAL: c_int = 77;
11721const EREMCHG_VAL: c_int = 78;
11722const ELIBACC_VAL: c_int = 79;
11723const ELIBBAD_VAL: c_int = 80;
11724const ELIBSCN_VAL: c_int = 81;
11725const ELIBMAX_VAL: c_int = 82;
11726const ELIBEXEC_VAL: c_int = 83;
11727const EILSEQ_VAL: c_int = 84;
11728const ERESTART_VAL: c_int = 85;
11729const ESTRPIPE_VAL: c_int = 86;
11730const EUSERS_VAL: c_int = 87;
11731const ENOTSOCK_VAL: c_int = 88;
11732const EDESTADDRREQ_VAL: c_int = 89;
11733const EMSGSIZE_VAL: c_int = 90;
11734const EPROTOTYPE_VAL: c_int = 91;
11735const ENOPROTOOPT_VAL: c_int = 92;
11736const EPROTONOSUPPORT_VAL: c_int = 93;
11737const ESOCKTNOSUPPORT_VAL: c_int = 94;
11738const EOPNOTSUPP_VAL: c_int = 95;
11739const ENOTSUP_VAL: c_int = 95;
11740const EPFNOSUPPORT_VAL: c_int = 96;
11741const EAFNOSUPPORT_VAL: c_int = 97;
11742const EADDRINUSE_VAL: c_int = 98;
11743const EADDRNOTAVAIL_VAL: c_int = 99;
11744const ENETDOWN_VAL: c_int = 100;
11745const ENETUNREACH_VAL: c_int = 101;
11746const ENETRESET_VAL: c_int = 102;
11747const ECONNABORTED_VAL: c_int = 103;
11748const ECONNRESET_VAL: c_int = 104;
11749const ENOBUFS_VAL: c_int = 105;
11750const EISCONN_VAL: c_int = 106;
11751const ENOTCONN_VAL: c_int = 107;
11752const ESHUTDOWN_VAL: c_int = 108;
11753const ETOOMANYREFS_VAL: c_int = 109;
11754const ETIMEDOUT_VAL: c_int = 110;
11755const ECONNREFUSED_VAL: c_int = 111;
11756const EHOSTDOWN_VAL: c_int = 112;
11757const EHOSTUNREACH_VAL: c_int = 113;
11758const EALREADY_VAL: c_int = 114;
11759const EINPROGRESS_VAL: c_int = 115;
11760const ESTALE_VAL: c_int = 116;
11761const EUCLEAN_VAL: c_int = 117;
11762const ENOTNAM_VAL: c_int = 118;
11763const ENAVAIL_VAL: c_int = 119;
11764const EISNAM_VAL: c_int = 120;
11765const EREMOTEIO_VAL: c_int = 121;
11766const EDQUOT_VAL: c_int = 122;
11767const ENOMEDIUM_VAL: c_int = 123;
11768const EMEDIUMTYPE_VAL: c_int = 124;
11769const ECANCELED_VAL: c_int = 125;
11770const ENOKEY_VAL: c_int = 126;
11771const EKEYEXPIRED_VAL: c_int = 127;
11772const EKEYREVOKED_VAL: c_int = 128;
11773const EKEYREJECTED_VAL: c_int = 129;
11774const EOWNERDEAD_VAL: c_int = 130;
11775const ENOTRECOVERABLE_VAL: c_int = 131;
11776const ERFKILL_VAL: c_int = 132;
11777const EHWPOISON_VAL: c_int = 133;
11778
11779// ponytail: static error string table indexed by errno
11780static ERR_STRS: [&[u8]; 134] = [
11781    b"Success\0",                     // 0
11782    b"Operation not permitted\0",     // 1
11783    b"No such file or directory\0",   // 2
11784    b"No such process\0",             // 3
11785    b"Interrupted system call\0",     // 4
11786    b"Input/output error\0",          // 5
11787    b"No such device or address\0",   // 6
11788    b"Argument list too long\0",      // 7
11789    b"Exec format error\0",           // 8
11790    b"Bad file descriptor\0",         // 9
11791    b"No child processes\0",          // 10
11792    b"Resource temporarily unavailable\0", // 11
11793    b"Cannot allocate memory\0",      // 12
11794    b"Permission denied\0",           // 13
11795    b"Bad address\0",                 // 14
11796    b"Block device required\0",       // 15
11797    b"Device or resource busy\0",     // 16
11798    b"File exists\0",                 // 17
11799    b"Invalid cross-device link\0",   // 18
11800    b"No such device\0",              // 19
11801    b"Not a directory\0",             // 20
11802    b"Is a directory\0",              // 21
11803    b"Invalid argument\0",            // 22
11804    b"Too many open files in system\0", // 23
11805    b"Too many open files\0",         // 24
11806    b"Inappropriate ioctl for device\0", // 25
11807    b"Text file busy\0",              // 26
11808    b"File too large\0",              // 27
11809    b"No space left on device\0",     // 28
11810    b"Illegal seek\0",                // 29
11811    b"Read-only file system\0",       // 30
11812    b"Too many links\0",              // 31
11813    b"Broken pipe\0",                 // 32
11814    b"Numerical argument out of domain\0", // 33
11815    b"Numerical result out of range\0", // 34
11816    b"Resource deadlock avoided\0",   // 35
11817    b"File name too long\0",          // 36
11818    b"No locks available\0",          // 37
11819    b"Function not implemented\0",    // 38
11820    b"Directory not empty\0",         // 39
11821    b"Too many levels of symbolic links\0", // 40
11822    b"Unknown error 41\0",            // 41
11823    b"No message of desired type\0",  // 42
11824    b"Identifier removed\0",          // 43
11825    b"Channel number out of range\0", // 44
11826    b"Level 2 not synchronized\0",    // 45
11827    b"Level 3 halted\0",              // 46
11828    b"Level 3 reset\0",               // 47
11829    b"Link number out of range\0",    // 48
11830    b"Protocol driver not attached\0", // 49
11831    b"No CSI structure available\0",  // 50
11832    b"Level 2 halted\0",              // 51
11833    b"Invalid exchange\0",            // 52
11834    b"Invalid request descriptor\0",  // 53
11835    b"Exchange full\0",               // 54
11836    b"No anode\0",                    // 55
11837    b"Invalid request code\0",        // 56
11838    b"Invalid slot\0",                // 57
11839    b"Unknown error 58\0",            // 58
11840    b"Bad font file format\0",        // 59
11841    b"Device not a stream\0",         // 60
11842    b"No data available\0",           // 61
11843    b"Timer expired\0",               // 62
11844    b"Out of streams resources\0",    // 63
11845    b"Machine is not on the network\0", // 64
11846    b"Package not installed\0",       // 65
11847    b"Object is remote\0",            // 66
11848    b"Link has been severed\0",       // 67
11849    b"Advertise error\0",             // 68
11850    b"Srmount error\0",               // 69
11851    b"Communication error on send\0", // 70
11852    b"Protocol error\0",              // 71
11853    b"Multihop attempted\0",          // 72
11854    b"RFS specific error\0",          // 73
11855    b"Bad message\0",                 // 74
11856    b"Value too large for defined data type\0", // 75
11857    b"Name not unique on network\0",  // 76
11858    b"File descriptor in bad state\0", // 77
11859    b"Remote address changed\0",      // 78
11860    b"Can not access a needed shared library\0", // 79
11861    b"Accessing a corrupted shared library\0", // 80
11862    b".lib section in a.out corrupted\0", // 81
11863    b"Attempting to link in too many shared libraries\0", // 82
11864    b"Cannot exec a shared library directly\0", // 83
11865    b"Invalid or incomplete multibyte or wide character\0", // 84
11866    b"Interrupted system call should be restarted\0", // 85
11867    b"Streams pipe error\0",          // 86
11868    b"Too many users\0",              // 87
11869    b"Socket operation on non-socket\0", // 88
11870    b"Destination address required\0", // 89
11871    b"Message too long\0",            // 90
11872    b"Protocol wrong type for socket\0", // 91
11873    b"Protocol not available\0",      // 92
11874    b"Protocol not supported\0",      // 93
11875    b"Socket type not supported\0",   // 94
11876    b"Operation not supported\0",     // 95
11877    b"Protocol family not supported\0", // 96
11878    b"Address family not supported by protocol\0", // 97
11879    b"Address already in use\0",      // 98
11880    b"Cannot assign requested address\0", // 99
11881    b"Network is down\0",             // 100
11882    b"Network is unreachable\0",      // 101
11883    b"Network dropped connection on reset\0", // 102
11884    b"Software caused connection abort\0", // 103
11885    b"Connection reset by peer\0",    // 104
11886    b"No buffer space available\0",   // 105
11887    b"Transport endpoint is already connected\0", // 106
11888    b"Transport endpoint is not connected\0", // 107
11889    b"Cannot send after transport endpoint shutdown\0", // 108
11890    b"Too many references: cannot splice\0", // 109
11891    b"Connection timed out\0",        // 110
11892    b"Connection refused\0",          // 111
11893    b"Host is down\0",                // 112
11894    b"No route to host\0",            // 113
11895    b"Operation already in progress\0", // 114
11896    b"Operation now in progress\0",   // 115
11897    b"Stale file handle\0",           // 116
11898    b"Structure needs cleaning\0",    // 117
11899    b"Not a XENIX named type file\0", // 118
11900    b"No XENIX semaphores available\0", // 119
11901    b"Is a named type file\0",        // 120
11902    b"Remote I/O error\0",            // 121
11903    b"Quota exceeded\0",              // 122
11904    b"No medium found\0",             // 123
11905    b"Wrong medium type\0",           // 124
11906    b"Operation canceled\0",          // 125
11907    b"Required key not available\0",  // 126
11908    b"Key has expired\0",             // 127
11909    b"Key has been revoked\0",        // 128
11910    b"Key was rejected by service\0", // 129
11911    b"Owner died\0",                  // 130
11912    b"State not recoverable\0",       // 131
11913    b"Operation not possible due to RF-kill\0", // 132
11914    b"Memory page has hardware error\0", // 133
11915];
11916
11917#[no_mangle]
11918pub unsafe extern "C" fn strerror(errnum: c_int) -> *mut c_char {
11919    if errnum < 0 || errnum as usize >= ERR_STRS.len() {
11920        // ponytail: static buf for unknown errors
11921        static mut UNKNOWN_BUF: [c_char; 64] = [0; 64];
11922        let prefix = b"Unknown error \0";
11923        let mut i = 0;
11924        while prefix[i] != 0 {
11925            UNKNOWN_BUF[i] = prefix[i] as c_char;
11926            i += 1;
11927        }
11928        let (buf, len) = format_u64(errnum as u64);
11929        for j in 0..len {
11930            UNKNOWN_BUF[i] = buf[20 - len + j] as c_char;
11931            i += 1;
11932        }
11933        UNKNOWN_BUF[i] = 0;
11934        return core::ptr::addr_of_mut!(UNKNOWN_BUF).cast::<c_char>();
11935    }
11936    ERR_STRS[errnum as usize].as_ptr() as *mut c_char
11937}
11938
11939#[no_mangle]
11940pub unsafe extern "C" fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: usize) -> c_int {
11941    let s = strerror(errnum);
11942    let slen = strlen(s as *const c_char);
11943    if slen >= buflen {
11944        if buflen > 0 {
11945            core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, buflen - 1);
11946            *buf.add(buflen - 1) = 0;
11947        }
11948        return 34; // ERANGE
11949    }
11950    core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, slen + 1);
11951    0
11952}
11953
11954// ponytail: `environ` alias for tests that use extern char **environ
11955#[no_mangle]
11956pub static mut environ: *mut *mut c_char = core::ptr::null_mut();
11957
11958// keep environ in sync with __environ
11959unsafe fn sync_environ() {
11960    environ = __environ;
11961}
11962
11963// ============================================================
11964// unistd extensions: pipe, dup, dup2, fcntl, access, unlink, etc.
11965// ============================================================
11966
11967#[inline]
11968unsafe fn sys_dup(oldfd: i32) -> i64 {
11969    <Arch as Syscalls>::syscall1(SYS_DUP, oldfd as i64)
11970}
11971
11972#[inline]unsafe fn sys_dup2(oldfd: i32, newfd: i32) -> i64 {
11973    // ponytail: dup3 with flags=0 is equivalent to dup2
11974    sys_dup3(oldfd, newfd, 0)
11975}
11976
11977#[inline]
11978unsafe fn sys_access(path: *const u8, mode: i32) -> i64 {
11979    <Arch as Syscalls>::syscall4(SYS_FACCESSAT, AT_FDCWD as i64, path as i64, mode as i64, 0)
11980}
11981
11982#[inline]unsafe fn sys_unlink(path: *const u8) -> i64 {
11983    sys_unlinkat(AT_FDCWD, path, 0)
11984}
11985
11986#[inline]unsafe fn sys_rmdir(path: *const u8) -> i64 {
11987    sys_unlinkat(AT_FDCWD, path, 512) // AT_REMOVEDIR
11988}
11989
11990#[inline]
11991unsafe fn sys_chdir(path: *const u8) -> i64 {
11992    <Arch as Syscalls>::syscall1(SYS_CHDIR, path as i64)
11993}
11994
11995#[inline]
11996unsafe fn sys_getcwd(buf: *mut u8, size: usize) -> i64 {
11997    <Arch as Syscalls>::syscall2(SYS_GETCWD, buf as i64, size as i64)
11998}
11999
12000#[inline]
12001unsafe fn sys_sethostname(name: *const u8, len: usize) -> i64 {
12002    <Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)
12003}
12004
12005#[inline]
12006unsafe fn sys_gethostname(buf: *mut u8, len: usize) -> i64 {
12007    #[repr(C)]
12008    struct UtsName {
12009        sysname: [u8; 65],
12010        nodename: [u8; 65],
12011        release: [u8; 65],
12012        version: [u8; 65],
12013        machine: [u8; 65],
12014        domainname: [u8; 65],
12015    }
12016    let mut uts: UtsName = core::mem::zeroed();
12017    let result = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
12018    if result < 0 {
12019        return result;
12020    }
12021    let nlen = strlen(uts.nodename.as_ptr() as *const c_char);
12022    let copylen = if nlen < len { nlen } else { if len > 0 { len - 1 } else { 0 } };
12023    core::ptr::copy_nonoverlapping(uts.nodename.as_ptr(), buf, copylen);
12024    if len > 0 { *buf.add(copylen) = 0; }
12025    0
12026}
12027
12028unsafe fn sys_truncate(path: *const u8, length: i64) -> i64 {
12029    <Arch as Syscalls>::syscall2(SYS_TRUNCATE, path as i64, length as i64)
12030}
12031
12032unsafe fn sys_ftruncate(fd: i32, length: i64) -> i64 {
12033    <Arch as Syscalls>::syscall2(SYS_FTRUNCATE, fd as i64, length as i64)
12034}
12035
12036unsafe fn sys_nanosleep(req: *const timespec, rem: *mut timespec) -> i64 {
12037    <Arch as Syscalls>::syscall2(SYS_NANOSLEEP, req as i64, rem as i64)
12038}
12039
12040const ITIMER_REAL: i32 = 0;
12041
12042#[repr(C)]
12043struct itimerval {
12044    it_interval: timeval,
12045    it_value: timeval,
12046}
12047
12048unsafe fn sys_alarm(seconds: c_uint) -> i64 {
12049    let mut new: itimerval = core::mem::zeroed();
12050    new.it_value.tv_sec = seconds as c_long;
12051    let mut old: itimerval = core::mem::zeroed();
12052    let r = <Arch as Syscalls>::syscall3(
12053        SYS_SETITIMER,
12054        ITIMER_REAL as i64,
12055        &new as *const _ as i64,
12056        &mut old as *mut _ as i64,
12057    );
12058    if r < 0 {
12059        return r;
12060    }
12061    old.it_value.tv_sec as i64 + (old.it_value.tv_usec != 0) as i64
12062}
12063
12064unsafe fn sys_pause() -> i64 {
12065    #[cfg(target_arch = "x86_64")]
12066    { <Arch as Syscalls>::syscall0(SYS_PAUSE) }
12067    #[cfg(target_arch = "aarch64")]
12068    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
12069    #[cfg(target_arch = "riscv64")]
12070    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
12071}
12072
12073unsafe fn sys_fsync(fd: i32) -> i64 {
12074    <Arch as Syscalls>::syscall1(SYS_FSYNC, fd as i64)
12075}
12076
12077unsafe fn sys_fdatasync(fd: i32) -> i64 {
12078    <Arch as Syscalls>::syscall1(SYS_FDATASYNC, fd as i64)
12079}
12080
12081unsafe fn sys_sync() {
12082    let _ = <Arch as Syscalls>::syscall0(SYS_SYNC);
12083}
12084
12085unsafe fn sys_symlink(target: *const u8, linkpath: *const u8) -> i64 {
12086    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, AT_FDCWD as i64, linkpath as i64)
12087}
12088
12089unsafe fn sys_symlinkat(target: *const u8, newdirfd: i32, linkpath: *const u8) -> i64 {
12090    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)
12091}
12092
12093unsafe fn sys_readlinkat(dirfd: i32, path: *const u8, buf: *mut u8, bufsiz: usize) -> i64 {
12094    <Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, path as i64, buf as i64, bufsiz as i64)
12095}
12096
12097unsafe fn sys_linkat(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: i32) -> i64 {
12098    <Arch as Syscalls>::syscall5(SYS_LINKAT, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
12099}
12100
12101unsafe fn sys_fchmod(fd: i32, mode: u32) -> i64 {
12102    <Arch as Syscalls>::syscall2(SYS_FCHMOD, fd as i64, mode as i64)
12103}
12104
12105unsafe fn sys_fchmodat(dirfd: i32, path: *const u8, mode: u32, flags: i32) -> i64 {
12106    <Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, path as i64, mode as i64, flags as i64)
12107}
12108
12109unsafe fn sys_umask(mask: u32) -> u32 {
12110    <Arch as Syscalls>::syscall1(SYS_UMASK, mask as i64) as u32
12111}
12112
12113unsafe fn sys_getgroups(size: i32, list: *mut c_uint) -> i64 {
12114    <Arch as Syscalls>::syscall2(SYS_GETGROUPS, size as i64, list as i64)
12115}
12116
12117unsafe fn sys_setuid(uid: c_uint) -> i64 {
12118    <Arch as Syscalls>::syscall1(SYS_SETUID, uid as i64)
12119}
12120
12121unsafe fn sys_setgid(gid: c_uint) -> i64 {
12122    <Arch as Syscalls>::syscall1(SYS_SETGID, gid as i64)
12123}
12124
12125unsafe fn sys_setsid() -> i64 {
12126    <Arch as Syscalls>::syscall0(SYS_SETSID)
12127}
12128
12129unsafe fn sys_setpgid(pid: c_int, pgid: c_int) -> i64 {
12130    <Arch as Syscalls>::syscall2(SYS_SETPGID, pid as i64, pgid as i64)
12131}
12132
12133unsafe fn sys_getpgid(pid: c_int) -> i64 {
12134    <Arch as Syscalls>::syscall1(SYS_GETPGID, pid as i64)
12135}
12136
12137unsafe fn sys_getsid(pid: c_int) -> i64 {
12138    <Arch as Syscalls>::syscall1(SYS_GETSID, pid as i64)
12139}
12140
12141unsafe fn sys_mkdirat(dirfd: i32, path: *const u8, mode: u32) -> i64 {
12142    <Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, path as i64, mode as i64)
12143}
12144
12145// Public C ABI wrappers for unistd
12146
12147#[no_mangle]
12148pub unsafe extern "C" fn pipe(fds: *mut c_int) -> c_int {
12149    let r = sys_pipe2(fds, 0);
12150    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12151    0
12152}
12153
12154#[no_mangle]
12155pub unsafe extern "C" fn pipe2(fds: *mut c_int, flags: c_int) -> c_int {
12156    let r = sys_pipe2(fds, flags);
12157    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12158    0
12159}
12160
12161#[no_mangle]
12162pub unsafe extern "C" fn dup(oldfd: c_int) -> c_int {
12163    let r = sys_dup(oldfd);
12164    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12165    r as c_int
12166}
12167
12168#[no_mangle]
12169pub unsafe extern "C" fn dup2(oldfd: c_int, newfd: c_int) -> c_int {
12170    if oldfd == newfd {
12171        // dup3 rejects equal descriptors with EINVAL; dup2 must validate the
12172        // descriptor and return newfd unchanged.
12173        let r = sys_fcntl(oldfd, 1 /* F_GETFD */, 0);
12174        if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12175        return newfd;
12176    }
12177    let r = sys_dup2(oldfd, newfd);
12178    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12179    r as c_int
12180}
12181
12182#[no_mangle]
12183pub unsafe extern "C" fn dup3(oldfd: c_int, newfd: c_int, flags: c_int) -> c_int {
12184    let r = sys_dup3(oldfd, newfd, flags);
12185    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12186    r as c_int
12187}
12188
12189#[no_mangle]
12190pub unsafe extern "C" fn fcntl(fd: c_int, cmd: c_int, mut args: ...) -> c_int {
12191    // Commands without an argument. Everything else (including seals,
12192    // pipe sizes, ownership and locks) takes the third argument.
12193    let no_arg = matches!(cmd, 1 /* F_GETFD */ | 3 /* F_GETFL */ | 9 /* F_GETOWN */
12194        | 11 /* F_GETSIG */ | 1025 /* F_GETLEASE */ | 1032 /* F_GETPIPE_SZ */
12195        | 1034 /* F_GET_SEALS */);
12196    let r = if no_arg {
12197        sys_fcntl(fd, cmd, 0)
12198    } else {
12199        let arg = args.next_arg::<c_long>();
12200        sys_fcntl(fd, cmd, arg)
12201    };
12202    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12203    r as c_int
12204}
12205
12206#[no_mangle]
12207pub unsafe extern "C" fn access(path: *const c_char, mode: c_int) -> c_int {
12208    let r = sys_access(path as *const u8, mode);
12209    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12210    0
12211}
12212
12213#[no_mangle]
12214pub unsafe extern "C" fn unlink(path: *const c_char) -> c_int {
12215    let r = sys_unlink(path as *const u8);
12216    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12217    0
12218}
12219
12220#[no_mangle]
12221pub unsafe extern "C" fn rmdir(path: *const c_char) -> c_int {
12222    let r = sys_rmdir(path as *const u8);
12223    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12224    0
12225}
12226
12227#[no_mangle]
12228pub unsafe extern "C" fn chdir(path: *const c_char) -> c_int {
12229    let r = sys_chdir(path as *const u8);
12230    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12231    0
12232}
12233
12234#[no_mangle]
12235pub unsafe extern "C" fn getcwd(buf: *mut c_char, size: usize) -> *mut c_char {
12236    if buf.is_null() {
12237        // allocate
12238        let alloc_size = if size == 0 { 256 } else { size };
12239        let p = malloc(alloc_size) as *mut c_char;
12240        if p.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
12241        let r = sys_getcwd(p as *mut u8, alloc_size);
12242        if r < 0 { free(p as *mut c_void); ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
12243        // The kernel returns "(unreachable)..." when cwd is outside the
12244        // current root; POSIX getcwd must fail with ENOENT in that case.
12245        if *p as u8 != b'/' {
12246            free(p as *mut c_void);
12247            ERRNO!() = 2;
12248            return core::ptr::null_mut();
12249        }
12250        return p;
12251    }
12252    if size == 0 { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
12253    let r = sys_getcwd(buf as *mut u8, size);
12254    if r < 0 { ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
12255    if *buf as u8 != b'/' {
12256        ERRNO!() = 2;
12257        return core::ptr::null_mut();
12258    }
12259    buf
12260}
12261
12262#[no_mangle]
12263pub unsafe extern "C" fn gethostname(name: *mut c_char, len: usize) -> c_int {
12264    let r = sys_gethostname(name as *mut u8, len);
12265    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12266    0
12267}
12268
12269// ponytail: getpagesize - hardcoded 4096 for x86_64
12270#[no_mangle]
12271pub extern "C" fn getpagesize() -> c_int {
12272    4096
12273}
12274
12275#[no_mangle]
12276pub unsafe extern "C" fn truncate(path: *const c_char, length: i64) -> c_int {
12277    let r = sys_truncate(path as *const u8, length);
12278    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12279    0
12280}
12281
12282#[no_mangle]
12283pub unsafe extern "C" fn ftruncate(fd: c_int, length: i64) -> c_int {
12284    let r = sys_ftruncate(fd, length);
12285    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12286    0
12287}
12288
12289#[no_mangle]
12290pub unsafe extern "C" fn nanosleep(req: *const timespec, rem: *mut timespec) -> c_int {
12291    pthread_testcancel();
12292    let r = sys_nanosleep(req, rem);
12293    pthread_testcancel();
12294    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12295    0
12296}
12297
12298#[no_mangle]
12299pub unsafe extern "C" fn sleep(seconds: c_uint) -> c_uint {
12300    let req = timespec { tv_sec: seconds as c_long, tv_nsec: 0 };
12301    let mut rem: timespec = core::mem::zeroed();
12302    pthread_testcancel();
12303    let r = sys_nanosleep(&req, &mut rem);
12304    pthread_testcancel();
12305    if r < 0 {
12306        let e = (-r) as c_int;
12307        if e == EINTR { return rem.tv_sec as c_uint; }
12308    }
12309    0
12310}
12311
12312#[no_mangle]
12313pub unsafe extern "C" fn usleep(usec: c_uint) -> c_int {
12314    let req = timespec { tv_sec: (usec / 1000000) as c_long, tv_nsec: ((usec % 1000000) * 1000) as c_long };
12315    pthread_testcancel();
12316    let r = sys_nanosleep(&req, core::ptr::null_mut());
12317    pthread_testcancel();
12318    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12319    0
12320}
12321
12322#[no_mangle]
12323pub unsafe extern "C" fn alarm(seconds: c_uint) -> c_uint {
12324    // POSIX rounds a nonzero fractional remainder up to one second;
12325    // sys_alarm() already performs that rounding.
12326    let r = sys_alarm(seconds);
12327    if r < 0 { 0 } else { r as c_uint }
12328}
12329
12330#[no_mangle]
12331pub unsafe extern "C" fn pause() -> c_int {
12332    pthread_testcancel();
12333    sys_pause();
12334    pthread_testcancel();
12335    ERRNO!() = EINTR;
12336    -1
12337}
12338
12339#[no_mangle]
12340pub unsafe extern "C" fn fsync(fd: c_int) -> c_int {
12341    let r = sys_fsync(fd);
12342    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12343    0
12344}
12345
12346#[no_mangle]
12347pub unsafe extern "C" fn fdatasync(fd: c_int) -> c_int {
12348    let r = sys_fdatasync(fd);
12349    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12350    0
12351}
12352
12353#[no_mangle]
12354pub unsafe extern "C" fn sync() {
12355    sys_sync();
12356}
12357
12358#[no_mangle]
12359pub unsafe extern "C" fn symlink(target: *const c_char, linkpath: *const c_char) -> c_int {
12360    let r = sys_symlinkat(target as *const u8, AT_FDCWD, linkpath as *const u8);
12361    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12362    0
12363}
12364
12365#[no_mangle]
12366pub unsafe extern "C" fn readlink(path: *const c_char, buf: *mut c_char, bufsiz: usize) -> isize {
12367    let r = sys_readlinkat(AT_FDCWD, path as *const u8, buf as *mut u8, bufsiz);
12368    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12369    r as isize
12370}
12371
12372#[no_mangle]
12373pub unsafe extern "C" fn link(oldpath: *const c_char, newpath: *const c_char) -> c_int {
12374    let r = sys_linkat(AT_FDCWD, oldpath as *const u8, AT_FDCWD, newpath as *const u8, 0);
12375    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12376    0
12377}
12378
12379#[no_mangle]
12380pub unsafe extern "C" fn chmod(path: *const c_char, mode: c_uint) -> c_int {
12381    let r = sys_fchmodat(AT_FDCWD, path as *const u8, mode, 0);
12382    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12383    0
12384}
12385
12386#[no_mangle]
12387pub unsafe extern "C" fn fchmod(fd: c_int, mode: c_uint) -> c_int {
12388    let r = sys_fchmod(fd, mode);
12389    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12390    0
12391}
12392
12393#[no_mangle]
12394pub unsafe extern "C" fn umask(mask: c_uint) -> c_uint {
12395    sys_umask(mask) as c_uint
12396}
12397
12398#[no_mangle]
12399pub unsafe extern "C" fn isatty(fd: c_int) -> c_int {
12400    let mut ws: winsize = core::mem::zeroed();
12401    if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 { 1 } else { 0 }
12402}
12403
12404#[no_mangle]
12405pub unsafe extern "C" fn getlogin() -> *mut c_char {
12406    crate::getenv(b"LOGNAME\0".as_ptr() as *const c_char)
12407}
12408
12409#[no_mangle]
12410pub unsafe extern "C" fn getgroups(size: c_int, list: *mut c_uint) -> c_int {
12411    let r = sys_getgroups(size, list);
12412    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12413    r as c_int
12414}
12415
12416#[no_mangle]
12417pub unsafe extern "C" fn setuid(uid: c_uint) -> c_int {
12418    let r = sys_setuid(uid);
12419    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12420    0
12421}
12422
12423#[no_mangle]
12424pub unsafe extern "C" fn setgid(gid: c_uint) -> c_int {
12425    let r = sys_setgid(gid);
12426    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12427    0
12428}
12429
12430#[no_mangle]
12431pub unsafe extern "C" fn seteuid(euid: c_uint) -> c_int {
12432    // Setting only the effective uid must keep the real and saved uids, so a
12433    // process can drop privileges and later restore them (setuid would clear
12434    // the saved uid for root).
12435    setresuid(u32::MAX, euid, u32::MAX)
12436}
12437
12438#[no_mangle]
12439pub unsafe extern "C" fn setegid(egid: c_uint) -> c_int {
12440    setresgid(u32::MAX, egid, u32::MAX)
12441}
12442
12443#[no_mangle]
12444pub unsafe extern "C" fn setreuid(ruid: c_uint, euid: c_uint) -> c_int {
12445    let r = <Arch as Syscalls>::syscall2(sysno(113, 145), ruid as i64, euid as i64);
12446    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
12447}
12448
12449
12450
12451#[no_mangle]
12452pub unsafe extern "C" fn setsid() -> c_int {
12453    let r = sys_setsid();
12454    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12455    r as c_int
12456}
12457
12458#[no_mangle]
12459pub unsafe extern "C" fn setpgid(pid: c_int, pgid: c_int) -> c_int {
12460    let r = sys_setpgid(pid, pgid);
12461    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12462    0
12463}
12464
12465#[no_mangle]
12466pub unsafe extern "C" fn getpgid(pid: c_int) -> c_int {
12467    let r = sys_getpgid(pid);
12468    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12469    r as c_int
12470}
12471
12472#[no_mangle]
12473pub unsafe extern "C" fn getsid(pid: c_int) -> c_int {
12474    let r = sys_getsid(pid);
12475    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12476    r as c_int
12477}
12478
12479#[no_mangle]
12480pub unsafe extern "C" fn getpgrp() -> c_int {
12481    sys_getpgid(0) as c_int
12482}
12483
12484#[no_mangle]
12485pub unsafe extern "C" fn setpgrp() -> c_int {
12486    setpgid(0, 0)
12487}
12488
12489#[no_mangle]
12490unsafe fn mkstemps_impl(template: *mut c_char, suffixlen: i32) -> c_int {
12491    if template.is_null() || suffixlen < 0 {
12492        ERRNO!() = EINVAL;
12493        return -1;
12494    }
12495    let len = strlen(template as *const c_char);
12496    let suffix = suffixlen as usize;
12497    if len < 6 + suffix {
12498        ERRNO!() = EINVAL;
12499        return -1;
12500    }
12501    let x_start = len - suffix - 6;
12502    for i in x_start..x_start + 6 {
12503        if *template.add(i) != b'X' as c_char {
12504            ERRNO!() = EINVAL;
12505            return -1;
12506        }
12507    }
12508    let mut ts: timespec = core::mem::zeroed();
12509    let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
12510    let mut ctr: u32 = ts.tv_nsec as u32;
12511    for _ in 0..100 {
12512        ctr = ctr.wrapping_mul(1103515245).wrapping_add(12345);
12513        let mut seed = ctr;
12514        let hex = b"0123456789abcdef";
12515        for i in x_start..x_start + 6 {
12516            *template.add(i) = hex[(seed & 0xf) as usize] as c_char;
12517            seed >>= 4;
12518        }
12519        let fd = sys_open(template as *const u8, (O_RDWR | O_CREAT | O_EXCL) as i64, 0o600);
12520        if fd >= 0 {
12521            return fd as c_int;
12522        }
12523        let e = (-fd) as c_int;
12524        if e != EEXIST_VAL {
12525            ERRNO!() = e;
12526            return -1;
12527        }
12528    }
12529    ERRNO!() = EEXIST_VAL;
12530    -1
12531}
12532
12533#[no_mangle]
12534pub unsafe extern "C" fn mkstemp(template: *mut c_char) -> c_int {
12535    mkstemps_impl(template, 0)
12536}
12537
12538#[no_mangle]
12539pub unsafe extern "C" fn mkdir(path: *const c_char, mode: c_uint) -> c_int {
12540    let r = sys_mkdirat(AT_FDCWD, path as *const u8, mode);
12541    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12542    0
12543}
12544
12545// ============================================================
12546// libgen: basename / dirname
12547// ============================================================
12548
12549#[no_mangle]
12550pub unsafe extern "C" fn dirname(s: *mut c_char) -> *mut c_char {
12551    if s.is_null() || *s == 0 {
12552        return b".\0".as_ptr() as *mut c_char;
12553    }
12554    let mut i = strlen(s as *const c_char);
12555    i = i.wrapping_sub(1);
12556    // skip trailing slashes
12557    while i > 0 && *s.add(i) == b'/' as c_char {
12558        i = i.wrapping_sub(1);
12559    }
12560    if i == 0 && *s.add(0) == b'/' as c_char {
12561        return b"/\0".as_ptr() as *mut c_char;
12562    }
12563    // skip non-slashes
12564    while i > 0 && *s.add(i) != b'/' as c_char {
12565        i = i.wrapping_sub(1);
12566    }
12567    if i == 0 {
12568        if *s.add(0) == b'/' as c_char {
12569            return b"/\0".as_ptr() as *mut c_char;
12570        }
12571        return b".\0".as_ptr() as *mut c_char;
12572    }
12573    // skip slashes
12574    while i > 0 && *s.add(i - 1) == b'/' as c_char {
12575        i = i.wrapping_sub(1);
12576    }
12577    if i == 0 {
12578        return b"/\0".as_ptr() as *mut c_char;
12579    }
12580    *s.add(i) = 0;
12581    s
12582}
12583
12584#[no_mangle]
12585pub unsafe extern "C" fn basename(s: *mut c_char) -> *mut c_char {
12586    if s.is_null() || *s == 0 {
12587        return b".\0".as_ptr() as *mut c_char;
12588    }
12589    let mut i = strlen(s as *const c_char);
12590    i = i.wrapping_sub(1);
12591    // strip trailing slashes
12592    while i > 0 && *s.add(i) == b'/' as c_char {
12593        *s.add(i) = 0;
12594        i = i.wrapping_sub(1);
12595    }
12596    // find last slash
12597    while i > 0 && *s.add(i - 1) != b'/' as c_char {
12598        i = i.wrapping_sub(1);
12599    }
12600    s.add(i)
12601}
12602
12603// ============================================================
12604// arpa/inet: inet_pton / inet_ntop / inet_addr / inet_ntoa / inet_aton
12605// ============================================================
12606
12607const AF_INET_VAL: c_int = 2;
12608const AF_INET6_VAL: c_int = 10;
12609const EAFNOSUPPORT: c_int = 97;
12610const ENOSPC_VAL2: c_int = 28;
12611
12612unsafe fn inet_pton_v4(s: *const u8, a: *mut u8) -> c_int {
12613    let mut p = s;
12614    let mut i = 0;
12615    while i < 4 {
12616        let oct_start = p;
12617        let mut v: u32 = 0;
12618        let mut j: u32 = 0;
12619        while j < 3 && *p >= b'0' && *p <= b'9' {
12620            v = v * 10 + (*p - b'0') as u32;
12621            p = p.add(1);
12622            j += 1;
12623        }
12624        if j == 0 || (j > 1 && *oct_start == b'0') || v > 255 { return 0; }
12625        *a.add(i) = v as u8;
12626        if *p == 0 && i == 3 { return 1; }
12627        if *p != b'.' { return 0; }
12628        p = p.add(1);
12629        i += 1;
12630    }
12631    0
12632}
12633
12634unsafe fn inet_pton_v6(s: *const u8, a: *mut u8) -> c_int {
12635    let mut ip = [0u16; 8];
12636    let mut p = s;
12637    let mut i: usize = 0;
12638    let mut brk: isize = -1;
12639    let mut need_v4 = false;
12640    let mut v4_start: *const u8 = core::ptr::null();
12641
12642    if *p == b':' {
12643        p = p.add(1);
12644        if *p != b':' { return 0; }
12645    }
12646
12647    loop {
12648        if *p == b':' && brk < 0 {
12649            brk = i as isize;
12650            ip[i & 7] = 0;
12651            p = p.add(1);
12652            if *p == 0 { break; }
12653            if i == 7 { return 0; }
12654            i += 1;
12655            continue;
12656        }
12657        v4_start = p;
12658        let mut v: u16 = 0;
12659        let mut j = 0;
12660        while j < 4 {
12661            let d = hex_digit(*p);
12662            if d < 0 { break; }
12663            v = v * 16 + d as u16;
12664            p = p.add(1);
12665            j += 1;
12666        }
12667        if j == 0 { return 0; }
12668        ip[i & 7] = v;
12669        if *p == 0 && (brk >= 0 || i == 7) { break; }
12670        if i == 7 { return 0; }
12671        if *p != b':' {
12672            if *p != b'.' || (i < 6 && brk < 0) { return 0; }
12673            need_v4 = true;
12674            i += 1;
12675            ip[i & 7] = 0;
12676            break;
12677        }
12678        p = p.add(1);
12679        i += 1;
12680    }
12681
12682    if brk >= 0 {
12683        // expand :: : move trailing fields to the end and zero the gap
12684        let trail_count = i + 1 - brk as usize;
12685        let dest_start = brk as usize + 7 - i;
12686        // move backwards to avoid overwrite in the overlapping case
12687        for j in (0..trail_count).rev() {
12688            ip[dest_start + j] = ip[brk as usize + j];
12689        }
12690        for j in 0..(7 - i) {
12691            ip[brk as usize + j] = 0;
12692        }
12693    }
12694
12695    for k in 0..8 {
12696        *a.add(k * 2) = (ip[k] >> 8) as u8;
12697        *a.add(k * 2 + 1) = (ip[k] & 0xff) as u8;
12698    }
12699
12700    if need_v4 {
12701        if inet_pton_v4(v4_start, a.add(12)) <= 0 { return 0; }
12702    }
12703    1
12704}
12705
12706unsafe fn hex_digit(c: u8) -> i32 {
12707    if c >= b'0' && c <= b'9' { (c - b'0') as i32 }
12708    else if c >= b'a' && c <= b'f' { (c - b'a' + 10) as i32 }
12709    else if c >= b'A' && c <= b'F' { (c - b'A' + 10) as i32 }
12710    else { -1 }
12711}
12712
12713#[no_mangle]
12714pub unsafe extern "C" fn inet_pton(af: c_int, s: *const c_char, a: *mut c_void) -> c_int {
12715    if af == AF_INET_VAL {
12716        inet_pton_v4(s as *const u8, a as *mut u8)
12717    } else if af == AF_INET6_VAL {
12718        inet_pton_v6(s as *const u8, a as *mut u8)
12719    } else {
12720        ERRNO!() = EAFNOSUPPORT;
12721        -1
12722    }
12723}
12724
12725#[no_mangle]
12726pub unsafe extern "C" fn inet_ntop(af: c_int, a: *const c_void, s: *mut c_char, size: u32) -> *mut c_char {
12727    if af == AF_INET_VAL {
12728        let b = a as *const u8;
12729        let needed = 16; // "255.255.255.255\0"
12730        if size < needed as u32 { ERRNO!() = ENOSPC_VAL2; return core::ptr::null_mut(); }
12731        let mut pos = 0;
12732        for i in 0..4 {
12733            if i > 0 { *s.add(pos) = b'.' as c_char; pos += 1; }
12734            let (buf, len) = format_u64(*b.add(i) as u64);
12735            for j in 0..len { *s.add(pos) = buf[j] as c_char; pos += 1; }
12736        }
12737        *s.add(pos) = 0;
12738        s
12739    } else if af == AF_INET6_VAL {
12740        let b = a as *const u8;
12741        let needed = 46; // max IPv6
12742        if size < needed as u32 { ERRNO!() = ENOSPC_VAL2; return core::ptr::null_mut(); }
12743        let mut words = [0u16; 8];
12744        for i in 0..8 {
12745            words[i] = ((*b.add(i * 2) as u16) << 8) | (*b.add(i * 2 + 1) as u16);
12746        }
12747        // IPv4-mapped: ::ffff:a.b.c.d
12748        let mut pos = 0usize;
12749        if words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0
12750            && words[4] == 0 && words[5] == 0xffff
12751        {
12752            let prefix = b"::ffff:";
12753            for k in 0..prefix.len() { *s.add(pos) = prefix[k] as c_char; pos += 1; }
12754            for idx in 0..4 {
12755                if idx > 0 { *s.add(pos) = b'.' as c_char; pos += 1; }
12756                let octet = *b.add(12 + idx);
12757                if octet >= 100 {
12758                    *s.add(pos) = (b'0' + octet / 100) as c_char; pos += 1;
12759                    *s.add(pos) = (b'0' + (octet / 10) % 10) as c_char; pos += 1;
12760                } else if octet >= 10 {
12761                    *s.add(pos) = (b'0' + octet / 10) as c_char; pos += 1;
12762                }
12763                *s.add(pos) = (b'0' + octet % 10) as c_char; pos += 1;
12764            }
12765            *s.add(pos) = 0;
12766            return s;
12767        }
12768        // find longest run of zeros
12769        let mut best_start: isize = -1;
12770        let mut best_len: usize = 0;
12771        let mut j: usize = 0;
12772        while j < 8 {
12773            if words[j] == 0 {
12774                let mut k = j;
12775                while k < 8 && words[k] == 0 { k += 1; }
12776                let run = k - j;
12777                if run > best_len { best_start = j as isize; best_len = run; }
12778                j = k;
12779            } else {
12780                j += 1;
12781            }
12782        }
12783        let mut i: usize = 0;
12784        let mut prev_in_run = false;
12785        while i < 8 {
12786            let in_run = best_len >= 2 && i >= best_start as usize && i < best_start as usize + best_len;
12787            if in_run {
12788                if i == best_start as usize {
12789                    *s.add(pos) = b':' as c_char; pos += 1;
12790                    *s.add(pos) = b':' as c_char; pos += 1;
12791                }
12792                i += 1;
12793                prev_in_run = true;
12794                continue;
12795            }
12796            if i > 0 && !prev_in_run {
12797                *s.add(pos) = b':' as c_char; pos += 1;
12798            }
12799            let (buf, len) = format_hex(words[i] as u64, false);
12800            for k in 0..len { *s.add(pos) = buf[k] as c_char; pos += 1; }
12801            i += 1;
12802            prev_in_run = false;
12803        }
12804        *s.add(pos) = 0;
12805        s
12806    } else {
12807        ERRNO!() = EAFNOSUPPORT;
12808        core::ptr::null_mut()
12809    }
12810}
12811
12812#[no_mangle]
12813pub unsafe extern "C" fn inet_aton(s: *const c_char, dest: *mut c_void) -> c_int {
12814    let a = dest as *mut u8;
12815    let mut p = s as *const u8;
12816    let mut vals = [0u64; 4];
12817    let mut i = 0usize;
12818    while i < 4 {
12819        if *p < b'0' || *p > b'9' { return 0; }
12820        let mut base = 10u32;
12821        if *p == b'0' {
12822            let c = *p.add(1);
12823            if c == b'x' || c == b'X' {
12824                base = 16;
12825                p = p.add(2);
12826                if !((*p >= b'0' && *p <= b'9')
12827                    || (*p >= b'a' && *p <= b'f')
12828                    || (*p >= b'A' && *p <= b'F')) {
12829                    return 0;
12830                }
12831            } else {
12832                base = 8;
12833            }
12834        }
12835        let mut v: u64 = 0;
12836        let start = p;
12837        loop {
12838            let c = *p;
12839            let d = if c >= b'0' && c <= b'9' {
12840                (c - b'0') as u64
12841            } else if base == 16 && c >= b'a' && c <= b'f' {
12842                (c - b'a' + 10) as u64
12843            } else if base == 16 && c >= b'A' && c <= b'F' {
12844                (c - b'A' + 10) as u64
12845            } else {
12846                break;
12847            };
12848            v = v * (base as u64) + d;
12849            p = p.add(1);
12850        }
12851        if p == start { return 0; }
12852        vals[i] = v;
12853        if *p == 0 {
12854            break;
12855        }
12856        if *p != b'.' || i == 3 { return 0; }
12857        p = p.add(1);
12858        i += 1;
12859    }
12860    if i == 4 { return 0; }
12861    if i < 1 { vals[1] = vals[0] & 0xffffff; vals[0] >>= 24; }
12862    if i < 2 { vals[2] = vals[1] & 0xffff; vals[1] >>= 16; }
12863    if i < 3 { vals[3] = vals[2] & 0xff; vals[2] >>= 8; }
12864    for j in 0..4 {
12865        if vals[j] > 255 { return 0; }
12866        *a.add(j) = vals[j] as u8;
12867    }
12868    1
12869}
12870
12871#[no_mangle]
12872pub unsafe extern "C" fn inet_addr(s: *const c_char) -> u32 {
12873    let mut a = [0u8; 4];
12874    if inet_aton(s, a.as_mut_ptr() as *mut c_void) == 1 {
12875        u32::from_ne_bytes(a)
12876    } else {
12877        !0u32 // INADDR_NONE
12878    }
12879}
12880
12881#[no_mangle]
12882pub unsafe extern "C" fn inet_ntoa(addr: u32) -> *mut c_char {
12883    static mut NTOA_BUF: [c_char; 16] = [0; 16];
12884    let b = addr.to_ne_bytes();
12885    let mut pos = 0;
12886    for i in 0..4 {
12887        if i > 0 { NTOA_BUF[pos] = b'.' as c_char; pos += 1; }
12888        let (buf, len) = format_u64(b[i] as u64);
12889        for j in 0..len { NTOA_BUF[pos] = buf[j] as c_char; pos += 1; }
12890    }
12891    NTOA_BUF[pos] = 0;
12892    core::ptr::addr_of_mut!(NTOA_BUF).cast::<c_char>()
12893}
12894
12895// ponytail: inet_network/inet_makeaddr/inet_lnaof/inet_netof - simple implementations
12896#[no_mangle]
12897pub unsafe extern "C" fn inet_network(s: *const c_char) -> u32 {
12898    inet_addr(s).to_be()
12899}
12900
12901#[no_mangle]
12902pub extern "C" fn inet_makeaddr(net: c_int, host: c_int) -> u32 {
12903    let addr: u32;
12904    if (net as u32) < 128 {
12905        addr = (net as u32) << 24;
12906    } else if (net as u32) < 0x10000 {
12907        addr = (net as u32) << 16;
12908    } else if (net as u32) < 0x1000000 {
12909        addr = (net as u32) << 8;
12910    } else {
12911        addr = net as u32;
12912    }
12913    addr | (host as u32 & 0xffffffff)
12914}
12915
12916#[no_mangle]
12917pub extern "C" fn inet_lnaof(addr: u32) -> c_int {
12918    let h = u32::from_be(addr);
12919    if h < 0x80000000 { (h & 0x00ffffff) as c_int }
12920    else if h < 0xc0000000 { (h & 0x0000ffff) as c_int }
12921    else { (h & 0x000000ff) as c_int }
12922}
12923
12924#[no_mangle]
12925pub extern "C" fn inet_netof(addr: u32) -> c_int {
12926    let h = u32::from_be(addr);
12927    if h < 0x80000000 { (h >> 24) as c_int }
12928    else if h < 0xc0000000 { (h >> 16) as c_int }
12929    else { (h >> 8) as c_int }
12930}
12931
12932// ============================================================
12933// stdlib: strtod / strtof / strtold
12934// ============================================================
12935
12936// ponytail: correctly-rounded float parser.
12937// Decimal: collects digits into buffer, uses core::str::FromStr.
12938// Hex: u128 integer arithmetic with round-to-nearest-even.
12939// is_f32: true for strtof (f32::from_str), false for strtod/strtold (f64::from_str).
12940unsafe fn parse_float(s: *const u8, endptr: *mut *mut u8, is_f32: bool) -> f64 {
12941    let mut p = s;
12942    // skip whitespace
12943    while *p == b' ' || *p == b'\t' || *p == b'\n' || *p == b'\r' { p = p.add(1); }
12944    let mut neg = false;
12945    if *p == b'-' { neg = true; p = p.add(1); }
12946    else if *p == b'+' { p = p.add(1); }
12947
12948    // inf
12949    if (*p | 0x20) == b'i'
12950        && (*p.add(1) | 0x20) == b'n'
12951        && (*p.add(2) | 0x20) == b'f'
12952    {
12953        p = p.add(3);
12954        // optionally consume "inity"
12955        if (*p | 0x20) == b'i'
12956            && (*p.add(1) | 0x20) == b't'
12957            && (*p.add(2) | 0x20) == b'y'
12958        {
12959            p = p.add(3);
12960        }
12961        if !endptr.is_null() { *endptr = p as *mut u8; }
12962        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
12963    }
12964    // nan
12965    if (*p | 0x20) == b'n'
12966        && (*p.add(1) | 0x20) == b'a'
12967        && (*p.add(2) | 0x20) == b'n'
12968    {
12969        p = p.add(3);
12970        // optionally consume (n-char-sequence)
12971        if *p == b'(' {
12972            p = p.add(1);
12973            while *p != 0 && *p != b')' { p = p.add(1); }
12974            if *p == b')' { p = p.add(1); }
12975        }
12976        if !endptr.is_null() { *endptr = p as *mut u8; }
12977        return if neg { -f64::NAN } else { f64::NAN };
12978    }
12979
12980    // hex float
12981    if *p == b'0' && (*p.add(1) == b'x' || *p.add(1) == b'X') {
12982        p = p.add(2);
12983        let mut mant: u128 = 0;
12984        let mut frac_hex: u32 = 0;
12985        let mut found = false;
12986        let mut in_frac = false;
12987
12988        loop {
12989            if let Some(d) = hex_val(*p) {
12990                if mant <= u128::MAX / 16 {
12991                    mant = mant * 16 + d as u128;
12992                }
12993                if in_frac { frac_hex += 1; }
12994                p = p.add(1);
12995                found = true;
12996            } else if *p == b'.' && !in_frac {
12997                in_frac = true;
12998                p = p.add(1);
12999            } else {
13000                break;
13001            }
13002        }
13003
13004        if !found {
13005            if !endptr.is_null() { *endptr = s as *mut u8; }
13006            return 0.0;
13007        }
13008
13009        // binary exponent p[+-]N
13010        let mut bin_exp: i32 = 0;
13011        if *p == b'p' || *p == b'P' {
13012            p = p.add(1);
13013            let mut exp_neg = false;
13014            if *p == b'-' { exp_neg = true; p = p.add(1); }
13015            else if *p == b'+' { p = p.add(1); }
13016            while *p >= b'0' && *p <= b'9' {
13017                if bin_exp < 100000 {
13018                    bin_exp = bin_exp * 10 + (*p - b'0') as i32;
13019                }
13020                p = p.add(1);
13021            }
13022            if exp_neg { bin_exp = -bin_exp; }
13023        }
13024
13025        if !endptr.is_null() { *endptr = p as *mut u8; }
13026        if mant == 0 { return if neg { -0.0 } else { 0.0 }; }
13027
13028        let total_exp = bin_exp as i64 - 4 * frac_hex as i64;
13029        return hex_mant_to_f64(mant, total_exp, neg);
13030    }
13031
13032    // decimal: collect into buffer, use from_str for correct rounding
13033    let mut buf = [0u8; 65536];
13034    let mut n = 0usize;
13035    let mut found_digit = false;
13036
13037    while *p >= b'0' && *p <= b'9' {
13038        if n < 65535 { buf[n] = *p; n += 1; }
13039        p = p.add(1);
13040        found_digit = true;
13041    }
13042    if *p == b'.' {
13043        if n < 65535 { buf[n] = b'.'; n += 1; }
13044        p = p.add(1);
13045        while *p >= b'0' && *p <= b'9' {
13046            if n < 65535 { buf[n] = *p; n += 1; }
13047            p = p.add(1);
13048            found_digit = true;
13049        }
13050    }
13051    if !found_digit {
13052        if !endptr.is_null() { *endptr = s as *mut u8; }
13053        return 0.0;
13054    }
13055    if *p == b'e' || *p == b'E' {
13056        if n < 65535 { buf[n] = b'e'; n += 1; }
13057        p = p.add(1);
13058        if *p == b'-' || *p == b'+' {
13059            if n < 65535 { buf[n] = *p; n += 1; }
13060            p = p.add(1);
13061        }
13062        while *p >= b'0' && *p <= b'9' {
13063            if n < 65535 { buf[n] = *p; n += 1; }
13064            p = p.add(1);
13065        }
13066    }
13067
13068    if !endptr.is_null() { *endptr = p as *mut u8; }
13069    let s_str = core::str::from_utf8_unchecked(
13070        core::slice::from_raw_parts(buf.as_ptr(), n),
13071    );
13072    if is_f32 {
13073        match <f32 as core::str::FromStr>::from_str(s_str) {
13074            Ok(v) => { let r = v as f64; if neg { -r } else { r } }
13075            Err(_) => { if !endptr.is_null() { *endptr = s as *mut u8; } 0.0 }
13076        }
13077    } else {
13078        match <f64 as core::str::FromStr>::from_str(s_str) {
13079            Ok(v) => if neg { -v } else { v },
13080            Err(_) => { if !endptr.is_null() { *endptr = s as *mut u8; } 0.0 }
13081        }
13082    }
13083}
13084
13085// Convert hex mantissa integer to f64 with correct rounding.
13086// mant: integer from parsed hex digits. total_exp: bin_exp - 4 * frac_hex_digits.
13087// Value = mant * 2^total_exp.
13088fn hex_mant_to_f64(mant: u128, total_exp: i64, neg: bool) -> f64 {
13089    if mant == 0 { return if neg { -0.0 } else { 0.0 }; }
13090
13091    let msb = (127 - mant.leading_zeros()) as i64;
13092    let unbiased_exp = msb + total_exp;
13093    let biased_exp = unbiased_exp + 1023;
13094
13095    // Overflow → infinity
13096    if biased_exp >= 2047 {
13097        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13098    }
13099
13100    // Subnormal or underflow
13101    if biased_exp <= 0 {
13102        // subnormal: biased_exp=0, effective exponent=-1022
13103        // mantissa = round(mant * 2^(total_exp + 1074))
13104        let shift = total_exp + 1074;
13105        if shift < 0 {
13106            return if neg { -0.0 } else { 0.0 };
13107        }
13108        if shift > 128 {
13109            return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13110        }
13111        let shifted = mant << (shift as u32);
13112        let mantissa52 = (shifted as u64) & 0x000FFFFFFFFFFFFF;
13113        let guard = ((shifted >> 52) & 1) != 0;
13114        let sticky = (shifted >> 53) != 0;
13115        let mut result = mantissa52;
13116        if guard && (sticky || (result & 1) != 0) {
13117            result += 1;
13118            if result > 0x000FFFFFFFFFFFFF {
13119                // carry → smallest normal
13120                return if neg { -f64::from_bits(1u64 << 52) } else { f64::from_bits(1u64 << 52) };
13121            }
13122        }
13123        return if neg { -f64::from_bits(result) } else { f64::from_bits(result) };
13124    }
13125
13126    // Normal: biased_exp in [1, 2046]
13127    let shift = msb - 52;
13128
13129    if shift <= 0 {
13130        // fewer than 53 bits, no rounding needed
13131        let mantissa = ((mant as u64) & ((1u64 << msb as u32) - 1)) << ((-shift) as u32);
13132        let bits = ((biased_exp as u64) << 52) | mantissa;
13133        return if neg { -f64::from_bits(bits) } else { f64::from_bits(bits) };
13134    }
13135
13136    // shift > 0: round to nearest even
13137    let mantissa = ((mant >> shift as u32) as u64) & 0x000FFFFFFFFFFFFF;
13138    let guard = ((mant >> (shift as u32 - 1)) & 1) != 0;
13139    let sticky = if shift > 1 {
13140        (mant & ((1u128 << (shift as u32 - 1)) - 1)) != 0
13141    } else { false };
13142
13143    let mut result_mant = mantissa;
13144    let mut result_exp = biased_exp;
13145    if guard && (sticky || (result_mant & 1) != 0) {
13146        result_mant += 1;
13147        if result_mant > 0x000FFFFFFFFFFFFF {
13148            result_mant = 0;
13149            result_exp += 1;
13150            if result_exp >= 2047 {
13151                return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13152            }
13153        }
13154    }
13155
13156    let bits = ((result_exp as u64) << 52) | result_mant;
13157    if neg { -f64::from_bits(bits) } else { f64::from_bits(bits) }
13158}
13159
13160unsafe fn hex_val(c: u8) -> Option<u8> {
13161    if c >= b'0' && c <= b'9' { Some(c - b'0') }
13162    else if c >= b'a' && c <= b'f' { Some(c - b'a' + 10) }
13163    else if c >= b'A' && c <= b'F' { Some(c - b'A' + 10) }
13164    else { None }
13165}
13166
13167#[no_mangle]
13168pub unsafe extern "C" fn strtod(s: *const c_char, endptr: *mut *mut c_char) -> f64 {
13169    let mut end: *mut u8 = s as *mut u8;
13170    let r = parse_float(s as *const u8, &mut end, false);
13171    if !endptr.is_null() { *endptr = end as *mut c_char; }
13172    r
13173}
13174
13175#[no_mangle]
13176pub unsafe extern "C" fn strtof(s: *const c_char, endptr: *mut *mut c_char) -> f32 {
13177    let mut end: *mut u8 = s as *mut u8;
13178    let r = parse_float(s as *const u8, &mut end, true);
13179    if !endptr.is_null() { *endptr = end as *mut c_char; }
13180    r as f32
13181}
13182
13183#[no_mangle]
13184#[cfg(target_arch = "x86_64")]
13185pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f64 {
13186    strtod(s, endptr)
13187}
13188
13189#[no_mangle]
13190#[cfg(target_arch = "aarch64")]
13191pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f128 {
13192    strtod(s, endptr) as f128
13193}
13194
13195#[no_mangle]
13196#[cfg(target_arch = "riscv64")]
13197pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f128 {
13198    strtod(s, endptr) as f128
13199}
13200
13201#[no_mangle]
13202pub unsafe extern "C" fn atof(s: *const c_char) -> f64 {
13203    strtod(s, core::ptr::null_mut())
13204}
13205
13206// ============================================================
13207// stdio: open_memstream / fmemopen
13208// ============================================================
13209
13210#[repr(C)]
13211struct MsCookie {
13212    bufp: *mut *mut c_char,
13213    sizep: *mut usize,
13214    pos: usize,
13215    len: usize,
13216    buf: *mut u8,
13217    space: usize,
13218}
13219
13220#[repr(C)]
13221struct MfCookie {
13222    pos: usize,
13223    len: usize,
13224    size: usize,
13225    buf: *mut u8,
13226    mode: c_char,
13227}
13228
13229unsafe extern "C" fn ms_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
13230    let c = (*f).cookie as *mut MsCookie;
13231    if whence < 0 || whence > 2 { ERRNO!() = EINVAL; return -1; }
13232    let base: i64 = match whence {
13233        0 => 0,
13234        1 => (*c).pos as i64,
13235        2 => (*c).len as i64,
13236        _ => { ERRNO!() = EINVAL; return -1; }
13237    };
13238    if off < -base || off > isize::MAX as i64 - base { ERRNO!() = EINVAL; return -1; }
13239    (*c).pos = (base + off) as usize;
13240    (*c).pos as i64
13241}
13242
13243unsafe extern "C" fn ms_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
13244    let c = (*f).cookie as *mut MsCookie;
13245    let buffered = (*f).wpos as usize - (*f).wbase as usize;
13246    if buffered > 0 {
13247        (*f).wpos = (*f).wbase;
13248        if ms_write(f, (*f).wbase, buffered) < buffered { return 0; }
13249    }
13250    if len == 0 { return 0; }
13251    if (*c).pos + len >= (*c).space {
13252        let new_space = 2 * (*c).space + 1 | (*c).pos + len + 1;
13253        let newbuf = realloc((*c).buf as *mut c_void, new_space) as *mut u8;
13254        if newbuf.is_null() { return 0; }
13255        *(*c).bufp = newbuf as *mut c_char;
13256        core::ptr::write_bytes(newbuf.add((*c).space), 0, new_space - (*c).space);
13257        (*c).buf = newbuf;
13258        (*c).space = new_space;
13259    }
13260    core::ptr::copy_nonoverlapping(buf, (*c).buf.add((*c).pos), len);
13261    (*c).pos += len;
13262    if (*c).pos >= (*c).len { (*c).len = (*c).pos; }
13263    *(*c).sizep = (*c).pos;
13264    len
13265}
13266
13267unsafe extern "C" fn ms_close(_f: *mut FILE) -> c_int {
13268    0
13269}
13270
13271#[no_mangle]
13272pub unsafe extern "C" fn open_memstream(bufp: *mut *mut c_char, sizep: *mut usize) -> *mut FILE {
13273    if bufp.is_null() || sizep.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
13274    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
13275    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13276    let buf_area = buf_ptr(f);
13277    init_file(f, -1, b"w\0".as_ptr() as *const c_char, Some(ms_close), buf_area, BUFSIZ);
13278    (*f).flags = F_NORD | F_SVB;
13279    (*f).lbf = -1;
13280    let c = calloc(1, core::mem::size_of::<MsCookie>()) as *mut MsCookie;
13281    if c.is_null() { free(f as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13282    (*c).bufp = bufp;
13283    (*c).sizep = sizep;
13284    (*c).pos = 0;
13285    (*c).len = 0;
13286    (*c).buf = core::ptr::null_mut();
13287    (*c).space = 0;
13288    (*f).cookie = c as *mut c_void;
13289    (*f).write_fn = Some(ms_write);
13290    (*f).seek_fn = Some(ms_seek);
13291    *bufp = core::ptr::null_mut();
13292    *sizep = 0;
13293    f
13294}
13295
13296unsafe extern "C" fn mseek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
13297    let c = (*f).cookie as *mut MfCookie;
13298    if whence < 0 || whence > 2 { ERRNO!() = EINVAL; return -1; }
13299    let base: i64 = match whence {
13300        0 => 0,
13301        1 => (*c).pos as i64,
13302        2 => (*c).len as i64,
13303        _ => { ERRNO!() = EINVAL; return -1; }
13304    };
13305    if off < -base || off > (*c).size as i64 - base { ERRNO!() = EINVAL; return -1; }
13306    (*c).pos = (base + off) as usize;
13307    (*c).pos as i64
13308}
13309
13310unsafe extern "C" fn mread(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
13311    let c = (*f).cookie as *mut MfCookie;
13312    let mut rem = if (*c).pos <= (*c).len { (*c).len - (*c).pos } else { 0 };
13313    let mut l = len;
13314    if l > rem {
13315        l = rem;
13316        (*f).flags |= F_EOF;
13317    }
13318    core::ptr::copy_nonoverlapping((*c).buf.add((*c).pos), buf, l);
13319    (*c).pos += l;
13320    rem -= l;
13321    if rem > (*f).buf_size { rem = (*f).buf_size; }
13322    (*f).rpos = (*f).buf;
13323    (*f).rend = (*f).buf.add(rem);
13324    core::ptr::copy_nonoverlapping((*c).buf.add((*c).pos), (*f).rpos, rem);
13325    (*c).pos += rem;
13326    l
13327}
13328
13329unsafe extern "C" fn mwrite(f: *mut FILE, buf: *const u8, len: usize) -> usize {
13330    let c = (*f).cookie as *mut MfCookie;
13331    let buffered = (*f).wpos as usize - (*f).wbase as usize;
13332    if buffered > 0 {
13333        (*f).wpos = (*f).wbase;
13334        if mwrite(f, (*f).wbase, buffered) < buffered { return 0; }
13335    }
13336    if len == 0 { return 0; }
13337    if (*c).mode == b'a' as c_char { (*c).pos = (*c).len; }
13338    let rem = (*c).size - (*c).pos;
13339    let mut l = len;
13340    if l > rem { l = rem; }
13341    core::ptr::copy_nonoverlapping(buf, (*c).buf.add((*c).pos), l);
13342    (*c).pos += l;
13343    if (*c).pos > (*c).len {
13344        (*c).len = (*c).pos;
13345        if (*c).len < (*c).size {
13346            *(*c).buf.add((*c).len) = 0;
13347        } else if ((*f).flags & F_NORD) != 0 && (*c).size > 0 {
13348            *(*c).buf.add((*c).size - 1) = 0;
13349        }
13350    }
13351    l
13352}
13353
13354unsafe extern "C" fn mclose(_f: *mut FILE) -> c_int {
13355    0
13356}
13357
13358#[no_mangle]
13359pub unsafe extern "C" fn fmemopen(buf: *mut c_void, size: usize, mode: *const c_char) -> *mut FILE {
13360    if mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
13361    let m = *mode;
13362    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
13363        ERRNO!() = EINVAL; return core::ptr::null_mut();
13364    }
13365    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
13366    let need_alloc = buf.is_null();
13367    let alloc_size = core::mem::size_of::<FILE>() + UNGET + BUFSIZ + if need_alloc { size } else { 0 };
13368    let f = calloc(1, alloc_size) as *mut FILE;
13369    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13370    let buf_area = buf_ptr(f);
13371    init_file(f, -1, mode, Some(mclose), buf_area, BUFSIZ);
13372    (*f).flags |= F_SVB;
13373    let actual_buf: *mut u8 = if need_alloc {
13374        (f as *mut u8).add(alloc_size - size)
13375    } else {
13376        buf as *mut u8
13377    };
13378    if need_alloc { core::ptr::write_bytes(actual_buf, 0, size); }
13379    let c = calloc(1, core::mem::size_of::<MfCookie>()) as *mut MfCookie;
13380    if c.is_null() { free(f as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13381    (*c).buf = actual_buf;
13382    (*c).size = size;
13383    (*c).mode = m;
13384    (*f).cookie = c as *mut c_void;
13385    (*f).read_fn = Some(mread);
13386    (*f).write_fn = Some(mwrite);
13387    (*f).seek_fn = Some(mseek);
13388    if !has_plus { (*f).flags = if m == b'r' as c_char { F_NOWR } else { F_NORD }; }
13389    if m == b'r' as c_char {
13390        (*c).len = size;
13391    } else if m == b'a' as c_char {
13392        (*c).len = strnlen(actual_buf, size);
13393        (*c).pos = (*c).len;
13394    } else if has_plus {
13395        *actual_buf = 0;
13396    }
13397    f
13398}
13399
13400// ============================================================
13401// Stat (for ftok)
13402// ============================================================
13403
13404#[repr(C)]
13405struct kernel_stat64 {
13406    st_dev: u64,
13407    st_ino: u64,
13408    st_nlink: u64,
13409    st_mode: u32,
13410    st_uid: u32,
13411    st_gid: u32,
13412    __pad0: c_int,
13413    st_rdev: u64,
13414    st_size: i64,
13415    st_blksize: i64,
13416    st_blocks: i64,
13417    st_atime: i64,
13418    st_atime_nsec: i64,
13419    st_mtime: i64,
13420    st_mtime_nsec: i64,
13421    st_ctime: i64,
13422    st_ctime_nsec: i64,
13423    __unused: [i64; 3],
13424}
13425
13426// sys_stat = 4 on x86_64
13427#[inline]
13428unsafe fn sys_stat(path: *const u8, statbuf: *mut kernel_stat64) -> i64 {
13429    <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, statbuf as i64, 0)
13430}
13431
13432// ============================================================
13433// Search: hcreate/hdestroy/hsearch (hash table)
13434// ============================================================
13435
13436const HSEARCH_MINSIZE: usize = 8;
13437
13438#[repr(C)]
13439#[derive(Copy, Clone)]
13440pub struct HSearchEntry {
13441    key: *mut c_char,
13442    data: *mut c_void,
13443}
13444
13445#[repr(C)]
13446struct HTab {
13447    entries: *mut HSearchEntry,
13448    mask: usize,
13449    used: usize,
13450}
13451
13452#[repr(C)]
13453pub struct HSearchData {
13454    tab: *mut HTab,
13455    __unused1: c_uint,
13456    __unused2: c_uint,
13457}
13458
13459// ponytail: single static hash table for non-_r variants
13460static mut HTAB_DATA: HSearchData = HSearchData {
13461    tab: core::ptr::null_mut(),
13462    __unused1: 0,
13463    __unused2: 0,
13464};
13465
13466unsafe fn keyhash(k: *const c_char) -> usize {
13467    let mut h: usize = 0;
13468    let mut p = k;
13469    while *p != 0 {
13470        h = h.wrapping_mul(31).wrapping_add(*p as usize);
13471        p = p.add(1);
13472    }
13473    h
13474}
13475
13476unsafe fn htab_lookup(key: *const c_char, hash: usize, htab: *mut HSearchData) -> *mut HSearchEntry {
13477    let tab = (*htab).tab;
13478    let mask = (*tab).mask;
13479    let entries = (*tab).entries;
13480    let mut i = hash;
13481    let mut j: usize = 1;
13482    loop {
13483        let e = entries.add(i & mask);
13484        if (*e).key.is_null() || strcmp((*e).key as *const u8, key as *const u8) == 0 {
13485            return e;
13486        }
13487        i = i.wrapping_add(j);
13488        j += 1;
13489    }
13490}
13491
13492unsafe fn htab_resize(nel: usize, htab: *mut HSearchData) -> c_int {
13493    let tab = (*htab).tab;
13494    let old_entries = (*tab).entries;
13495    let old_size = (*tab).mask + 1;
13496
13497    let mut newsize: usize = HSEARCH_MINSIZE;
13498    while newsize < nel {
13499        let Some(next) = newsize.checked_mul(2) else {
13500            ERRNO!() = ENOMEM;
13501            return 0;
13502        };
13503        newsize = next;
13504    }
13505
13506    let new_entries = calloc(newsize, core::mem::size_of::<HSearchEntry>()) as *mut HSearchEntry;
13507    if new_entries.is_null() {
13508        ERRNO!() = ENOMEM;
13509        return 0;
13510    }
13511    (*tab).entries = new_entries;
13512    (*tab).mask = newsize - 1;
13513
13514    if !old_entries.is_null() {
13515        for idx in 0..old_size {
13516            let old_e = old_entries.add(idx);
13517            if !(*old_e).key.is_null() {
13518                let h = keyhash((*old_e).key);
13519                let mut i = h;
13520                let mut j: usize = 1;
13521                loop {
13522                    let e = new_entries.add(i & (*tab).mask);
13523                    if (*e).key.is_null() {
13524                        *e = *old_e;
13525                        break;
13526                    }
13527                    i = i.wrapping_add(j);
13528                    j += 1;
13529                }
13530            }
13531        }
13532        free(old_entries as *mut c_void);
13533    }
13534    1
13535}
13536
13537unsafe fn hcreate_r_impl(nel: usize, htab: *mut HSearchData) -> c_int {
13538    if nel == 0 || nel > (1usize << 30) {
13539        ERRNO!() = ENOMEM;
13540        return 0;
13541    }
13542    (*htab).tab = calloc(1, core::mem::size_of::<HTab>()) as *mut HTab;
13543    if (*htab).tab.is_null() {
13544        ERRNO!() = ENOMEM;
13545        return 0;
13546    }
13547    if htab_resize(nel, htab) == 0 {
13548        free((*htab).tab as *mut c_void);
13549        (*htab).tab = core::ptr::null_mut();
13550        return 0;
13551    }
13552    1
13553}
13554
13555unsafe fn hdestroy_r_impl(htab: *mut HSearchData) {
13556    if !(*htab).tab.is_null() {
13557        if !(*(*htab).tab).entries.is_null() {
13558            free((*(*htab).tab).entries as *mut c_void);
13559        }
13560        free((*htab).tab as *mut c_void);
13561        (*htab).tab = core::ptr::null_mut();
13562    }
13563}
13564
13565unsafe fn hsearch_r_impl(item: HSearchEntry, action: c_int, retval: *mut *mut HSearchEntry, htab: *mut HSearchData) -> c_int {
13566    let hash = keyhash(item.key);
13567    let e = htab_lookup(item.key, hash, htab);
13568
13569    if !(*e).key.is_null() {
13570        *retval = e;
13571        return 1;
13572    }
13573    if action == 0 { // FIND
13574        *retval = core::ptr::null_mut();
13575        return 0;
13576    }
13577    // ENTER
13578    let item_key = item.key;
13579    *e = item;
13580    (*(*htab).tab).used += 1;
13581    if (*(*htab).tab).used > (*(*htab).tab).mask - (*(*htab).tab).mask / 4 {
13582        if htab_resize(2 * (*(*htab).tab).used, htab) == 0 {
13583            (*(*htab).tab).used -= 1;
13584            (*e).key = core::ptr::null_mut();
13585            *retval = core::ptr::null_mut();
13586            return 0;
13587        }
13588        let e2 = htab_lookup(item_key, hash, htab);
13589        *retval = e2;
13590        return 1;
13591    }
13592    *retval = e;
13593    1
13594}
13595
13596#[no_mangle]
13597pub unsafe extern "C" fn hcreate(nel: usize) -> c_int {
13598    hcreate_r_impl(nel, core::ptr::addr_of_mut!(HTAB_DATA))
13599}
13600
13601#[no_mangle]
13602pub unsafe extern "C" fn hdestroy() {
13603    hdestroy_r_impl(core::ptr::addr_of_mut!(HTAB_DATA));
13604}
13605
13606#[no_mangle]
13607pub unsafe extern "C" fn hsearch(item: HSearchEntry, action: c_int) -> *mut HSearchEntry {
13608    let mut e: *mut HSearchEntry = core::ptr::null_mut();
13609    hsearch_r_impl(item, action, &mut e, core::ptr::addr_of_mut!(HTAB_DATA));
13610    e
13611}
13612
13613#[no_mangle]
13614pub unsafe extern "C" fn hcreate_r(nel: usize, htab: *mut HSearchData) -> c_int {
13615    hcreate_r_impl(nel, htab)
13616}
13617
13618#[no_mangle]
13619pub unsafe extern "C" fn hdestroy_r(htab: *mut HSearchData) {
13620    hdestroy_r_impl(htab);
13621}
13622
13623#[no_mangle]
13624pub unsafe extern "C" fn hsearch_r(item: HSearchEntry, action: c_int, retval: *mut *mut HSearchEntry, htab: *mut HSearchData) -> c_int {
13625    hsearch_r_impl(item, action, retval, htab)
13626}
13627
13628// ============================================================
13629// Search: insque / remque
13630// ============================================================
13631
13632#[repr(C)]
13633struct QueNode {
13634    next: *mut QueNode,
13635    prev: *mut QueNode,
13636}
13637
13638#[no_mangle]
13639pub unsafe extern "C" fn insque(element: *mut c_void, pred: *mut c_void) {
13640    let e = element as *mut QueNode;
13641    let p = pred as *mut QueNode;
13642    if p.is_null() {
13643        (*e).next = core::ptr::null_mut();
13644        (*e).prev = core::ptr::null_mut();
13645        return;
13646    }
13647    (*e).next = (*p).next;
13648    (*e).prev = p;
13649    (*p).next = e;
13650    if !(*e).next.is_null() {
13651        (*(*e).next).prev = e;
13652    }
13653}
13654
13655#[no_mangle]
13656pub unsafe extern "C" fn remque(element: *mut c_void) {
13657    let e = element as *mut QueNode;
13658    if !(*e).next.is_null() {
13659        (*(*e).next).prev = (*e).prev;
13660    }
13661    if !(*e).prev.is_null() {
13662        (*(*e).prev).next = (*e).next;
13663    }
13664}
13665
13666// ============================================================
13667// Search: lsearch / lfind
13668// ============================================================
13669
13670#[no_mangle]
13671pub unsafe extern "C" fn lsearch(
13672    key: *const c_void,
13673    base: *mut c_void,
13674    nelp: *mut usize,
13675    width: usize,
13676    compar: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
13677) -> *mut c_void {
13678    let n = *nelp;
13679    let p = base as *mut u8;
13680    for i in 0..n {
13681        let elem = p.add(i * width);
13682        if compar.unwrap()(key, elem as *const c_void) == 0 {
13683            return elem as *mut c_void;
13684        }
13685    }
13686    let dest = p.add(n * width);
13687    memcpy(dest as *mut c_void, key as *const c_void, width);
13688    *nelp = n + 1;
13689    dest as *mut c_void
13690}
13691
13692#[no_mangle]
13693pub unsafe extern "C" fn lfind(
13694    key: *const c_void,
13695    base: *const c_void,
13696    nelp: *mut usize,
13697    width: usize,
13698    compar: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
13699) -> *mut c_void {
13700    let n = *nelp;
13701    let p = base as *const u8;
13702    for i in 0..n {
13703        let elem = p.add(i * width);
13704        if compar.unwrap()(key, elem as *const c_void) == 0 {
13705            return elem as *mut c_void;
13706        }
13707    }
13708    core::ptr::null_mut()
13709}
13710
13711// ============================================================
13712// Search: tsearch / tfind / tdelete / twalk / tdestroy (BST, no balancing)
13713// ============================================================
13714
13715// ponytail: simple BST, no balancing; correct for tests, O(n) worst case
13716#[repr(C)]
13717pub struct TreeNode {
13718    key: *const c_void,
13719    left: *mut TreeNode,
13720    right: *mut TreeNode,
13721}
13722
13723type ComparFn = Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>;
13724
13725unsafe fn bst_new(key: *const c_void) -> *mut TreeNode {
13726    let n = calloc(1, core::mem::size_of::<TreeNode>()) as *mut TreeNode;
13727    if !n.is_null() {
13728        (*n).key = key;
13729        (*n).left = core::ptr::null_mut();
13730        (*n).right = core::ptr::null_mut();
13731    }
13732    n
13733}
13734
13735#[no_mangle]
13736pub unsafe extern "C" fn tsearch(
13737    key: *const c_void,
13738    rootp: *mut *mut TreeNode,
13739    compar: ComparFn,
13740) -> *mut c_void {
13741    if rootp.is_null() {
13742        return core::ptr::null_mut();
13743    }
13744    let mut pp = rootp;
13745    loop {
13746        let n = *pp;
13747        if n.is_null() {
13748            let r = bst_new(key);
13749            if r.is_null() {
13750                return core::ptr::null_mut();
13751            }
13752            *pp = r;
13753            return r as *mut c_void;
13754        }
13755        let c = compar.unwrap()(key, (*n).key);
13756        if c == 0 {
13757            return n as *mut c_void;
13758        }
13759        if c < 0 {
13760            pp = &mut (*n).left;
13761        } else {
13762            pp = &mut (*n).right;
13763        }
13764    }
13765}
13766
13767#[no_mangle]
13768pub unsafe extern "C" fn tfind(
13769    key: *const c_void,
13770    rootp: *const *mut TreeNode,
13771    compar: ComparFn,
13772) -> *mut c_void {
13773    if rootp.is_null() {
13774        return core::ptr::null_mut();
13775    }
13776    let mut n = *rootp;
13777    loop {
13778        if n.is_null() {
13779            return core::ptr::null_mut();
13780        }
13781        let c = compar.unwrap()(key, (*n).key);
13782        if c == 0 {
13783            return n as *mut c_void;
13784        }
13785        if c < 0 {
13786            n = (*n).left;
13787        } else {
13788            n = (*n).right;
13789        }
13790    }
13791}
13792
13793#[no_mangle]
13794pub unsafe extern "C" fn tdelete(
13795    key: *const c_void,
13796    rootp: *mut *mut TreeNode,
13797    compar: ComparFn,
13798) -> *mut c_void {
13799    if rootp.is_null() {
13800        return core::ptr::null_mut();
13801    }
13802    let mut pp = rootp;
13803    loop {
13804        let n = *pp;
13805        if n.is_null() {
13806            return core::ptr::null_mut();
13807        }
13808        let c = compar.unwrap()(key, (*n).key);
13809        if c == 0 {
13810            break;
13811        }
13812        if c < 0 {
13813            pp = &mut (*n).left;
13814        } else {
13815            pp = &mut (*n).right;
13816        }
13817    }
13818    let n = *pp;
13819    // parent is *rootp if we went to root, otherwise the node above
13820    let parent = *rootp;
13821    if !(*n).left.is_null() {
13822        // replace with in-order predecessor
13823        let mut q = &mut (*n).left;
13824        while !(*(*q)).right.is_null() {
13825            q = &mut (*(*q)).right;
13826        }
13827        let pred = *q;
13828        // swap keys
13829        (*n).key = (*pred).key;
13830        // remove predecessor
13831        *q = (*pred).left;
13832        free(pred as *mut c_void);
13833    } else {
13834        // replace with right child (may be null)
13835        *pp = (*n).right;
13836        free(n as *mut c_void);
13837    }
13838    parent as *mut c_void
13839}
13840
13841#[no_mangle]
13842pub unsafe extern "C" fn twalk(
13843    root: *const TreeNode,
13844    action: Option<unsafe extern "C" fn(*const c_void, c_int, c_int)>,
13845) {
13846    unsafe fn walk(
13847        node: *const TreeNode,
13848        action: Option<unsafe extern "C" fn(*const c_void, c_int, c_int)>,
13849        depth: c_int,
13850    ) {
13851        if node.is_null() {
13852            return;
13853        }
13854        let is_leaf = (*node).left.is_null() && (*node).right.is_null();
13855        if is_leaf {
13856            action.unwrap()(node as *const c_void, 3, depth); // leaf
13857        } else {
13858            action.unwrap()(node as *const c_void, 0, depth); // preorder
13859            walk((*node).left, action, depth + 1);
13860            action.unwrap()(node as *const c_void, 1, depth); // postorder (left done)
13861            walk((*node).right, action, depth + 1);
13862            action.unwrap()(node as *const c_void, 2, depth); // endorder
13863        }
13864    }
13865    walk(root, action, 0);
13866}
13867
13868#[no_mangle]
13869pub unsafe extern "C" fn tdestroy(root: *mut TreeNode, freekey: Option<unsafe extern "C" fn(*mut c_void)>) {
13870    if root.is_null() {
13871        return;
13872    }
13873    tdestroy((*root).left, freekey);
13874    tdestroy((*root).right, freekey);
13875    if let Some(f) = freekey {
13876        f((*root).key as *mut c_void);
13877    }
13878    free(root as *mut c_void);
13879}
13880
13881// ============================================================
13882// fnmatch: full POSIX pattern matching
13883// ============================================================
13884
13885const FNM_PATHNAME: c_int = 0x1;
13886const FNM_NOESCAPE: c_int = 0x2;
13887const FNM_PERIOD: c_int = 0x4;
13888const FNM_LEADING_DIR: c_int = 0x8;
13889const FNM_CASEFOLD: c_int = 0x10;
13890const FNM_NOMATCH: c_int = 1;
13891
13892const FNM_END: c_int = 0;
13893const FNM_STAR: c_int = -5;
13894const FNM_QUESTION: c_int = -4;
13895const FNM_BRACKET: c_int = -3;
13896const FNM_UNMATCHABLE: c_int = -2;
13897
13898fn ascii_tolower(c: u8) -> u8 {
13899    if c >= b'A' && c <= b'Z' { c + 32 } else { c }
13900}
13901
13902fn ascii_toupper(c: u8) -> u8 {
13903    if c >= b'a' && c <= b'z' { c - 32 } else { c }
13904}
13905
13906fn ascii_casefold(k: u8) -> u8 {
13907    let upper = ascii_toupper(k);
13908    if upper != k { upper } else { ascii_tolower(k) }
13909}
13910
13911/// Get next byte from pattern, classifying it.
13912/// Returns (token_type, bytes_consumed).
13913unsafe fn pat_next(pat: *const u8, m: usize, flags: c_int) -> (c_int, usize) {
13914    if m == 0 || *pat == 0 {
13915        return (FNM_END, 0);
13916    }
13917    let mut p = pat;
13918    let mut step = 1usize;
13919    let mut esc = false;
13920    if *p == b'\\' && !(flags & FNM_NOESCAPE != 0) && *p.add(1) != 0 {
13921        p = p.add(1);
13922        step = 2;
13923        esc = true;
13924    }
13925    if *p == b'[' && !esc {
13926        // scan for matching ]
13927        let mut k = 1usize;
13928        if k < m && (*pat.add(k) == b'^' || *pat.add(k) == b'!') { k += 1; }
13929        if k < m && *pat.add(k) == b']' { k += 1; }
13930        while k < m && *pat.add(k) != 0 && *pat.add(k) != b']' {
13931            if k + 1 < m && *pat.add(k) == b'[' &&
13932               (*pat.add(k+1) == b':' || *pat.add(k+1) == b'.' || *pat.add(k+1) == b'=') {
13933                let z = *pat.add(k+1);
13934                k += 2;
13935                if k < m { k += 1; }
13936                while k < m && *pat.add(k) != 0 && (*pat.add(k-1) != z || *pat.add(k) != b']') { k += 1; }
13937                if k == m || *pat.add(k) == 0 { break; }
13938            }
13939            k += 1;
13940        }
13941        if k == m || *pat.add(k) == 0 {
13942            // unmatched [ is literal
13943            return (b'[' as c_int, 1);
13944        }
13945        return (FNM_BRACKET, k + 1);
13946    }
13947    if *p == b'*' && !esc {
13948        return (FNM_STAR, 1);
13949    }
13950    if *p == b'?' && !esc {
13951        return (FNM_QUESTION, 1);
13952    }
13953    (*p as c_int, step)
13954}
13955
13956unsafe fn match_class(name: &[u8], k: u8, kfold: u8) -> bool {
13957    let eq = |c: u8| k == c || kfold == c;
13958    let in_range = |lo: u8, hi: u8| (k >= lo && k <= hi) || (kfold >= lo && kfold <= hi);
13959    match name {
13960        b"alnum" => in_range(b'0', b'9') || in_range(b'A', b'Z') || in_range(b'a', b'z'),
13961        b"alpha" => in_range(b'A', b'Z') || in_range(b'a', b'z'),
13962        b"blank" => eq(b' ') || eq(b'\t'),
13963        b"cntrl" => k < 0x20 || k == 0x7f,
13964        b"digit" => in_range(b'0', b'9'),
13965        b"graph" => k >= 0x21 && k <= 0x7e,
13966        b"lower" => in_range(b'a', b'z'),
13967        b"print" => k >= 0x20 && k <= 0x7e,
13968        b"punct" =>
13969            (k >= 0x21 && k <= 0x2f) ||
13970            (k >= 0x3a && k <= 0x40) ||
13971            (k >= 0x5b && k <= 0x60) ||
13972            (k >= 0x7b && k <= 0x7e),
13973        b"space" => eq(b' ') || eq(b'\t') || eq(b'\n') || eq(b'\r') || eq(0x0c) || eq(0x0b),
13974        b"upper" => in_range(b'A', b'Z'),
13975        b"xdigit" => in_range(b'0', b'9') || in_range(b'A', b'F') || in_range(b'a', b'f'),
13976        _ => false,
13977    }
13978}
13979
13980/// Match a bracket expression [class] against char k.
13981unsafe fn match_bracket(mut p: *const u8, k: u8, kfold: u8) -> bool {
13982    let mut inv = false;
13983    p = p.add(1); // skip [
13984    if *p == b'^' || *p == b'!' {
13985        inv = true;
13986        p = p.add(1);
13987    }
13988    // handle ] as first char
13989    if *p == b']' {
13990        if k == b']' { return !inv; }
13991        p = p.add(1);
13992    } else if *p == b'-' {
13993        if k == b'-' { return !inv; }
13994        p = p.add(1);
13995    }
13996    while *p != b']' && *p != 0 {
13997        if *p == b'-' && *p.add(1) != b']' && *p.add(1) != 0 {
13998            // range: previous char to next char
13999            let lo = *p.sub(1);
14000            let hi = *p.add(1);
14001            if lo <= hi && (k >= lo && k <= hi || kfold >= lo && kfold <= hi) {
14002                return !inv;
14003            }
14004            p = p.add(2);
14005        } else if *p == b'[' && (*p.add(1) == b':' || *p.add(1) == b'.' || *p.add(1) == b'=') {
14006            let z = *p.add(1);
14007            let start = p.add(2);
14008            let mut q = start;
14009            while *q != 0 && (*q != z || *q.add(1) != b']') { q = q.add(1); }
14010            if *q != 0 {
14011                let len = (q as usize) - (start as usize);
14012                if len > 0 {
14013                    let inner = core::slice::from_raw_parts(start, len);
14014                    let matched =
14015                        if z == b':' { match_class(inner, k, kfold) }
14016                        else { len == 1 && (inner[0] == k || inner[0] == kfold) };
14017                    if matched { return !inv; }
14018                }
14019                p = q.add(2);
14020                continue;
14021            }
14022        } else {
14023            if *p == k || *p == kfold {
14024                return !inv;
14025            }
14026            p = p.add(1);
14027        }
14028    }
14029    inv
14030}
14031
14032/// Core fnmatch for a single path component (no FNM_PATHNAME splitting).
14033unsafe fn fnmatch_internal(pat: *const u8, str: *const u8, flags: c_int) -> c_int {
14034    // Handle leading .
14035    if flags & FNM_PERIOD != 0 && *str == b'.' && *pat != b'.' {
14036        return FNM_NOMATCH;
14037    }
14038
14039    let mut p = pat;
14040    let mut s = str;
14041
14042    // Consume pattern up to first *
14043    loop {
14044        let (tok, step) = pat_next(p, usize::MAX, flags);
14045        match tok {
14046            FNM_END => {
14047                return if *s == 0 { 0 } else { FNM_NOMATCH };
14048            }
14049            FNM_STAR => {
14050                p = p.add(1);
14051                break;
14052            }
14053            FNM_QUESTION => {
14054                if *s == 0 { return FNM_NOMATCH; }
14055                s = s.add(1);
14056                p = p.add(step);
14057            }
14058            FNM_BRACKET => {
14059                if *s == 0 { return FNM_NOMATCH; }
14060                let k = *s;
14061                let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14062                if !match_bracket(p, k, kfold) { return FNM_NOMATCH; }
14063                p = p.add(step);
14064                s = s.add(1);
14065            }
14066            c => {
14067                if *s == 0 { return FNM_NOMATCH; }
14068                let k = *s;
14069                let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14070                if k as c_int != c && kfold as c_int != c { return FNM_NOMATCH; }
14071                p = p.add(step);
14072                s = s.add(1);
14073            }
14074        }
14075    }
14076
14077    // Now p points after first *, rest of pattern is variable
14078    // Factor: find tail after last * and count fixed chars needed
14079    let mut ptail = p;
14080    let mut tailcnt: usize = 0;
14081    let mut pp = p;
14082    loop {
14083        let (tok, step) = pat_next(pp, usize::MAX, flags);
14084        if tok == FNM_END { break; }
14085        if tok == FNM_STAR {
14086            tailcnt = 0;
14087            ptail = pp.add(1);
14088        } else {
14089            tailcnt += 1;
14090        }
14091        pp = pp.add(step);
14092    }
14093
14094    // str must have at least tailcnt chars
14095    let slen = strlen(s as *const c_char);
14096    if slen < tailcnt { return FNM_NOMATCH; }
14097
14098    // Match tail: ptail..end against str[tailcnt from end]
14099    let stail = s.add(slen - tailcnt);
14100    let mut tp = ptail;
14101    let mut ts = stail;
14102    loop {
14103        let (tok, step) = pat_next(tp, usize::MAX, flags);
14104        tp = tp.add(step);
14105        if tok == FNM_END {
14106            break;
14107        }
14108        let k = *ts;
14109        if k == 0 { return FNM_NOMATCH; }
14110        let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14111        match tok {
14112            FNM_QUESTION => { ts = ts.add(1); }
14113            FNM_BRACKET => {
14114                if !match_bracket(tp.sub(step), k, kfold) { return FNM_NOMATCH; }
14115                ts = ts.add(1);
14116            }
14117            c => {
14118                if k as c_int != c && kfold as c_int != c { return FNM_NOMATCH; }
14119                ts = ts.add(1);
14120            }
14121        }
14122    }
14123
14124    let endstr = stail;
14125    let endpat = ptail;
14126
14127    let mut cp = p;
14128    let mut cs = s;
14129    while cp < endpat {
14130        let (tok, step) = pat_next(cp, usize::MAX, flags);
14131        if tok == FNM_STAR {
14132            cp = cp.add(step);
14133            cs = s;
14134            continue;
14135        }
14136        let comp_start = cp;
14137        let mut ok = false;
14138        let mut try_s = cs;
14139        while try_s < endstr {
14140            let mut tmp_p = comp_start;
14141            let mut tmp_s = try_s;
14142            let mut matched = true;
14143            loop {
14144                let (t, st) = pat_next(tmp_p, usize::MAX, flags);
14145                if t == FNM_STAR || t == FNM_END {
14146                    cp = tmp_p;
14147                    cs = tmp_s;
14148                    ok = true;
14149                    break;
14150                }
14151                if *tmp_s == 0 {
14152                    matched = false;
14153                    break;
14154                }
14155                let k = *tmp_s;
14156                let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14157                match t {
14158                    FNM_QUESTION => {
14159                        tmp_s = tmp_s.add(1);
14160                    }
14161                    FNM_BRACKET => {
14162                        if !match_bracket(tmp_p, k, kfold) {
14163                            matched = false;
14164                            break;
14165                        }
14166                        tmp_s = tmp_s.add(1);
14167                    }
14168                    c => {
14169                        if k as c_int != c && kfold as c_int != c {
14170                            matched = false;
14171                            break;
14172                        }
14173                        tmp_s = tmp_s.add(1);
14174                    }
14175                }
14176                tmp_p = tmp_p.add(st);
14177            }
14178            if ok { break; }
14179            if !matched {
14180                try_s = try_s.add(1);
14181            }
14182        }
14183        if !ok {
14184            return FNM_NOMATCH;
14185        }
14186    }
14187    0
14188}
14189
14190#[no_mangle]
14191pub unsafe extern "C" fn fnmatch(pat: *const c_char, str: *const c_char, flags: c_int) -> c_int {
14192    let pat = pat as *const u8;
14193    let str = str as *const u8;
14194
14195    if flags & FNM_PATHNAME != 0 {
14196        // Split on /
14197        let mut s = str;
14198        let mut p = pat;
14199        loop {
14200            // find next / in str
14201            let mut send = s;
14202            while *send != 0 && *send != b'/' { send = send.add(1); }
14203            // find next / in pat
14204            let mut pend = p;
14205            loop {
14206                let (tok, step) = pat_next(pend, usize::MAX, flags);
14207                if tok == FNM_END || (tok >= 0 && tok as u8 == b'/') {
14208                    break;
14209                }
14210                pend = pend.add(step);
14211            }
14212            let (ptok, pstep) = pat_next(pend, usize::MAX, flags);
14213            let pat_is_slash = ptok >= 0 && ptok as u8 == b'/';
14214            let str_is_slash = *send == b'/';
14215            if pat_is_slash != str_is_slash && (*send != 0 || !(flags & FNM_LEADING_DIR != 0)) {
14216                return FNM_NOMATCH;
14217            }
14218            // match component
14219            // We need a null-terminated copy of the component
14220            let plen = (pend as usize) - (p as usize);
14221            let slen = (send as usize) - (s as usize);
14222            // Use stack buffers for components
14223            // ponytail: max component 1024 bytes
14224            if plen > 1024 || slen > 1024 { return FNM_NOMATCH; }
14225            let mut pbuf = [0u8; 1025];
14226            let mut sbuf = [0u8; 1025];
14227            core::ptr::copy_nonoverlapping(p, pbuf.as_mut_ptr(), plen);
14228            pbuf[plen] = 0;
14229            core::ptr::copy_nonoverlapping(s, sbuf.as_mut_ptr(), slen);
14230            sbuf[slen] = 0;
14231            if fnmatch_internal(pbuf.as_ptr(), sbuf.as_ptr(), flags & !FNM_LEADING_DIR) != 0 {
14232                return FNM_NOMATCH;
14233            }
14234            if !pat_is_slash {
14235                return 0;
14236            }
14237            s = send.add(1);
14238            p = pend.add(pstep);
14239        }
14240    }
14241
14242    if flags & FNM_LEADING_DIR != 0 {
14243        // Try matching at each /
14244        let mut s = str;
14245        while *s != 0 {
14246            if *s == b'/' {
14247                // temporarily null-terminate
14248                // ponytail: we need to copy. Use a simple approach.
14249                let len = (s as usize) - (str as usize);
14250                // Just call fnmatch_internal with a temp buffer
14251                if len < 4096 {
14252                    let mut buf = [0u8; 4096];
14253                    core::ptr::copy_nonoverlapping(str, buf.as_mut_ptr(), len);
14254                    buf[len] = 0;
14255                    if fnmatch_internal(pat, buf.as_ptr(), flags) == 0 {
14256                        return 0;
14257                    }
14258                }
14259            }
14260            s = s.add(1);
14261        }
14262    }
14263
14264    fnmatch_internal(pat, str, flags)
14265}
14266
14267// ============================================================
14268// mntent: setmntent/endmntent/getmntent/getmntent_r/addmntent/hasmntopt
14269// ============================================================
14270
14271#[no_mangle]
14272pub unsafe extern "C" fn setmntent(name: *const c_char, mode: *const c_char) -> *mut FILE {
14273    fopen(name, mode)
14274}
14275
14276#[no_mangle]
14277pub unsafe extern "C" fn endmntent(f: *mut FILE) -> c_int {
14278    if !f.is_null() {
14279        fclose(f);
14280    }
14281    1
14282}
14283
14284// ponytail: static buffers for getmntent (non-_r variant)
14285static mut MNTENT_MNT: MntEnt = MntEnt {
14286    mnt_fsname: core::ptr::null_mut(),
14287    mnt_dir: core::ptr::null_mut(),
14288    mnt_type: core::ptr::null_mut(),
14289    mnt_opts: core::ptr::null_mut(),
14290    mnt_freq: 0,
14291    mnt_passno: 0,
14292};
14293
14294#[repr(C)]
14295pub struct MntEnt {
14296    mnt_fsname: *mut c_char,
14297    mnt_dir: *mut c_char,
14298    mnt_type: *mut c_char,
14299    mnt_opts: *mut c_char,
14300    mnt_freq: c_int,
14301    mnt_passno: c_int,
14302}
14303
14304unsafe fn unescape_ent(beg: *mut c_char) -> *mut c_char {
14305    let mut dest = beg;
14306    let mut src = beg;
14307    while *src != 0 {
14308        if *src != b'\\' as c_char {
14309            *dest = *src;
14310            dest = dest.add(1);
14311            src = src.add(1);
14312            continue;
14313        }
14314        // backslash
14315        if *src.add(1) == b'\\' as c_char {
14316            src = src.add(1);
14317            *dest = *src;
14318            dest = dest.add(1);
14319            src = src.add(1);
14320            continue;
14321        }
14322        // octal escape
14323        let mut val: u8 = 0;
14324        let mut cnt = 0;
14325        let mut sp = src.add(1);
14326        while cnt < 3 && *sp >= b'0' as c_char && *sp <= b'7' as c_char {
14327            val = val * 8 + (*sp as u8 - b'0');
14328            sp = sp.add(1);
14329            cnt += 1;
14330        }
14331        if cnt > 0 {
14332            *dest = val as c_char;
14333            dest = dest.add(1);
14334            src = sp;
14335        } else {
14336            *dest = *src;
14337            dest = dest.add(1);
14338            src = src.add(1);
14339        }
14340    }
14341    *dest = 0;
14342    beg
14343}
14344
14345unsafe fn parse_mntent_line(
14346    linebuf: *mut c_char,
14347    mnt: *mut MntEnt,
14348) -> *mut MntEnt {
14349    let _len = strlen(linebuf as *const c_char);
14350    // skip comments and empty lines
14351    // parse: fsname dir type opts freq passno
14352    let mut p = linebuf;
14353    // skip leading whitespace
14354    while *p == b' ' as c_char || *p == b'\t' as c_char || *p == b'\n' as c_char || *p == b'\r' as c_char {
14355        p = p.add(1);
14356    }
14357    if *p == 0 || *p == b'#' as c_char {
14358        return core::ptr::null_mut();
14359    }
14360
14361    // fsname
14362    (*mnt).mnt_fsname = p;
14363    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14364        p = p.add(1);
14365    }
14366    if *p == 0 { return core::ptr::null_mut(); }
14367    *p = 0;
14368    p = p.add(1);
14369    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14370
14371    // dir
14372    (*mnt).mnt_dir = p;
14373    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14374        p = p.add(1);
14375    }
14376    if *p == 0 { return core::ptr::null_mut(); }
14377    *p = 0;
14378    p = p.add(1);
14379    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14380
14381    // type
14382    (*mnt).mnt_type = p;
14383    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14384        p = p.add(1);
14385    }
14386    if *p == 0 { return core::ptr::null_mut(); }
14387    *p = 0;
14388    p = p.add(1);
14389    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14390
14391    // opts
14392    (*mnt).mnt_opts = p;
14393    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14394        p = p.add(1);
14395    }
14396    if *p != 0 {
14397        *p = 0;
14398        p = p.add(1);
14399    }
14400    if *(*mnt).mnt_opts == 0 {
14401        (*mnt).mnt_opts = b"defaults\0".as_ptr() as *mut c_char;
14402    }
14403
14404    // freq and passno
14405    (*mnt).mnt_freq = 0;
14406    (*mnt).mnt_passno = 0;
14407    // skip whitespace
14408    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14409    if *p >= b'0' as c_char && *p <= b'9' as c_char {
14410        (*mnt).mnt_freq = (*p - b'0' as c_char) as c_int;
14411        p = p.add(1);
14412        while *p >= b'0' as c_char && *p <= b'9' as c_char {
14413            (*mnt).mnt_freq = (*mnt).mnt_freq * 10 + (*p - b'0' as c_char) as c_int;
14414            p = p.add(1);
14415        }
14416    }
14417    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14418    if *p >= b'0' as c_char && *p <= b'9' as c_char {
14419        (*mnt).mnt_passno = (*p - b'0' as c_char) as c_int;
14420        p = p.add(1);
14421        while *p >= b'0' as c_char && *p <= b'9' as c_char {
14422            (*mnt).mnt_passno = (*mnt).mnt_passno * 10 + (*p - b'0' as c_char) as c_int;
14423            p = p.add(1);
14424        }
14425    }
14426
14427    // unescape
14428    unescape_ent((*mnt).mnt_fsname);
14429    unescape_ent((*mnt).mnt_dir);
14430    unescape_ent((*mnt).mnt_type);
14431    unescape_ent((*mnt).mnt_opts);
14432
14433    mnt
14434}
14435
14436// Use a sentinel pointer to detect internal buffer usage
14437// ponytail: cast integer to pointer for sentinel
14438static SENTINEL_PTR: usize = 1;
14439
14440// Read one char from FILE buffer directly (avoids musl's static fgets ABI mismatch)
14441unsafe fn mntent_fgetc(f: *mut FILE) -> c_int {
14442    fgetc(f)
14443}
14444
14445unsafe fn mntent_fgets(buf: *mut c_char, n: usize, f: *mut FILE) -> *mut c_char {
14446    if n == 0 { return core::ptr::null_mut(); }
14447    let max = n - 1;
14448    let mut i = 0usize;
14449    while i < max {
14450        let c = mntent_fgetc(f);
14451        if c == -1 { if i == 0 { return core::ptr::null_mut(); } break; }
14452        *buf.add(i) = c as c_char;
14453        i += 1;
14454        if c == b'\n' as c_int { break; }
14455    }
14456    *buf.add(i) = 0;
14457    buf
14458}
14459
14460#[no_mangle]
14461pub unsafe extern "C" fn getmntent_r(
14462    f: *mut FILE,
14463    mnt: *mut MntEnt,
14464    mut linebuf: *mut c_char,
14465    buflen: c_int,
14466) -> *mut MntEnt {
14467    let use_internal = linebuf as usize == SENTINEL_PTR;
14468
14469    (*mnt).mnt_freq = 0;
14470    (*mnt).mnt_passno = 0;
14471
14472    static mut MNT_LINE: *mut c_char = core::ptr::null_mut();
14473    static mut MNT_LINE_CAP: usize = 0;
14474
14475    loop {
14476        let res = if use_internal {
14477            let n = getline(&raw mut MNT_LINE, &raw mut MNT_LINE_CAP, f);
14478            if n < 0 {
14479                return core::ptr::null_mut();
14480            }
14481            linebuf = MNT_LINE;
14482            MNT_LINE
14483        } else {
14484            if buflen <= 0 {
14485                ERRNO!() = EINVAL;
14486                return core::ptr::null_mut();
14487            }
14488            mntent_fgets(linebuf, buflen as usize, f)
14489        };
14490        if res.is_null() {
14491            return core::ptr::null_mut();
14492        }
14493        let mut has_newline = false;
14494        let mut p = linebuf;
14495        while *p != 0 { if *p == b'\n' as c_char { has_newline = true; break; } p = p.add(1); }
14496        if !has_newline {
14497            ERRNO!() = 34;
14498            return core::ptr::null_mut();
14499        }
14500        let result = parse_mntent_line(linebuf, mnt);
14501        if !result.is_null() {
14502            return result;
14503        }
14504    }
14505}
14506
14507#[no_mangle]
14508pub unsafe extern "C" fn getmntent(f: *mut FILE) -> *mut MntEnt {
14509    getmntent_r(f, core::ptr::addr_of_mut!(MNTENT_MNT), SENTINEL_PTR as *mut c_char, 0)
14510}
14511
14512#[no_mangle]
14513pub unsafe extern "C" fn addmntent(f: *mut FILE, mnt: *const MntEnt) -> c_int {
14514    fseek(f, 0, 2); // SEEK_END
14515    let written = fprintf(
14516        f,
14517        b"%s\t%s\t%s\t%s\t%d\t%d\n\0".as_ptr() as *const c_char,
14518        (*mnt).mnt_fsname,
14519        (*mnt).mnt_dir,
14520        (*mnt).mnt_type,
14521        (*mnt).mnt_opts,
14522        (*mnt).mnt_freq,
14523        (*mnt).mnt_passno,
14524    );
14525    if written < 0 { 1 } else { 0 }
14526}
14527
14528#[no_mangle]
14529pub unsafe extern "C" fn hasmntopt(mnt: *const MntEnt, opt: *const c_char) -> *mut c_char {
14530    let l = strlen(opt as *const c_char);
14531    let mut p = (*mnt).mnt_opts;
14532    loop {
14533        if strncmp(p as *const u8, opt as *const u8, l) == 0 {
14534            let after = *p.add(l);
14535            if after == 0 || after == b',' as c_char || after == b'=' as c_char {
14536                return p;
14537            }
14538        }
14539        let comma = strchr(p as *const u8, b',' as c_int);
14540        if comma.is_null() {
14541            return core::ptr::null_mut();
14542        }
14543        p = comma.add(1) as *mut c_char;
14544    }
14545}
14546
14547// ============================================================
14548// SysV IPC: ftok, msg*, sem*, shm*
14549// x86_64 direct syscalls: msgget=68, msgsnd=69, msgrcv=70, msgctl=71
14550//   semget=64, semop=65, semctl=66, semtimedop=220
14551//   shmget=29, shmat=30, shmctl=31, shmdt=67
14552// ============================================================
14553
14554const EEXIST: c_int = 17;
14555const ENAMETOOLONG: c_int = 36;
14556const EMFILE: c_int = 24;
14557const EIDRM: c_int = 43;
14558
14559#[inline]
14560unsafe fn sys_msgget(key: c_int, msgflg: c_int) -> i64 {
14561    <Arch as Syscalls>::syscall2(SYS_MSGGET, key as i64, msgflg as i64)
14562}
14563
14564#[inline]
14565unsafe fn sys_msgsnd(msqid: c_int, msgp: *const c_void, msgsz: usize, msgflg: c_int) -> i64 {
14566    <Arch as Syscalls>::syscall4(SYS_MSGSND, msqid as i64, msgp as i64, msgsz as i64, msgflg as i64)
14567}
14568
14569#[inline]
14570unsafe fn sys_msgrcv(msqid: c_int, msgp: *mut c_void, msgsz: usize, msgtyp: c_long, msgflg: c_int) -> i64 {
14571    <Arch as Syscalls>::syscall5(SYS_MSGRCV, msqid as i64, msgp as i64, msgsz as i64, msgtyp as i64, msgflg as i64)
14572}
14573
14574#[inline]
14575unsafe fn sys_msgctl(msqid: c_int, cmd: c_int, buf: *mut c_void) -> i64 {
14576    <Arch as Syscalls>::syscall3(SYS_MSGCTL, msqid as i64, cmd as i64, buf as i64)
14577}
14578
14579#[inline]
14580unsafe fn sys_semget(key: c_int, nsems: c_int, semflg: c_int) -> i64 {
14581    <Arch as Syscalls>::syscall3(SYS_SEMGET, key as i64, nsems as i64, semflg as i64)
14582}
14583
14584#[inline]
14585unsafe fn sys_semop(semid: c_int, sops: *const c_void, nsops: usize) -> i64 {
14586    <Arch as Syscalls>::syscall3(SYS_SEMOP, semid as i64, sops as i64, nsops as i64)
14587}
14588
14589#[inline]
14590unsafe fn sys_semctl(semid: c_int, semnum: c_int, cmd: c_int, arg: *mut c_void) -> i64 {
14591    <Arch as Syscalls>::syscall4(SYS_SEMCTL, semid as i64, semnum as i64, cmd as i64, arg as i64)
14592}
14593
14594#[inline]
14595unsafe fn sys_shmget(key: c_int, size: usize, shmflg: c_int) -> i64 {
14596    <Arch as Syscalls>::syscall3(SYS_SHMGET, key as i64, size as i64, shmflg as i64)
14597}
14598
14599#[inline]
14600unsafe fn sys_shmat(shmid: c_int, shmaddr: *const c_void, shmflg: c_int) -> i64 {
14601    <Arch as Syscalls>::syscall3(SYS_SHMAT, shmid as i64, shmaddr as i64, shmflg as i64)
14602}
14603
14604#[inline]
14605unsafe fn sys_shmdt(shmaddr: *const c_void) -> i64 {
14606    <Arch as Syscalls>::syscall1(SYS_SHMDT, shmaddr as i64)
14607}
14608
14609#[inline]
14610unsafe fn sys_shmctl(shmid: c_int, cmd: c_int, buf: *mut c_void) -> i64 {
14611    <Arch as Syscalls>::syscall3(SYS_SHMCTL, shmid as i64, cmd as i64, buf as i64)
14612}
14613
14614// ftok
14615#[no_mangle]
14616pub unsafe extern "C" fn ftok(path: *const c_char, id: c_int) -> c_int {
14617    let mut st: kernel_stat64 = core::mem::zeroed();
14618    let r = sys_stat(path as *const u8, &mut st);
14619    if r < 0 {
14620        ERRNO!() = (-r) as c_int;
14621        return -1;
14622    }
14623    ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16) | (((id as u32 & 0xff) << 24)) as u64) as c_int
14624}
14625
14626// msgget
14627#[no_mangle]
14628pub unsafe extern "C" fn msgget(key: c_int, msgflg: c_int) -> c_int {
14629    let r = sys_msgget(key, msgflg);
14630    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14631}
14632
14633// msgsnd
14634#[no_mangle]
14635pub unsafe extern "C" fn msgsnd(msqid: c_int, msgp: *const c_void, msgsz: usize, msgflg: c_int) -> c_int {
14636    let r = sys_msgsnd(msqid, msgp, msgsz, msgflg);
14637    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14638}
14639
14640// msgrcv
14641#[no_mangle]
14642pub unsafe extern "C" fn msgrcv(msqid: c_int, msgp: *mut c_void, msgsz: usize, msgtyp: c_long, msgflg: c_int) -> isize {
14643    let r = sys_msgrcv(msqid, msgp, msgsz, msgtyp, msgflg);
14644    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
14645}
14646
14647// msgctl
14648#[no_mangle]
14649pub unsafe extern "C" fn msgctl(msqid: c_int, cmd: c_int, buf: *mut c_void) -> c_int {
14650    let r = sys_msgctl(msqid, cmd, buf);
14651    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14652}
14653
14654// semget
14655#[no_mangle]
14656pub unsafe extern "C" fn semget(key: c_int, nsems: c_int, semflg: c_int) -> c_int {
14657    if nsems > 65535 { ERRNO!() = 22; return -1; }
14658    let r = sys_semget(key, nsems, semflg);
14659    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14660}
14661
14662// semop
14663#[no_mangle]
14664pub unsafe extern "C" fn semop(semid: c_int, sops: *const c_void, nsops: usize) -> c_int {
14665    let r = sys_semop(semid, sops, nsops);
14666    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14667}
14668
14669// semctl - C variadic
14670#[no_mangle]
14671pub unsafe extern "C" fn semctl(semid: c_int, semnum: c_int, cmd: c_int, mut args: ...) -> c_int {
14672    let mut arg: *mut c_void = core::ptr::null_mut();
14673    // Commands that take the union semun argument
14674    match cmd {
14675        // SETVAL/SETALL/GETALL, IPC_SET/IPC_STAT/IPC_INFO, SEM_STAT,
14676        // SEM_INFO, SEM_STAT_ANY and the 32-bit compat variants all carry
14677        // the `union semun` argument.
14678        16 | 13 | 17 | 1 | 2 | 3 | 18 | 19 | 20 | 0x102 | 0x104 | 0x106 => {
14679            arg = args.next_arg::<*mut c_void>();
14680        }
14681        _ => {}
14682    }
14683    let r = sys_semctl(semid, semnum, cmd, arg);
14684    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14685}
14686
14687// shmget
14688#[no_mangle]
14689pub unsafe extern "C" fn shmget(key: c_int, size: usize, shmflg: c_int) -> c_int {
14690    let r = sys_shmget(key, size, shmflg);
14691    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14692}
14693
14694// shmat
14695#[no_mangle]
14696pub unsafe extern "C" fn shmat(shmid: c_int, shmaddr: *const c_void, shmflg: c_int) -> *mut c_void {
14697    let r = sys_shmat(shmid, shmaddr, shmflg);
14698    if (r as usize) > (-(4096isize as isize)) as usize {
14699        ERRNO!() = (-r) as c_int;
14700        return -1isize as *mut c_void;
14701    }
14702    r as *mut c_void
14703}
14704
14705// shmdt
14706#[no_mangle]
14707pub unsafe extern "C" fn shmdt(shmaddr: *const c_void) -> c_int {
14708    let r = sys_shmdt(shmaddr);
14709    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14710}
14711
14712// shmctl
14713#[no_mangle]
14714pub unsafe extern "C" fn shmctl(shmid: c_int, cmd: c_int, buf: *mut c_void) -> c_int {
14715    let r = sys_shmctl(shmid, cmd, buf);
14716    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14717}
14718
14719// ============================================================
14720// Startup: __libc_start_main
14721//
14722// musl crt1.o _start_c calls:
14723//   __libc_start_main(main, argc, argv, _init, _fini, rtld_fini, stack_end)
14724// ============================================================
14725
14726// Auxiliary vector pointer, populated by the dynamic linker before
14727// constructors run so getauxval() works during early startup.
14728#[no_mangle]
14729pub static mut __auxv: *const usize = core::ptr::null();
14730#[no_mangle]
14731pub static mut __keel_static_base: usize = 0;
14732static mut RC_STATIC_EXEC: bool = false;
14733
14734#[no_mangle]
14735pub static mut __progname: *mut c_char = core::ptr::null_mut();
14736#[no_mangle]
14737pub static mut __progname_full: *mut c_char = core::ptr::null_mut();
14738#[no_mangle]
14739pub static mut program_invocation_name: *mut c_char = core::ptr::null_mut();
14740#[no_mangle]
14741pub static mut program_invocation_short_name: *mut c_char = core::ptr::null_mut();
14742
14743#[no_mangle]
14744pub static in6addr_any: [u32; 4] = [0; 4];
14745#[no_mangle]
14746pub static in6addr_loopback: [u32; 4] = [0, 0, 0, 0x0100_0000];
14747
14748#[no_mangle]
14749pub static mut __daylight: c_int = 0;
14750#[no_mangle]
14751pub static mut __timezone: c_long = 0;
14752#[no_mangle]
14753pub static mut __tzname: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
14754
14755#[no_mangle]
14756pub unsafe extern "C" fn getauxval(type_: c_ulong) -> c_ulong {
14757    let mut p = __auxv;
14758    if p.is_null() {
14759        return 0;
14760    }
14761    loop {
14762        let tag = *p;
14763        if tag == 0 {
14764            return 0;
14765        }
14766        if tag == type_ as usize {
14767            return *p.add(1) as c_ulong;
14768        }
14769        p = p.add(2);
14770    }
14771}
14772
14773
14774unsafe fn run_static_init() {
14775    if !RC_STATIC_EXEC {
14776        return;
14777    }
14778    extern "C" {
14779        static __preinit_array_start: usize;
14780        static __preinit_array_end: usize;
14781        static __init_array_start: usize;
14782        static __init_array_end: usize;
14783    }
14784    let mut p = core::ptr::addr_of!(__preinit_array_start) as usize;
14785    let end = core::ptr::addr_of!(__preinit_array_end) as usize;
14786    while p < end {
14787        let f = core::ptr::read_unaligned(p as *const usize);
14788        if f != 0 {
14789            let f: unsafe extern "C" fn() = core::mem::transmute(f);
14790            f();
14791        }
14792        p += core::mem::size_of::<usize>();
14793    }
14794    p = core::ptr::addr_of!(__init_array_start) as usize;
14795    let end = core::ptr::addr_of!(__init_array_end) as usize;
14796    while p < end {
14797        let f = core::ptr::read_unaligned(p as *const usize);
14798        if f != 0 {
14799            let f: unsafe extern "C" fn() = core::mem::transmute(f);
14800            f();
14801        }
14802        p += core::mem::size_of::<usize>();
14803    }
14804}
14805
14806type MainFn = unsafe extern "C" fn(c_int, *const *const c_char, *const *const c_char) -> c_int;
14807type InitFn = unsafe extern "C" fn();
14808
14809#[cfg(target_arch = "x86_64")]
14810unsafe fn static_tls_tp() -> usize {
14811    let mut fs: u64 = 0;
14812    if arch_prctl(0x1003, &mut fs as *mut u64 as u64) != 0 {
14813        0
14814    } else {
14815        fs as usize
14816    }
14817}
14818
14819#[cfg(target_arch = "x86_64")]
14820unsafe fn set_static_tls_tp(tp: usize) {
14821    let _ = arch_prctl(0x1002, tp as u64);
14822}
14823
14824#[cfg(target_arch = "aarch64")]
14825unsafe fn static_tls_tp() -> usize {
14826    let tp: usize;
14827    core::arch::asm!("mrs {}, tpidr_el0", out(reg) tp, options(nostack));
14828    tp
14829}
14830
14831#[cfg(target_arch = "aarch64")]
14832unsafe fn set_static_tls_tp(tp: usize) {
14833    core::arch::asm!("msr tpidr_el0, {}", in(reg) tp, options(nostack));
14834}
14835
14836#[cfg(target_arch = "riscv64")]
14837unsafe fn static_tls_tp() -> usize {
14838    let tp: usize;
14839    core::arch::asm!("mv {}, tp", out(reg) tp, options(nostack));
14840    tp
14841}
14842
14843#[cfg(target_arch = "riscv64")]
14844unsafe fn set_static_tls_tp(tp: usize) {
14845    core::arch::asm!("mv tp, {}", in(reg) tp, options(nostack));
14846}
14847
14848static mut STATIC_TLS_BLOCK_SIZE: usize = 0;
14849static mut STATIC_TLS_TP_OFFSET: usize = 0;
14850static mut STATIC_TLS_VAR_OFFSET: usize = 0;
14851static mut STATIC_TLS_TLS_SIZE: usize = 0;
14852static mut STATIC_TLS_IMAGE: *const u8 = core::ptr::null();
14853static mut STATIC_TLS_FILESZ: usize = 0;
14854static mut STATIC_TLS_CANARY: u64 = 0;
14855
14856unsafe fn static_tls_init_block(block: *mut u8) -> *mut u8 {
14857    if block.is_null() || STATIC_TLS_BLOCK_SIZE == 0 {
14858        return core::ptr::null_mut();
14859    }
14860    let var_base = block.add(STATIC_TLS_VAR_OFFSET);
14861    if STATIC_TLS_TLS_SIZE > 0 {
14862        core::ptr::write_bytes(var_base, 0, STATIC_TLS_TLS_SIZE);
14863    }
14864    if STATIC_TLS_FILESZ > 0 && !STATIC_TLS_IMAGE.is_null() {
14865        core::ptr::copy_nonoverlapping(STATIC_TLS_IMAGE, var_base, STATIC_TLS_FILESZ);
14866    }
14867    let tp = block.add(STATIC_TLS_TP_OFFSET);
14868    let tcb = if cfg!(target_arch = "x86_64") {
14869        tp as usize
14870    } else {
14871        block as usize
14872    };
14873    core::ptr::write_unaligned(tcb as *mut u64, tcb as u64);
14874    core::ptr::write_unaligned((tcb as *mut u64).add(1), 1);
14875    core::ptr::write_unaligned((tcb as *mut u64).add(2), STATIC_TLS_TLS_SIZE as u64);
14876    core::ptr::write_unaligned((tcb as *mut u64).add(3), 1);
14877    core::ptr::write_unaligned((tcb as *mut u64).add(4), 0); // reserved
14878    core::ptr::write_unaligned((tcb as *mut u64).add(5), STATIC_TLS_CANARY); // 0x28
14879    core::ptr::write_unaligned((tcb as *mut u64).add(6), 0); // errno at 0x30
14880    core::ptr::write_unaligned((tcb as *mut u64).add(7), 0); // vDSO getrandom state at 0x38
14881    core::ptr::write_unaligned((tcb as *mut u64).add(8), 0); // Thread record at 0x40
14882    tp
14883}
14884
14885unsafe fn static_tls_create_block() -> *mut u8 {
14886    if STATIC_TLS_BLOCK_SIZE == 0 {
14887        return core::ptr::null_mut();
14888    }
14889    let block = sys_mmap(
14890        core::ptr::null_mut(),
14891        STATIC_TLS_BLOCK_SIZE,
14892        PROT_READ | PROT_WRITE,
14893        MAP_PRIVATE | MAP_ANONYMOUS,
14894        -1,
14895        0,
14896    );
14897    if block.is_null() || block == MMAP_FAILED {
14898        return core::ptr::null_mut();
14899    }
14900    static_tls_init_block(block)
14901}
14902
14903#[repr(C)]
14904pub struct TlsIndex {
14905    pub ti_module: usize,
14906    pub ti_offset: usize,
14907}
14908
14909/// Global-dynamic TLS access.  The dynamic loader intercepts this symbol for
14910/// dynamically linked programs and uses its own multi-module implementation.
14911/// A static executable has only module 0, so resolve directly against the
14912/// static TLS block created by `init_static_tls()`.
14913static mut TLS_GET_ADDR_IMPL: usize = 0;
14914
14915/// The dynamic loader installs its multi-module TLS resolver here before
14916/// running constructors.  Keeping a dispatch pointer means a program that
14917/// obtains `__tls_get_addr` through `dlsym` still reaches the loader's
14918/// implementation rather than the static fallback below.
14919#[no_mangle]
14920pub unsafe extern "C" fn __keel_set_tls_get_addr(f: usize) {
14921    TLS_GET_ADDR_IMPL = f;
14922}
14923
14924#[no_mangle]
14925pub unsafe extern "C" fn __tls_get_addr(ti: *const TlsIndex) -> *mut u8 {
14926    if TLS_GET_ADDR_IMPL != 0 {
14927        let f: unsafe extern "C" fn(*const TlsIndex) -> *mut u8 =
14928            core::mem::transmute(TLS_GET_ADDR_IMPL);
14929        return f(ti);
14930    }
14931    if ti.is_null() || (*ti).ti_module != 0 || !RC_STATIC_EXEC {
14932        return core::ptr::null_mut();
14933    }
14934    let tp = static_tls_tp();
14935    if tp == 0 {
14936        return core::ptr::null_mut();
14937    }
14938    (tp - STATIC_TLS_TP_OFFSET + STATIC_TLS_VAR_OFFSET + (*ti).ti_offset) as *mut u8
14939}
14940
14941/// Static executables have no dynamic loader to build a TCB.  Allocate one
14942/// from PT_TLS so that `%fs`/TP-relative TLS accesses and errno work.
14943unsafe fn init_static_tls() {
14944    if static_tls_tp() != 0 {
14945        return;
14946    }
14947    let phdr = getauxval(3) as usize; // AT_PHDR
14948    let phnum = getauxval(5) as usize; // AT_PHNUM
14949    let phent = getauxval(4) as usize; // AT_PHENT
14950    if phdr == 0 || phnum == 0 || phent < 56 {
14951        return;
14952    }
14953
14954    let mut tls_vaddr = 0usize;
14955    let mut tls_filesz = 0usize;
14956    let mut tls_memsz = 0usize;
14957    let mut tls_align = 1usize;
14958    let mut exec_base = __keel_static_base;
14959    let mut i = 0usize;
14960    while i < phnum {
14961        let ph = phdr + i * phent;
14962        let p_type = core::ptr::read_unaligned(ph as *const u32);
14963        if p_type == 3 {
14964            // PT_INTERP means the dynamic loader already owns TLS.
14965            return;
14966        }
14967        if p_type == 6 {
14968            // PT_PHDR
14969            if exec_base == 0 {
14970                let p_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
14971                exec_base = phdr.wrapping_sub(p_vaddr);
14972            }
14973        } else if p_type == 7 {
14974            // PT_TLS
14975            tls_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
14976            tls_filesz = core::ptr::read_unaligned((ph + 32) as *const u64) as usize;
14977            tls_memsz = core::ptr::read_unaligned((ph + 40) as *const u64) as usize;
14978            let align = core::ptr::read_unaligned((ph + 48) as *const u64) as usize;
14979            if align > 1 {
14980                tls_align = align;
14981            }
14982        }
14983        i += 1;
14984    }
14985
14986    let tcb_size = 256usize;
14987    #[cfg(target_arch = "x86_64")]
14988    let gap = 0usize;
14989    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
14990    let gap = if cfg!(target_arch = "aarch64") { 16usize } else { 0usize };
14991
14992    let tls_size = if tls_align > 1 {
14993        (tls_memsz + tls_align - 1) & !(tls_align - 1)
14994    } else {
14995        tls_memsz
14996    };
14997    let total = tcb_size + gap + tls_size + tls_align;
14998    STATIC_TLS_BLOCK_SIZE = total;
14999    STATIC_TLS_TP_OFFSET = if cfg!(target_arch = "x86_64") {
15000        tls_size
15001    } else {
15002        tcb_size
15003    };
15004    STATIC_TLS_VAR_OFFSET = if cfg!(target_arch = "x86_64") {
15005        0
15006    } else {
15007        tcb_size + gap
15008    };
15009    STATIC_TLS_TLS_SIZE = tls_size;
15010    STATIC_TLS_IMAGE = (exec_base + tls_vaddr) as *const u8;
15011    STATIC_TLS_FILESZ = tls_filesz;
15012    let random = getauxval(25) as *const u8; // AT_RANDOM
15013    STATIC_TLS_CANARY = if random.is_null() {
15014        0xdefaced_cafebeefu64
15015    } else {
15016        core::ptr::read_unaligned(random as *const u64)
15017            ^ core::ptr::read_unaligned(random.add(8) as *const u64)
15018    };
15019
15020    let block = sys_mmap(
15021        core::ptr::null_mut(),
15022        total,
15023        PROT_READ | PROT_WRITE,
15024        MAP_PRIVATE | MAP_ANONYMOUS,
15025        -1,
15026        0,
15027    );
15028    if block.is_null() || block == MMAP_FAILED {
15029        return;
15030    }
15031    let tp = static_tls_init_block(block);
15032    if tp.is_null() {
15033        return;
15034    }
15035    set_static_tls_tp(tp as usize);
15036    RC_STATIC_EXEC = true;
15037}
15038
15039
15040#[no_mangle]
15041pub unsafe extern "C" fn __libc_start_main(
15042    main: MainFn,
15043    argc: c_int,
15044    argv: *const *const c_char,
15045    _init: *const c_void,
15046    _fini: *const c_void,
15047    _rtld_fini: *const c_void,
15048    _stack_end: *const c_void,
15049) -> ! {
15050    let envp = argv.add((argc + 1) as usize);
15051    let mut aux = envp;
15052    while !(*aux).is_null() {
15053        aux = aux.add(1);
15054    }
15055    __auxv = aux.add(1) as *const usize;
15056    init_static_tls();
15057    errno_init();
15058    // Register the main thread during startup.  pthread_exit() uses the
15059    // thread table to decide whether it is the last thread; if the main
15060    // thread only registered lazily, a worker exiting first could call
15061    // exit() while the main thread was still alive.
15062    pthread_self();
15063
15064    __environ = envp as *mut *mut c_char;
15065    environ = __environ; // sync environ alias
15066    ___environ = __environ;
15067    _environ = __environ;
15068
15069    // glibc-compatible program name globals.
15070    if !argv.is_null() && argc > 0 {
15071        let argv0 = *argv;
15072        __progname_full = argv0 as *mut c_char;
15073        program_invocation_name = argv0 as *mut c_char;
15074        let mut base = argv0;
15075        let mut p = argv0;
15076        while *p != 0 {
15077            if *p == b'/' as c_char { base = p.add(1); }
15078            p = p.add(1);
15079        }
15080        __progname = base as *mut c_char;
15081        program_invocation_short_name = base as *mut c_char;
15082    }
15083
15084    __stdio_init();
15085    run_static_init();
15086
15087    let mut set: SigSetT = 0;
15088    sigemptyset(&mut set);
15089    sigaddset(&mut set, SIGCANCEL);
15090    sigprocmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
15091
15092    if !_init.is_null() {
15093        let init_fn: InitFn = core::mem::transmute(_init);
15094        init_fn();
15095    }
15096
15097    // aarch64/riscv64 GCC reads __stack_chk_guard as a global (GOT-based for PIE),
15098    // so we must initialize it from AT_RANDOM before calling main.
15099    // x86_64 uses %fs:0x28 which the kernel already set up.
15100    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
15101    {
15102        let random_ptr = getauxval(25) as *const u8; // AT_RANDOM = 25
15103        if !random_ptr.is_null() {
15104            let a = core::ptr::read_unaligned(random_ptr as *const u64);
15105            let b = core::ptr::read_unaligned(random_ptr.add(8) as *const u64);
15106            __stack_chk_guard = (a ^ b) as usize;
15107        } else {
15108            // ponytail: fallback entropy, not crypto-grade but nonzero
15109            __stack_chk_guard = 0xdefaced_cafebeef;
15110        }
15111    }
15112
15113    let result = main(argc, argv, envp);
15114
15115    if !_fini.is_null() {
15116        let fini_fn: InitFn = core::mem::transmute(_fini);
15117        fini_fn();
15118    }
15119
15120    exit(result);
15121}
15122
15123type LdsoDlopenFn = unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void;
15124type LdsoDlsymFn = unsafe extern "C" fn(*mut c_void, *const c_char, *mut c_void) -> *mut c_void;
15125type LdsoDlcloseFn = unsafe extern "C" fn(*mut c_void) -> c_int;
15126type LdsoDlerrorFn = unsafe extern "C" fn() -> *const c_char;
15127
15128static mut LDSO_DLOPEN: Option<LdsoDlopenFn> = None;
15129static mut LDSO_DLSYM: Option<LdsoDlsymFn> = None;
15130static mut LDSO_DLCLOSE: Option<LdsoDlcloseFn> = None;
15131static mut LDSO_DLERROR: Option<LdsoDlerrorFn> = None;
15132
15133#[no_mangle]
15134pub unsafe extern "C" fn __ldso_register_dlopen(f: LdsoDlopenFn) {
15135    LDSO_DLOPEN = Some(f);
15136}
15137
15138#[no_mangle]
15139pub unsafe extern "C" fn __ldso_register_dlsym(f: LdsoDlsymFn) {
15140    LDSO_DLSYM = Some(f);
15141}
15142
15143#[no_mangle]
15144pub unsafe extern "C" fn __ldso_register_dlclose(f: LdsoDlcloseFn) {
15145    LDSO_DLCLOSE = Some(f);
15146}
15147
15148#[no_mangle]
15149pub unsafe extern "C" fn __ldso_register_dlerror(f: LdsoDlerrorFn) {
15150    LDSO_DLERROR = Some(f);
15151}
15152
15153#[no_mangle]
15154pub unsafe extern "C" fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void {
15155    if let Some(f) = LDSO_DLOPEN {
15156        f(filename, flags)
15157    } else {
15158        null_mut()
15159    }
15160}
15161
15162#[no_mangle]
15163pub unsafe extern "C" fn dlsym_impl(
15164    handle: *mut c_void,
15165    symbol: *const c_char,
15166    ra: *mut c_void,
15167) -> *mut c_void {
15168    if let Some(f) = LDSO_DLSYM {
15169        f(handle, symbol, ra)
15170    } else {
15171        null_mut()
15172    }
15173}
15174
15175// dlsym() must pass its own return address to the loader so that
15176// RTLD_NEXT can identify the calling object.  Keep the public entry
15177// point in assembly and tail-jump into the Rust implementation.
15178#[no_mangle]
15179#[unsafe(naked)]
15180#[cfg(target_arch = "x86_64")]
15181pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15182    core::arch::naked_asm!("mov rdx, [rsp]", "jmp dlsym_impl");
15183}
15184
15185#[no_mangle]
15186#[unsafe(naked)]
15187#[cfg(target_arch = "aarch64")]
15188pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15189    core::arch::naked_asm!("mov x2, x30", "b dlsym_impl");
15190}
15191
15192#[no_mangle]
15193#[unsafe(naked)]
15194#[cfg(target_arch = "riscv64")]
15195pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15196    core::arch::naked_asm!("mv a2, ra", "la t0, dlsym_impl", "jr t0");
15197}
15198
15199#[no_mangle]
15200pub unsafe extern "C" fn dlclose(handle: *mut c_void) -> c_int {
15201    if let Some(f) = LDSO_DLCLOSE {
15202        f(handle)
15203    } else {
15204        0
15205    }
15206}
15207
15208#[no_mangle]
15209pub unsafe extern "C" fn dlerror() -> *const c_char {
15210    if let Some(f) = LDSO_DLERROR {
15211        f()
15212    } else {
15213        core::ptr::null()
15214    }
15215}
15216
15217include!("crypt_impl.rs");
15218include!("statvfs.rs");
15219include!("daemon.rs");
15220include!("dn_expand.rs");
15221include!("lrand48.rs");
15222include!("strverscmp.rs");
15223include!("syscall.rs");
15224include!("pthread_atfork.rs");
15225include!("fenv.rs");
15226include!("locale_ctype.rs");
15227include!("regression_stubs.rs");
15228include!("netdb_extra.rs");
15229include!("compat_extra.rs");
15230include!("stdio_extra.rs");
15231include!("ns_parse.rs");
15232include!("fts.rs");
15233include!("ifaddrs.rs");
15234include!("dl_extra.rs");
15235include!("des.rs");
15236include!("path_extra.rs");
15237include!("wordexp.rs");
15238include!("getopt_impl.rs");
15239
15240// ============================================================
15241// regex.h
15242// ============================================================
15243
15244// musl defines regoff_t as _Addr (long on every Linux target), not int.
15245type regoff_t = c_long;
15246
15247#[repr(C)]
15248pub struct regex_t {
15249    pub re_nsub: usize,
15250    pub __opaque: *mut c_void,
15251    pub __padding: [*mut c_void; 4],
15252    pub __nsub2: usize,
15253    pub __padding2: c_char,
15254}
15255
15256#[repr(C)]
15257pub struct regmatch_t {
15258    pub rm_so: regoff_t,
15259    pub rm_eo: regoff_t,
15260}
15261
15262include!("regex.rs");
15263include!("tz.rs");
15264
15265#[cfg(test)]
15266mod libc_unit_stub {
15267    #[test]
15268    fn stub() {
15269        assert!(true);
15270    }
15271}
15272
15273// ============================================================
15274// Missing math functions - simple implementations
15275// ============================================================
15276
15277#[inline]
15278pub(crate) fn fmax_impl(x: f64, y: f64) -> f64 {
15279    if x.is_nan() { return y; }
15280    if y.is_nan() { return x; }
15281    if x == 0.0 && y == 0.0 {
15282        return if x.is_sign_negative() && y.is_sign_negative() { -0.0 } else { 0.0 };
15283    }
15284    if x > y { x } else { y }
15285}
15286
15287#[inline]
15288pub(crate) fn fmin_impl(x: f64, y: f64) -> f64 {
15289    if x.is_nan() { return y; }
15290    if y.is_nan() { return x; }
15291    if x == 0.0 && y == 0.0 {
15292        return if x.is_sign_negative() || y.is_sign_negative() { -0.0 } else { 0.0 };
15293    }
15294    if x < y { x } else { y }
15295}
15296
15297#[inline]
15298pub(crate) fn fmaxf_impl(x: f32, y: f32) -> f32 {
15299    if x.is_nan() { return y; }
15300    if y.is_nan() { return x; }
15301    if x == 0.0 && y == 0.0 {
15302        return if x.is_sign_negative() && y.is_sign_negative() { -0.0 } else { 0.0 };
15303    }
15304    if x > y { x } else { y }
15305}
15306
15307#[inline]
15308pub(crate) fn fminf_impl(x: f32, y: f32) -> f32 {
15309    if x.is_nan() { return y; }
15310    if y.is_nan() { return x; }
15311    if x == 0.0 && y == 0.0 {
15312        return if x.is_sign_negative() || y.is_sign_negative() { -0.0 } else { 0.0 };
15313    }
15314    if x < y { x } else { y }
15315}
15316
15317#[inline(never)]
15318#[no_mangle]
15319pub unsafe extern "C" fn fmax(x: f64, y: f64) -> f64 {
15320    fmax_impl(x, y)
15321}
15322
15323#[inline(never)]
15324#[no_mangle]
15325pub unsafe extern "C" fn fmin(x: f64, y: f64) -> f64 {
15326    fmin_impl(x, y)
15327}
15328
15329#[no_mangle]
15330pub unsafe extern "C" fn fminf(x: f32, y: f32) -> f32 {
15331    fminf_impl(x, y)
15332}
15333
15334#[no_mangle]
15335pub unsafe extern "C" fn fdim(x: f64, y: f64) -> f64 {
15336    if x.is_nan() || y.is_nan() {
15337        return f64::NAN;
15338    }
15339    if x > y { x - y } else { 0.0 }
15340}
15341
15342#[no_mangle]
15343pub unsafe extern "C" fn fma(x: f64, y: f64, z: f64) -> f64 {
15344    if (x.is_infinite() && y == 0.0) || (y.is_infinite() && x == 0.0) {
15345        feraiseexcept(FE_INVALID);
15346        return f64::NAN;
15347    }
15348    if x.is_nan() || y.is_nan() || z.is_nan() {
15349        return f64::NAN;
15350    }
15351    let r = libm::fma(x, y, z);
15352    // inf-inf is invalid; libm may return NaN without raising.
15353    if r.is_nan() {
15354        feraiseexcept(FE_INVALID);
15355    }
15356    r
15357}
15358
15359#[no_mangle]
15360pub unsafe extern "C" fn ilogb(x: f64) -> i32 {
15361    if x.is_nan() {
15362        feraiseexcept(FE_INVALID);
15363        return -0x7fffffff - 1; // FP_ILOGBNAN
15364    }
15365    if x == 0.0 || x.is_infinite() {
15366        feraiseexcept(FE_INVALID);
15367        return if x == 0.0 { -0x7fffffff - 1 } else { 0x7fffffff };
15368    }
15369    let bits = x.to_bits();
15370    let exp = ((bits >> 52) & 0x7ff) as i32;
15371    if exp == 0 {
15372        // subnormal
15373        let mut v = bits & 0xfffffffffffff;
15374        let mut e = -1022;
15375        while v < (1u64 << 52) { v <<= 1; e -= 1; }
15376        e
15377    } else {
15378        exp - 1023
15379    }
15380}
15381
15382#[no_mangle]
15383pub unsafe extern "C" fn logb(x: f64) -> f64 {
15384    if x.is_nan() { return x; }
15385    if x == 0.0 { return __math_divzero(1); }
15386    let bits = x.to_bits();
15387    let exp = ((bits >> 52) & 0x7ff) as i32;
15388    if exp == 0 {
15389        // subnormal
15390        let mut v = bits & 0xfffffffffffff;
15391        let mut e = -1022i32;
15392        while v < (1u64 << 52) { v <<= 1; e -= 1; }
15393        e as f64
15394    } else if exp == 0x7ff {
15395        x * x // infinity * infinity = infinity (preserves sign)
15396    } else {
15397        (exp - 1023) as f64
15398    }
15399}
15400
15401#[no_mangle]
15402pub unsafe extern "C" fn nearbyint(x: f64) -> f64 {
15403    let had_inexact = fetestexcept(FE_INEXACT) & FE_INEXACT != 0;
15404    let r = libm::rint(x);
15405    if !had_inexact {
15406        feclearexcept(FE_INEXACT);
15407    }
15408    r
15409}
15410
15411#[no_mangle]
15412pub unsafe extern "C" fn nextafter(x: f64, y: f64) -> f64 {
15413    if x.is_nan() || y.is_nan() { return x + y; }
15414    if x == 0.0 && y == 0.0 { return y; }
15415    if x == y { return x; }
15416    let r = libm::nextafter(x, y);
15417    if r.is_infinite() && x.is_finite() {
15418        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
15419    } else if r != x {
15420        let bits = r.to_bits();
15421        let is_subnormal = (bits & 0x7ff0000000000000) == 0 && (bits & 0xfffffffffffff) != 0;
15422        if r == 0.0 || is_subnormal {
15423            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
15424        }
15425    }
15426    r
15427}
15428
15429#[no_mangle]
15430pub unsafe extern "C" fn nexttoward(x: f64, y: f64) -> f64 {
15431    // On x86_64, long double = f64, so nexttoward = nextafter
15432    if x == 0.0 && y == 0.0 {
15433        return if y.is_sign_negative() { -0.0 } else { 0.0 };
15434    }
15435    nextafter(x, y)
15436}
15437
15438#[no_mangle]
15439pub unsafe extern "C" fn remainder(x: f64, y: f64) -> f64 {
15440    if x.is_nan() || y.is_nan() { return x + y; }
15441    if y == 0.0 || x.is_infinite() { return __math_invalid(x); }
15442    libm::remainder(x, y)
15443}
15444
15445#[no_mangle]
15446pub unsafe extern "C" fn remquo(x: f64, y: f64, quo: *mut i32) -> f64 {
15447    if x.is_nan() || y.is_nan() {
15448        if !quo.is_null() { *quo = 0; }
15449        return x + y;
15450    }
15451    if y == 0.0 || x.is_infinite() {
15452        if !quo.is_null() { *quo = 0; }
15453        return __math_invalid(x);
15454    }
15455    let (r, q) = libm::remquo(x, y);
15456    if !quo.is_null() { *quo = q; }
15457    r
15458}
15459
15460#[no_mangle]
15461pub unsafe extern "C" fn exp2(x: f64) -> f64 {
15462    exp2_impl(x)
15463}
15464
15465#[no_mangle]
15466pub unsafe extern "C" fn expm1(x: f64) -> f64 {
15467    let r = libm::expm1(x);
15468    // Raise UNDERFLOW for very small results that underflow
15469    if r != 0.0 && x != 0.0 && libm::fabs(x) < 1e-307 {
15470        feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
15471    }
15472    r
15473}
15474
15475#[no_mangle]
15476pub unsafe extern "C" fn log1p(x: f64) -> f64 {
15477    if x == -1.0 {
15478        feraiseexcept(FE_DIVBYZERO);
15479        return f64::NEG_INFINITY;
15480    }
15481    libm::log1p(x)
15482}
15483
15484#[no_mangle]
15485pub unsafe extern "C" fn acosh(x: f64) -> f64 {
15486    if x < 1.0 {
15487        feraiseexcept(FE_INVALID);
15488        return f64::NAN;
15489    }
15490    libm::acosh(x)
15491}
15492
15493#[no_mangle]
15494pub unsafe extern "C" fn asinh(x: f64) -> f64 {
15495    if x == 0.0 { return x; }
15496    libm::asinh(x)
15497}
15498
15499#[no_mangle]
15500pub unsafe extern "C" fn atanh(x: f64) -> f64 {
15501    if x == 0.0 { return x; }
15502    let e = ((x.to_bits() >> 52) & 0x7ff) as i32;
15503    if e < 0x3ff - 32 {
15504        feraiseexcept(FE_INEXACT);
15505        if e == 0 { feraiseexcept(FE_UNDERFLOW); }
15506        return x;
15507    }
15508    if x == 1.0 {
15509        feraiseexcept(FE_DIVBYZERO);
15510        return f64::INFINITY;
15511    }
15512    if x == -1.0 {
15513        feraiseexcept(FE_DIVBYZERO);
15514        return f64::NEG_INFINITY;
15515    }
15516    if x.is_nan() { return x; }
15517    let ax = libm::fabs(x);
15518    if ax > 1.0 {
15519        feraiseexcept(FE_INVALID);
15520        return f64::NAN;
15521    }
15522    if ax < 0.5 {
15523        // For small x: use log1p formula with |x| and negate
15524        let r = libm::log1p(2.0 * (ax + ax * ax / (1.0 - ax))) / 2.0;
15525        if x < 0.0 { -r } else { r }
15526    } else {
15527        // For larger x: use log formula with |x| and negate
15528        let r = 0.5 * libm::log((1.0 + ax) / (1.0 - ax));
15529        if x < 0.0 { -r } else { r }
15530    }
15531}
15532
15533#[no_mangle]
15534pub unsafe extern "C" fn cbrt(x: f64) -> f64 {
15535    libm::cbrt(x)
15536}
15537
15538#[no_mangle]
15539pub unsafe extern "C" fn erf(x: f64) -> f64 {
15540    erf_impl(x)
15541}
15542
15543#[no_mangle]
15544pub unsafe extern "C" fn erfc(x: f64) -> f64 {
15545    erfc_impl(x)
15546}
15547
15548#[no_mangle]
15549pub unsafe extern "C" fn lgamma(x: f64) -> f64 {
15550    lgamma_impl(x)
15551}
15552
15553#[no_mangle]
15554pub unsafe extern "C" fn tgamma(x: f64) -> f64 {
15555    tgamma_impl(x)
15556}
15557
15558#[no_mangle]
15559pub unsafe extern "C" fn lround(x: f64) -> core::ffi::c_long {
15560    libm::round(x) as core::ffi::c_long
15561}
15562
15563#[no_mangle]
15564pub unsafe extern "C" fn llround(x: f64) -> i64 {
15565    libm::round(x) as i64
15566}
15567
15568// ============================================================
15569// Complex math functions - using (f64, f64) pairs
15570// ============================================================
15571
15572// Helper: complex number as (real, imag) pair
15573// cabs: magnitude = sqrt(re^2 + im^2)
15574#[no_mangle]
15575pub unsafe extern "C" fn cabs(z: (f64, f64)) -> f64 {
15576    libm::sqrt(z.0 * z.0 + z.1 * z.1)
15577}
15578
15579#[no_mangle]
15580pub unsafe extern "C" fn cabsf(z: (f32, f32)) -> f32 {
15581    libm::sqrtf(z.0 * z.0 + z.1 * z.1)
15582}
15583
15584#[no_mangle]
15585pub unsafe extern "C" fn cabsl(z: (f64, f64)) -> f64 {
15586    cabs(z)
15587}
15588
15589#[no_mangle]
15590pub unsafe extern "C" fn carg(z: (f64, f64)) -> f64 {
15591    libm::atan2(z.1, z.0)
15592}
15593
15594#[no_mangle]
15595pub unsafe extern "C" fn cargf(z: (f32, f32)) -> f32 {
15596    libm::atan2f(z.1, z.0)
15597}
15598
15599#[no_mangle]
15600pub unsafe extern "C" fn cargl(z: (f64, f64)) -> f64 {
15601    carg(z)
15602}
15603
15604#[no_mangle]
15605pub unsafe extern "C" fn cimag(z: (f64, f64)) -> f64 {
15606    z.1
15607}
15608
15609#[no_mangle]
15610pub unsafe extern "C" fn cimagf(z: (f32, f32)) -> f32 {
15611    z.1
15612}
15613
15614#[no_mangle]
15615pub unsafe extern "C" fn cimagl(z: (f64, f64)) -> f64 {
15616    z.1
15617}
15618
15619#[no_mangle]
15620pub unsafe extern "C" fn creal(z: (f64, f64)) -> f64 {
15621    z.0
15622}
15623
15624#[no_mangle]
15625pub unsafe extern "C" fn crealf(z: (f32, f32)) -> f32 {
15626    z.0
15627}
15628
15629#[no_mangle]
15630pub unsafe extern "C" fn creall(z: (f64, f64)) -> f64 {
15631    z.0
15632}
15633
15634#[no_mangle]
15635pub unsafe extern "C" fn conj(z: (f64, f64)) -> (f64, f64) {
15636    (z.0, -z.1)
15637}
15638
15639#[no_mangle]
15640pub unsafe extern "C" fn conjf(z: (f32, f32)) -> (f32, f32) {
15641    (z.0, -z.1)
15642}
15643
15644#[no_mangle]
15645pub unsafe extern "C" fn conjl(z: (f64, f64)) -> (f64, f64) {
15646    conj(z)
15647}
15648
15649#[no_mangle]
15650pub unsafe extern "C" fn cproj(z: (f64, f64)) -> (f64, f64) {
15651    if z.0.is_infinite() || z.1.is_infinite() {
15652        (f64::INFINITY, if z.1.is_sign_positive() { 0.0 } else { -0.0 })
15653    } else {
15654        z
15655    }
15656}
15657
15658#[no_mangle]
15659pub unsafe extern "C" fn cprojf(z: (f32, f32)) -> (f32, f32) {
15660    if z.0.is_infinite() || z.1.is_infinite() {
15661        (f32::INFINITY, if z.1.is_sign_positive() { 0.0 } else { -0.0 })
15662    } else {
15663        z
15664    }
15665}
15666
15667#[no_mangle]
15668pub unsafe extern "C" fn cprojl(z: (f64, f64)) -> (f64, f64) {
15669    cproj(z)
15670}
15671
15672// cexp: e^z = e^(re + i*im) = e^re * (cos(im) + i*sin(im))
15673#[no_mangle]
15674pub unsafe extern "C" fn cexp(z: (f64, f64)) -> (f64, f64) {
15675    let r = libm::exp(z.0);
15676    (r * libm::cos(z.1), r * libm::sin(z.1))
15677}
15678
15679#[no_mangle]
15680pub unsafe extern "C" fn cexpf(z: (f32, f32)) -> (f32, f32) {
15681    let r = libm::expf(z.0);
15682    (r * libm::cosf(z.1), r * libm::sinf(z.1))
15683}
15684
15685#[no_mangle]
15686pub unsafe extern "C" fn cexpl(z: (f64, f64)) -> (f64, f64) {
15687    cexp(z)
15688}
15689
15690// clog: ln(z) = ln|z| + i*arg(z)
15691#[no_mangle]
15692pub unsafe extern "C" fn clog(z: (f64, f64)) -> (f64, f64) {
15693    (libm::log(cabs(z)), carg(z))
15694}
15695
15696#[no_mangle]
15697pub unsafe extern "C" fn clogf(z: (f32, f32)) -> (f32, f32) {
15698    (libm::logf(cabsf(z)), cargf(z))
15699}
15700
15701#[no_mangle]
15702pub unsafe extern "C" fn clogl(z: (f64, f64)) -> (f64, f64) {
15703    clog(z)
15704}
15705
15706// csqrt: sqrt(z) = sqrt((|z|+re)/2) + i*sign(im)*sqrt((|z|-re)/2)
15707#[no_mangle]
15708pub unsafe extern "C" fn csqrt(z: (f64, f64)) -> (f64, f64) {
15709    let r = cabs(z);
15710    let sign = if z.1 < 0.0 { -1.0 } else { 1.0 };
15711    (libm::sqrt((r + z.0) / 2.0), sign * libm::sqrt((r - z.0) / 2.0))
15712}
15713
15714#[no_mangle]
15715pub unsafe extern "C" fn csqrtf(z: (f32, f32)) -> (f32, f32) {
15716    let r = cabsf(z);
15717    let sign = if z.1 < 0.0 { -1.0f32 } else { 1.0f32 };
15718    (libm::sqrtf((r + z.0) / 2.0), sign * libm::sqrtf((r - z.0) / 2.0))
15719}
15720
15721#[no_mangle]
15722pub unsafe extern "C" fn csqrtl(z: (f64, f64)) -> (f64, f64) {
15723    csqrt(z)
15724}
15725
15726// cpow: z^w = e^(w * log(z))
15727#[no_mangle]
15728pub unsafe extern "C" fn cpow(z: (f64, f64), w: (f64, f64)) -> (f64, f64) {
15729    let log_z = clog(z);
15730    let exp_arg = (w.0 * log_z.0 - w.1 * log_z.1, w.0 * log_z.1 + w.1 * log_z.0);
15731    cexp(exp_arg)
15732}
15733
15734#[no_mangle]
15735pub unsafe extern "C" fn cpowf(z: (f32, f32), w: (f32, f32)) -> (f32, f32) {
15736    let log_z = clogf(z);
15737    let exp_arg = (w.0 * log_z.0 - w.1 * log_z.1, w.0 * log_z.1 + w.1 * log_z.0);
15738    cexpf(exp_arg)
15739}
15740
15741#[no_mangle]
15742pub unsafe extern "C" fn cpowl(z: (f64, f64), w: (f64, f64)) -> (f64, f64) {
15743    cpow(z, w)
15744}
15745
15746// ccos: cos(z) = cos(re)*cosh(im) - i*sin(re)*sinh(im)
15747#[no_mangle]
15748pub unsafe extern "C" fn ccos(z: (f64, f64)) -> (f64, f64) {
15749    (libm::cos(z.0) * libm::cosh(z.1), -libm::sin(z.0) * libm::sinh(z.1))
15750}
15751
15752#[no_mangle]
15753pub unsafe extern "C" fn ccosf(z: (f32, f32)) -> (f32, f32) {
15754    (libm::cosf(z.0) * libm::coshf(z.1), -libm::sinf(z.0) * libm::sinhf(z.1))
15755}
15756
15757#[no_mangle]
15758pub unsafe extern "C" fn ccosl(z: (f64, f64)) -> (f64, f64) {
15759    ccos(z)
15760}
15761
15762// csin: sin(z) = sin(re)*cosh(im) + i*cos(re)*sinh(im)
15763#[no_mangle]
15764pub unsafe extern "C" fn csin(z: (f64, f64)) -> (f64, f64) {
15765    (libm::sin(z.0) * libm::cosh(z.1), libm::cos(z.0) * libm::sinh(z.1))
15766}
15767
15768#[no_mangle]
15769pub unsafe extern "C" fn csinf(z: (f32, f32)) -> (f32, f32) {
15770    (libm::sinf(z.0) * libm::coshf(z.1), libm::cosf(z.0) * libm::sinhf(z.1))
15771}
15772
15773#[no_mangle]
15774pub unsafe extern "C" fn csinl(z: (f64, f64)) -> (f64, f64) {
15775    csin(z)
15776}
15777
15778// ctan: tan(z) = sin(2re)/(cos(2re)+cosh(2im)) + i*sinh(2im)/(cos(2re)+cosh(2im))
15779#[no_mangle]
15780pub unsafe extern "C" fn ctan(z: (f64, f64)) -> (f64, f64) {
15781    let d = libm::cos(2.0 * z.0) + libm::cosh(2.0 * z.1);
15782    (libm::sin(2.0 * z.0) / d, libm::sinh(2.0 * z.1) / d)
15783}
15784
15785#[no_mangle]
15786pub unsafe extern "C" fn ctanf(z: (f32, f32)) -> (f32, f32) {
15787    let d = libm::cosf(2.0 * z.0) + libm::coshf(2.0 * z.1);
15788    (libm::sinf(2.0 * z.0) / d, libm::sinhf(2.0 * z.1) / d)
15789}
15790
15791#[no_mangle]
15792pub unsafe extern "C" fn ctanl(z: (f64, f64)) -> (f64, f64) {
15793    ctan(z)
15794}
15795
15796// ccosh: cosh(z) = cosh(re)*cos(im) + i*sinh(re)*sin(im)
15797#[no_mangle]
15798pub unsafe extern "C" fn ccosh(z: (f64, f64)) -> (f64, f64) {
15799    (libm::cosh(z.0) * libm::cos(z.1), libm::sinh(z.0) * libm::sin(z.1))
15800}
15801
15802#[no_mangle]
15803pub unsafe extern "C" fn ccoshf(z: (f32, f32)) -> (f32, f32) {
15804    (libm::coshf(z.0) * libm::cosf(z.1), libm::sinhf(z.0) * libm::sinf(z.1))
15805}
15806
15807#[no_mangle]
15808pub unsafe extern "C" fn ccoshl(z: (f64, f64)) -> (f64, f64) {
15809    ccosh(z)
15810}
15811
15812// csinh: sinh(z) = sinh(re)*cos(im) + i*cosh(re)*sin(im)
15813#[no_mangle]
15814pub unsafe extern "C" fn csinh(z: (f64, f64)) -> (f64, f64) {
15815    (libm::sinh(z.0) * libm::cos(z.1), libm::cosh(z.0) * libm::sin(z.1))
15816}
15817
15818#[no_mangle]
15819pub unsafe extern "C" fn csinhf(z: (f32, f32)) -> (f32, f32) {
15820    (libm::sinhf(z.0) * libm::cosf(z.1), libm::coshf(z.0) * libm::sinf(z.1))
15821}
15822
15823#[no_mangle]
15824pub unsafe extern "C" fn csinhl(z: (f64, f64)) -> (f64, f64) {
15825    csinh(z)
15826}
15827
15828// ctanh: tanh(z) = sinh(2re)/(cosh(2re)+cos(2im)) + i*sin(2im)/(cosh(2re)+cos(2im))
15829#[no_mangle]
15830pub unsafe extern "C" fn ctanh(z: (f64, f64)) -> (f64, f64) {
15831    let d = libm::cosh(2.0 * z.0) + libm::cos(2.0 * z.1);
15832    (libm::sinh(2.0 * z.0) / d, libm::sin(2.0 * z.1) / d)
15833}
15834
15835#[no_mangle]
15836pub unsafe extern "C" fn ctanhf(z: (f32, f32)) -> (f32, f32) {
15837    let d = libm::coshf(2.0 * z.0) + libm::cosf(2.0 * z.1);
15838    (libm::sinhf(2.0 * z.0) / d, libm::sinf(2.0 * z.1) / d)
15839}
15840
15841#[no_mangle]
15842pub unsafe extern "C" fn ctanhl(z: (f64, f64)) -> (f64, f64) {
15843    ctanh(z)
15844}
15845
15846// cacos: acos(z) = pi/2 - asin(z)
15847// asin(z) = -i * log(i*z + sqrt(1 - z^2))
15848#[no_mangle]
15849pub unsafe extern "C" fn cacos(z: (f64, f64)) -> (f64, f64) {
15850    let asin_z = casin(z);
15851    (3.14159265358979323846264338327950288419716939937510582097494459230781640 / 2.0 - asin_z.0, -asin_z.1)
15852}
15853
15854#[no_mangle]
15855pub unsafe extern "C" fn cacosf(z: (f32, f32)) -> (f32, f32) {
15856    let asin_z = casinf(z);
15857    (3.14159265358979323846264338327950288419716939937510582097494459230781640f32 / 2.0 - asin_z.0, -asin_z.1)
15858}
15859
15860#[no_mangle]
15861pub unsafe extern "C" fn cacosl(z: (f64, f64)) -> (f64, f64) {
15862    cacos(z)
15863}
15864
15865// casin: asin(z) = -i * log(i*z + sqrt(1 - z^2))
15866#[no_mangle]
15867pub unsafe extern "C" fn casin(z: (f64, f64)) -> (f64, f64) {
15868    // i*z = (-z.1, z.0)
15869    let iz = (-z.1, z.0);
15870    // 1 - z^2 = 1 - (z.0^2 - z.1^2 + 2i*z.0*z.1) = (1 - z.0^2 + z.1^2, -2*z.0*z.1)
15871    let one_minus_z2 = (1.0 - z.0 * z.0 + z.1 * z.1, -2.0 * z.0 * z.1);
15872    let sqrt_val = csqrt(one_minus_z2);
15873    let arg = clog((iz.0 + sqrt_val.0, iz.1 + sqrt_val.1));
15874    // -i * log(...) = (arg.1, -arg.0)
15875    (arg.1, -arg.0)
15876}
15877
15878#[no_mangle]
15879pub unsafe extern "C" fn casinf(z: (f32, f32)) -> (f32, f32) {
15880    let iz = (-z.1, z.0);
15881    let one_minus_z2 = (1.0 - z.0 * z.0 + z.1 * z.1, -2.0 * z.0 * z.1);
15882    let sqrt_val = csqrtf(one_minus_z2);
15883    let arg = clogf((iz.0 + sqrt_val.0, iz.1 + sqrt_val.1));
15884    (arg.1, -arg.0)
15885}
15886
15887#[no_mangle]
15888pub unsafe extern "C" fn casinl(z: (f64, f64)) -> (f64, f64) {
15889    casin(z)
15890}
15891
15892// catan: atan(z) = (i/2) * log((1 - i*z)/(1 + i*z))
15893#[no_mangle]
15894pub unsafe extern "C" fn catan(z: (f64, f64)) -> (f64, f64) {
15895    // i*z = (-z.1, z.0)
15896    // 1 - i*z = (1 + z.1, -z.0)
15897    // 1 + i*z = (1 - z.1, z.0)
15898    let num = (1.0 + z.1, -z.0);
15899    let den = (1.0 - z.1, z.0);
15900    let ratio = cdiv(num, den);
15901    let log_ratio = clog(ratio);
15902    // (i/2) * log = (-log.1/2, log.0/2)
15903    (-log_ratio.1 / 2.0, log_ratio.0 / 2.0)
15904}
15905
15906#[no_mangle]
15907pub unsafe extern "C" fn catanf(z: (f32, f32)) -> (f32, f32) {
15908    let num = (1.0 + z.1, -z.0);
15909    let den = (1.0 - z.1, z.0);
15910    let ratio = cdivf(num, den);
15911    let log_ratio = clogf(ratio);
15912    (-log_ratio.1 / 2.0, log_ratio.0 / 2.0)
15913}
15914
15915#[no_mangle]
15916pub unsafe extern "C" fn catanl(z: (f64, f64)) -> (f64, f64) {
15917    catan(z)
15918}
15919
15920// Helper: complex division
15921fn cdiv(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
15922    let d = b.0 * b.0 + b.1 * b.1;
15923    ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
15924}
15925
15926fn cdivf(a: (f32, f32), b: (f32, f32)) -> (f32, f32) {
15927    let d = b.0 * b.0 + b.1 * b.1;
15928    ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
15929}
15930
15931// cacosh: acosh(z) = log(z + sqrt(z^2 - 1))
15932#[no_mangle]
15933pub unsafe extern "C" fn cacosh(z: (f64, f64)) -> (f64, f64) {
15934    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
15935    let z2_minus_1 = (z2.0 - 1.0, z2.1);
15936    let sqrt_val = csqrt(z2_minus_1);
15937    clog((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
15938}
15939
15940#[no_mangle]
15941pub unsafe extern "C" fn cacoshf(z: (f32, f32)) -> (f32, f32) {
15942    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
15943    let z2_minus_1 = (z2.0 - 1.0, z2.1);
15944    let sqrt_val = csqrtf(z2_minus_1);
15945    clogf((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
15946}
15947
15948#[no_mangle]
15949pub unsafe extern "C" fn cacoshl(z: (f64, f64)) -> (f64, f64) {
15950    cacosh(z)
15951}
15952
15953// casinh: asinh(z) = log(z + sqrt(z^2 + 1))
15954#[no_mangle]
15955pub unsafe extern "C" fn casinh(z: (f64, f64)) -> (f64, f64) {
15956    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
15957    let z2_plus_1 = (z2.0 + 1.0, z2.1);
15958    let sqrt_val = csqrt(z2_plus_1);
15959    clog((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
15960}
15961
15962#[no_mangle]
15963pub unsafe extern "C" fn casinhf(z: (f32, f32)) -> (f32, f32) {
15964    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
15965    let z2_plus_1 = (z2.0 + 1.0, z2.1);
15966    let sqrt_val = csqrtf(z2_plus_1);
15967    clogf((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
15968}
15969
15970#[no_mangle]
15971pub unsafe extern "C" fn casinhl(z: (f64, f64)) -> (f64, f64) {
15972    casinh(z)
15973}
15974
15975// catanh: atanh(z) = (1/2) * log((1+z)/(1-z))
15976#[no_mangle]
15977pub unsafe extern "C" fn catanh(z: (f64, f64)) -> (f64, f64) {
15978    let num = (1.0 + z.0, z.1);
15979    let den = (1.0 - z.0, -z.1);
15980    let ratio = cdiv(num, den);
15981    let log_ratio = clog(ratio);
15982    (log_ratio.0 / 2.0, log_ratio.1 / 2.0)
15983}
15984
15985#[no_mangle]
15986pub unsafe extern "C" fn catanhf(z: (f32, f32)) -> (f32, f32) {
15987    let num = (1.0 + z.0, z.1);
15988    let den = (1.0 - z.0, -z.1);
15989    let ratio = cdivf(num, den);
15990    let log_ratio = clogf(ratio);
15991    (log_ratio.0 / 2.0, log_ratio.1 / 2.0)
15992}
15993
15994#[no_mangle]
15995pub unsafe extern "C" fn catanhl(z: (f64, f64)) -> (f64, f64) {
15996    catanh(z)
15997}
15998
15999// ============================================================
16000// Float math functions (f32 versions)
16001// ============================================================
16002
16003#[inline(never)]
16004#[no_mangle]
16005pub unsafe extern "C" fn fmaxf(x: f32, y: f32) -> f32 {
16006    fmaxf_impl(x, y)
16007}
16008
16009#[no_mangle]
16010pub unsafe extern "C" fn fdimf(x: f32, y: f32) -> f32 {
16011    if x.is_nan() || y.is_nan() {
16012        return f32::NAN;
16013    }
16014    if x > y { x - y } else { 0.0 }
16015}
16016
16017#[no_mangle]
16018pub unsafe extern "C" fn fmaf(x: f32, y: f32, z: f32) -> f32 {
16019    if (x.is_infinite() && y == 0.0) || (y.is_infinite() && x == 0.0) {
16020        feraiseexcept(FE_INVALID);
16021        return f32::NAN;
16022    }
16023    if x.is_nan() || y.is_nan() || z.is_nan() {
16024        return f32::NAN;
16025    }
16026    let r = libm::fmaf(x, y, z);
16027    if r.is_nan() {
16028        feraiseexcept(FE_INVALID);
16029    }
16030    r
16031}
16032
16033#[no_mangle]
16034pub unsafe extern "C" fn ilogbf(x: f32) -> i32 {
16035    if x.is_nan() {
16036        feraiseexcept(FE_INVALID);
16037        return -0x7fffffff - 1;
16038    }
16039    if x == 0.0 || x.is_infinite() {
16040        feraiseexcept(FE_INVALID);
16041        return if x == 0.0 { -0x7fffffff - 1 } else { 0x7fffffff };
16042    }
16043    let bits = x.to_bits();
16044    let exp = ((bits >> 23) & 0xff) as i32;
16045    if exp == 0 {
16046        let mut v = bits & 0x7fffff;
16047        let mut e = -126;
16048        while v < (1u32 << 23) { v <<= 1; e -= 1; }
16049        e
16050    } else {
16051        exp - 127
16052    }
16053}
16054
16055#[no_mangle]
16056pub unsafe extern "C" fn logbf(x: f32) -> f32 {
16057    if x.is_nan() { return x; }
16058    if x == 0.0 { return __math_divzerof(1); }
16059    let bits = x.to_bits();
16060    let exp = ((bits >> 23) & 0xff) as i32;
16061    if exp == 0 {
16062        let mut v = bits & 0x7fffff;
16063        let mut e = -126i32;
16064        while v < (1u32 << 23) { v <<= 1; e -= 1; }
16065        e as f32
16066    } else if exp == 0xff {
16067        x * x
16068    } else {
16069        (exp - 127) as f32
16070    }
16071}
16072
16073#[no_mangle]
16074pub unsafe extern "C" fn nearbyintf(x: f32) -> f32 {
16075    let had_inexact = fetestexcept(FE_INEXACT) & FE_INEXACT != 0;
16076    let r = libm::rintf(x);
16077    if !had_inexact {
16078        feclearexcept(FE_INEXACT);
16079    }
16080    r
16081}
16082
16083#[no_mangle]
16084pub unsafe extern "C" fn nextafterf(x: f32, y: f32) -> f32 {
16085    if x.is_nan() || y.is_nan() { return x + y; }
16086    if x == 0.0 && y == 0.0 { return y; }
16087    if x == y { return x; }
16088    let r = libm::nextafterf(x, y);
16089    if r.is_infinite() && x.is_finite() {
16090        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
16091    } else if r != x {
16092        let bits = r.to_bits();
16093        let is_subnormal = (bits & 0x7f800000) == 0 && (bits & 0x7fffff) != 0;
16094        if r == 0.0 || is_subnormal {
16095            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16096        }
16097    }
16098    r
16099}
16100
16101#[no_mangle]
16102#[cfg(target_arch = "x86_64")]
16103pub unsafe extern "C" fn nexttowardf(x: f32, y: f64) -> f32 {
16104    if y.is_nan() { return (x as f64 + y) as f32; }
16105    if x == 0.0 && y == 0.0 {
16106        return if y.is_sign_negative() { -0.0 } else { 0.0 };
16107    }
16108    if (x as f64) == y { return x; }
16109    nextafterf(x, if y > x as f64 { f32::INFINITY } else { f32::NEG_INFINITY })
16110}
16111
16112#[no_mangle]
16113#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
16114pub unsafe extern "C" fn nexttowardf(x: f32, y: f128) -> f32 {
16115    if y.is_nan() { return (x as f128 + y) as f32; }
16116    if (x as f128) == y { return x; }
16117    nextafterf(x, if y > x as f128 { f32::INFINITY } else { f32::NEG_INFINITY })
16118}
16119
16120#[no_mangle]
16121pub unsafe extern "C" fn remainderf(x: f32, y: f32) -> f32 {
16122    if x.is_nan() || y.is_nan() { return x + y; }
16123    if y == 0.0 || x.is_infinite() { return __math_invalidf(x); }
16124    libm::remainderf(x, y)
16125}
16126
16127#[no_mangle]
16128pub unsafe extern "C" fn remquof(x: f32, y: f32, quo: *mut i32) -> f32 {
16129    if x.is_nan() || y.is_nan() {
16130        if !quo.is_null() { *quo = 0; }
16131        return x + y;
16132    }
16133    if y == 0.0 || x.is_infinite() {
16134        if !quo.is_null() { *quo = 0; }
16135        return __math_invalidf(x);
16136    }
16137    let (r, q) = libm::remquof(x, y);
16138    if !quo.is_null() { *quo = q; }
16139    r
16140}
16141
16142#[no_mangle]
16143pub unsafe extern "C" fn exp2f(x: f32) -> f32 {
16144    if x == f32::INFINITY { return f32::INFINITY; }
16145    if x == f32::NEG_INFINITY { return 0.0; }
16146    if x.is_nan() { return f32::NAN; }
16147    let r = libm::exp2f(x);
16148    if r.is_infinite() && x.is_finite() {
16149        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
16150    } else if r == 0.0 && x < -149.0 {
16151        feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16152    } else if r != 0.0 && x != libm::truncf(x) {
16153        let bits = r.to_bits();
16154        if (bits & 0x7f800000) == 0 {
16155            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16156        }
16157    }
16158    r
16159}
16160
16161#[no_mangle]
16162pub unsafe extern "C" fn expm1f(x: f32) -> f32 {
16163    libm::expm1f(x)
16164}
16165
16166#[no_mangle]
16167pub unsafe extern "C" fn log1pf(x: f32) -> f32 {
16168    if x == -1.0 {
16169        feraiseexcept(FE_DIVBYZERO);
16170        return f32::NEG_INFINITY;
16171    }
16172    libm::log1pf(x)
16173}
16174
16175#[no_mangle]
16176pub unsafe extern "C" fn acoshf(x: f32) -> f32 {
16177    if x < 1.0 {
16178        feraiseexcept(FE_INVALID);
16179        return f32::NAN;
16180    }
16181    libm::acoshf(x)
16182}
16183
16184#[no_mangle]
16185pub unsafe extern "C" fn asinhf(x: f32) -> f32 {
16186    if x == 0.0 { return x; }
16187    libm::asinhf(x)
16188}
16189
16190#[no_mangle]
16191pub unsafe extern "C" fn atanhf(x: f32) -> f32 {
16192    if x == 0.0 { return x; }
16193    let e = ((x.to_bits() >> 23) & 0xff) as i32;
16194    if e < 0x7f - 32 {
16195        feraiseexcept(FE_INEXACT);
16196        if e == 0 { feraiseexcept(FE_UNDERFLOW); }
16197        return x;
16198    }
16199    if x == 1.0 {
16200        feraiseexcept(FE_DIVBYZERO);
16201        return f32::INFINITY;
16202    }
16203    if x == -1.0 {
16204        feraiseexcept(FE_DIVBYZERO);
16205        return f32::NEG_INFINITY;
16206    }
16207    if x.is_nan() { return x; }
16208    let ax = libm::fabsf(x);
16209    if ax > 1.0 {
16210        feraiseexcept(FE_INVALID);
16211        return f32::NAN;
16212    }
16213    if ax < 0.5 {
16214        let r = libm::log1pf(2.0 * (ax + ax * ax / (1.0 - ax))) / 2.0;
16215        if x < 0.0 { -r } else { r }
16216    } else {
16217        let r = 0.5 * libm::logf((1.0 + ax) / (1.0 - ax));
16218        if x < 0.0 { -r } else { r }
16219    }
16220}
16221
16222#[no_mangle]
16223pub unsafe extern "C" fn cbrtf(x: f32) -> f32 {
16224    libm::cbrtf(x)
16225}
16226
16227#[no_mangle]
16228pub unsafe extern "C" fn erff(x: f32) -> f32 {
16229    libm::erff(x)
16230}
16231
16232#[no_mangle]
16233pub unsafe extern "C" fn erfcf(x: f32) -> f32 {
16234    libm::erfcf(x)
16235}
16236
16237#[no_mangle]
16238pub unsafe extern "C" fn lgammaf(x: f32) -> f32 {
16239    if x.is_nan() {
16240        crate::signgam = 1;
16241        return x;
16242    }
16243    if x == 0.0 {
16244        crate::signgam = if x.is_sign_negative() { -1 } else { 1 };
16245        feraiseexcept(FE_DIVBYZERO);
16246        return f32::INFINITY;
16247    }
16248    let (r, sign) = libm::lgammaf_r(x);
16249    crate::signgam = sign;
16250    r
16251}
16252
16253#[no_mangle]
16254pub unsafe extern "C" fn tgammaf(x: f32) -> f32 {
16255    if x.is_nan() { return x; }
16256    if x == 0.0 {
16257        feraiseexcept(FE_DIVBYZERO);
16258        return if x.is_sign_negative() { f32::NEG_INFINITY } else { f32::INFINITY };
16259    }
16260    if x.is_infinite() {
16261        return if x.is_sign_negative() { __math_invalidf(x) } else { f32::INFINITY };
16262    }
16263    if x < 0.0 && x == libm::floorf(x) {
16264        feraiseexcept(FE_INVALID);
16265        return f32::NAN;
16266    }
16267    libm::tgammaf(x)
16268}
16269
16270#[no_mangle]
16271pub unsafe extern "C" fn lroundf(x: f32) -> core::ffi::c_long {
16272    libm::roundf(x) as core::ffi::c_long
16273}
16274
16275#[no_mangle]
16276pub unsafe extern "C" fn llroundf(x: f32) -> i64 {
16277    libm::roundf(x) as i64
16278}
16279
16280// ============================================================
16281// Wide char functions
16282// ============================================================
16283
16284#[no_mangle]
16285pub unsafe extern "C" fn wcscasecmp(s1: *const u32, s2: *const u32) -> i32 {
16286    let mut i = 0;
16287    loop {
16288        let c1 = *s1.add(i);
16289        let c2 = *s2.add(i);
16290        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16291        let l1 = if c1 >= 'A' as u32 && c1 <= 'Z' as u32 { c1 + 32 } else { c1 };
16292        let l2 = if c2 >= 'A' as u32 && c2 <= 'Z' as u32 { c2 + 32 } else { c2 };
16293        if l1 != l2 { return (l1 as i32) - (l2 as i32); }
16294        i += 1;
16295    }
16296}
16297
16298#[no_mangle]
16299pub unsafe extern "C" fn wcscasecmp_l(s1: *const u32, s2: *const u32, _loc: *mut core::ffi::c_void) -> i32 {
16300    wcscasecmp(s1, s2)
16301}
16302
16303#[no_mangle]
16304pub unsafe extern "C" fn wcsncasecmp(s1: *const u32, s2: *const u32, n: usize) -> i32 {
16305    let mut i = 0;
16306    while i < n {
16307        let c1 = *s1.add(i);
16308        let c2 = *s2.add(i);
16309        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16310        let l1 = if c1 >= 'A' as u32 && c1 <= 'Z' as u32 { c1 + 32 } else { c1 };
16311        let l2 = if c2 >= 'A' as u32 && c2 <= 'Z' as u32 { c2 + 32 } else { c2 };
16312        if l1 != l2 { return (l1 as i32) - (l2 as i32); }
16313        i += 1;
16314    }
16315    0
16316}
16317
16318#[no_mangle]
16319pub unsafe extern "C" fn wcsncasecmp_l(s1: *const u32, s2: *const u32, n: usize, _loc: *mut core::ffi::c_void) -> i32 {
16320    wcsncasecmp(s1, s2, n)
16321}
16322
16323#[no_mangle]
16324pub unsafe extern "C" fn wcscoll(s1: *const u32, s2: *const u32) -> i32 {
16325    // ponytail: simplified collation - just compare codepoints
16326    let mut i = 0;
16327    loop {
16328        let c1 = *s1.add(i);
16329        let c2 = *s2.add(i);
16330        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16331        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
16332        i += 1;
16333    }
16334}
16335
16336#[no_mangle]
16337pub unsafe extern "C" fn wcstok(s: *mut u32, sep: *const u32, p: *mut *mut u32) -> *mut u32 {
16338    let mut src = if s.is_null() { *p } else { s };
16339    // Skip leading separators
16340    while *src != 0 && *sep.add(0) == *src { src = src.add(1); }
16341    if *src == 0 { return core::ptr::null_mut(); }
16342    let start = src;
16343    // Find end of token
16344    while *src != 0 && *sep.add(0) != *src { src = src.add(1); }
16345    if *src != 0 {
16346        *src = 0;
16347        *p = src.add(1);
16348    } else {
16349        *p = src;
16350    }
16351    start
16352}
16353
16354#[no_mangle]
16355pub unsafe extern "C" fn wcswcs(haystack: *const u32, needle: *const u32) -> *mut u32 {
16356    if *needle == 0 { return haystack as *mut u32; }
16357    let mut i = 0;
16358    while *haystack.add(i) != 0 {
16359        let mut j = 0;
16360        while *needle.add(j) != 0 && *haystack.add(i + j) == *needle.add(j) {
16361            j += 1;
16362        }
16363        if *needle.add(j) == 0 { return haystack.add(i) as *mut u32; }
16364        i += 1;
16365    }
16366    core::ptr::null_mut()
16367}
16368
16369#[no_mangle]
16370pub unsafe extern "C" fn wcswidth(s: *const u32, n: usize) -> i32 {
16371    let mut width = 0i32;
16372    let mut i = 0;
16373    while i < n {
16374        let c = *s.add(i);
16375        if c == 0 { break; }
16376        // ponytail: simplified width - assume all printable chars are width 1
16377        width += 1;
16378        i += 1;
16379    }
16380    width
16381}
16382
16383#[no_mangle]
16384pub unsafe extern "C" fn wcsftime(s: *mut u32, maxsize: usize, fmt: *const u32, tm: *const c_void) -> usize {
16385    if s.is_null() || fmt.is_null() || maxsize == 0 { return 0; }
16386    // Convert the wide format string to multibyte, let strftime do the work,
16387    // then convert the result back.
16388    let mut cfmt = [0u8; 1024];
16389    let mut o = 0usize;
16390    let mut i = 0usize;
16391    let mut st: c_uint = 0;
16392    while *fmt.add(i) != 0 && o + 8 < cfmt.len() {
16393        let n = wcrtomb(
16394            cfmt.as_mut_ptr().add(o) as *mut c_char,
16395            *fmt.add(i) as c_int,
16396            &mut st as *mut c_uint,
16397        );
16398        if n == !0usize { return 0; }
16399        o += n;
16400        i += 1;
16401    }
16402    cfmt[o] = 0;
16403    let mut out = [0u8; 4096];
16404    let mut lim = maxsize.saturating_mul(4);
16405    if lim > out.len() { lim = out.len(); }
16406    let n = strftime(out.as_mut_ptr() as *mut c_char, lim, cfmt.as_ptr() as *const c_char, tm as *const tm);
16407    if n == 0 { return 0; }
16408    let mut ws = 0usize;
16409    let mut p = 0usize;
16410    while p < n && ws + 1 < maxsize {
16411        let mut wc: c_int = 0;
16412        let mut st2: c_uint = 0;
16413        let r = mbrtowc(&mut wc, out.as_ptr().add(p) as *const c_char, n - p, &mut st2);
16414        if r == !0usize { return 0; }
16415        if r == 0 || r == !1usize { break; }
16416        *s.add(ws) = wc as u32;
16417        ws += 1;
16418        p += r;
16419    }
16420    *s.add(ws) = 0;
16421    ws
16422}
16423
16424#[no_mangle]
16425pub unsafe extern "C" fn mbsnrtowcs(
16426    dst: *mut u32,
16427    src: *mut *const u8,
16428    nms: usize,
16429    len: usize,
16430    st: *mut core::ffi::c_void,
16431) -> usize {
16432    if src.is_null() { return 0; }
16433    let mut s = *src;
16434    if s.is_null() { return 0; }
16435    let state = st as *mut c_uint;
16436    let limit = if dst.is_null() { usize::MAX } else { len };
16437    let mut count = 0usize;
16438    let mut n = nms;
16439    while count < limit && n > 0 {
16440        let c = *s;
16441        if c == 0 {
16442            if !dst.is_null() {
16443                if count < len { *dst.add(count) = 0; }
16444                *src = core::ptr::null();
16445            }
16446            return count;
16447        }
16448        let mut wc: c_int = 0;
16449        let r = mbrtowc(&mut wc, s as *const c_char, n, state);
16450        if r == !0usize {
16451            *src = s;
16452            return !0usize;
16453        }
16454        if r == !1usize { break; }
16455        if !dst.is_null() { *dst.add(count) = wc as u32; }
16456        count += 1;
16457        s = s.add(r);
16458        n -= r;
16459    }
16460    *src = s;
16461    count
16462}
16463
16464#[no_mangle]
16465pub unsafe extern "C" fn wcsnrtombs(dst: *mut u8, src: *mut *const u32, nwc: usize, len: usize, _st: *mut core::ffi::c_void) -> usize {
16466    let mut count = 0;
16467    let mut s = *src;
16468    let mut d = dst;
16469    while count < len && count < nwc {
16470        let c = *s;
16471        if c == 0 { break; }
16472        if !d.is_null() {
16473            if c < 0x80 {
16474                *d = c as u8;
16475                d = d.add(1);
16476                count += 1;
16477            } else if c < 0x800 {
16478                if count + 2 > len { break; }
16479                *d = 0xc0 | (c >> 6) as u8;
16480                *d.add(1) = 0x80 | (c & 0x3f) as u8;
16481                d = d.add(2);
16482                count += 2;
16483            } else if c < 0x10000 {
16484                if count + 3 > len { break; }
16485                *d = 0xe0 | (c >> 12) as u8;
16486                *d.add(1) = 0x80 | ((c >> 6) & 0x3f) as u8;
16487                *d.add(2) = 0x80 | (c & 0x3f) as u8;
16488                d = d.add(3);
16489                count += 3;
16490            } else {
16491                if count + 4 > len { break; }
16492                *d = 0xf0 | (c >> 18) as u8;
16493                *d.add(1) = 0x80 | ((c >> 12) & 0x3f) as u8;
16494                *d.add(2) = 0x80 | ((c >> 6) & 0x3f) as u8;
16495                *d.add(3) = 0x80 | (c & 0x3f) as u8;
16496                d = d.add(4);
16497                count += 4;
16498            }
16499        }
16500        s = s.add(1);
16501    }
16502    if !dst.is_null() { *src = s; }
16503    count
16504}
16505
16506// ============================================================
16507// Thread sync functions (C11 threads)
16508// ============================================================
16509
16510
16511// C11 thread types
16512pub type thrd_start_t = Option<unsafe extern "C" fn(arg: *mut core::ffi::c_void) -> i32>;
16513
16514// Thread function stubs - these need actual implementation
16515#[no_mangle]
16516pub unsafe extern "C" fn thrd_create(thr: *mut usize, func: thrd_start_t, arg: *mut core::ffi::c_void) -> i32 {
16517    let mut thread: u64 = 0;
16518    let r = pthread_create(&mut thread, core::ptr::null(), core::mem::transmute(func), arg);
16519    if r == 0 {
16520        *thr = thread as usize;
16521        0 // thrd_success
16522    } else {
16523        -1 // thrd_nomem
16524    }
16525}
16526
16527#[no_mangle]
16528pub unsafe extern "C" fn thrd_join(thr: usize, res: *mut i32) -> i32 {
16529    let mut retval: *mut core::ffi::c_void = core::ptr::null_mut();
16530    let r = pthread_join(thr as u64, &mut retval);
16531    if r == 0 {
16532        if !res.is_null() { *res = retval as i32; }
16533        0
16534    } else {
16535        -1
16536    }
16537}
16538
16539#[no_mangle]
16540pub unsafe extern "C" fn thrd_exit(res: i32) {
16541    pthread_exit(res as *mut core::ffi::c_void);
16542}
16543
16544#[no_mangle]
16545pub unsafe extern "C" fn thrd_detach(thr: usize) -> i32 {
16546    let r = pthread_detach(thr as u64);
16547    if r == 0 { 0 } else { -1 }
16548}
16549
16550#[no_mangle]
16551pub unsafe extern "C" fn thrd_current() -> usize {
16552    pthread_self() as usize
16553}
16554
16555#[no_mangle]
16556pub unsafe extern "C" fn thrd_equal(thr1: usize, thr2: usize) -> i32 {
16557    (thr1 == thr2) as i32
16558}
16559
16560#[no_mangle]
16561pub unsafe extern "C" fn thrd_sleep(duration: *const core::ffi::c_void, remaining: *mut core::ffi::c_void) -> i32 {
16562    nanosleep(duration as *const timespec, remaining as *mut timespec)
16563}
16564
16565#[no_mangle]
16566pub unsafe extern "C" fn thrd_yield() {
16567    sched_yield();
16568}
16569
16570// Mutex
16571#[no_mangle]
16572pub unsafe extern "C" fn mtx_init(mtx: *mut usize, _mtx_type: i32) -> i32 {
16573    let r = pthread_mutex_init(mtx as *mut pthread_mutex_t, core::ptr::null());
16574    if r == 0 { 0 } else { -1 }
16575}
16576
16577#[no_mangle]
16578pub unsafe extern "C" fn mtx_lock(mtx: *mut usize) -> i32 {
16579    let r = pthread_mutex_lock(mtx as *mut pthread_mutex_t);
16580    if r == 0 { 0 } else { -1 }
16581}
16582
16583#[no_mangle]
16584pub unsafe extern "C" fn mtx_trylock(mtx: *mut usize) -> i32 {
16585    let r = pthread_mutex_trylock(mtx as *mut pthread_mutex_t);
16586    if r == 0 { 0 } else { -1 }
16587}
16588
16589#[no_mangle]
16590pub unsafe extern "C" fn mtx_unlock(mtx: *mut usize) -> i32 {
16591    let r = pthread_mutex_unlock(mtx as *mut pthread_mutex_t);
16592    if r == 0 { 0 } else { -1 }
16593}
16594
16595#[no_mangle]
16596pub unsafe extern "C" fn mtx_destroy(mtx: *mut usize) {
16597    pthread_mutex_destroy(mtx as *mut pthread_mutex_t);
16598}
16599
16600#[no_mangle]
16601pub unsafe extern "C" fn mtx_timedlock(mtx: *mut usize, ts: *const core::ffi::c_void) -> i32 {
16602    let r = pthread_mutex_timedlock(mtx as *mut pthread_mutex_t, ts as *const timespec);
16603    if r == 0 { 0 } else { -1 }
16604}
16605
16606// Condition variable
16607#[no_mangle]
16608pub unsafe extern "C" fn cnd_init(cnd: *mut usize) -> i32 {
16609    let r = pthread_cond_init(cnd as *mut pthread_cond_t, core::ptr::null());
16610    if r == 0 { 0 } else { -1 }
16611}
16612
16613#[no_mangle]
16614pub unsafe extern "C" fn cnd_signal(cnd: *mut usize) -> i32 {
16615    let r = pthread_cond_signal(cnd as *mut pthread_cond_t);
16616    if r == 0 { 0 } else { -1 }
16617}
16618
16619#[no_mangle]
16620pub unsafe extern "C" fn cnd_broadcast(cnd: *mut usize) -> i32 {
16621    let r = pthread_cond_broadcast(cnd as *mut pthread_cond_t);
16622    if r == 0 { 0 } else { -1 }
16623}
16624
16625#[no_mangle]
16626pub unsafe extern "C" fn cnd_wait(cnd: *mut usize, mtx: *mut usize) -> i32 {
16627    let r = pthread_cond_wait(cnd as *mut pthread_cond_t, mtx as *mut pthread_mutex_t);
16628    if r == 0 { 0 } else { -1 }
16629}
16630
16631#[no_mangle]
16632pub unsafe extern "C" fn cnd_timedwait(cnd: *mut usize, mtx: *mut usize, ts: *const core::ffi::c_void) -> i32 {
16633    let r = pthread_cond_timedwait(cnd as *mut pthread_cond_t, mtx as *mut pthread_mutex_t, ts as *const timespec);
16634    if r == 0 { 0 } else { -1 }
16635}
16636
16637#[no_mangle]
16638pub unsafe extern "C" fn cnd_destroy(cnd: *mut usize) {
16639    pthread_cond_destroy(cnd as *mut pthread_cond_t);
16640}
16641
16642// Thread-specific storage
16643#[no_mangle]
16644pub unsafe extern "C" fn tss_create(key: *mut u32, dtor: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>) -> i32 {
16645    let r = pthread_key_create(key, dtor);
16646    if r == 0 { 0 } else { -1 }
16647}
16648
16649#[no_mangle]
16650pub unsafe extern "C" fn tss_delete(key: u32) {
16651    pthread_key_delete(key);
16652}
16653
16654#[no_mangle]
16655pub unsafe extern "C" fn tss_set(key: u32, val: *mut core::ffi::c_void) -> i32 {
16656    let r = pthread_setspecific(key, val);
16657    if r == 0 { 0 } else { -1 }
16658}
16659
16660#[no_mangle]
16661pub unsafe extern "C" fn tss_get(key: u32) -> *mut core::ffi::c_void {
16662    pthread_getspecific(key)
16663}
16664
16665// call_once
16666#[no_mangle]
16667pub unsafe extern "C" fn call_once(flag: *mut u32, func: Option<unsafe extern "C" fn()>) {
16668    if *flag == 0 {
16669        if let Some(f) = func { f(); }
16670        *flag = 1;
16671    }
16672}
16673
16674// ============================================================
16675// Network functions
16676// ============================================================
16677
16678// accept4 - Linux-specific extension
16679#[no_mangle]
16680pub unsafe extern "C" fn accept4(fd: i32, addr: *mut core::ffi::c_void, addrlen: *mut u32, flags: i32) -> i32 {
16681    syscall_ret(<Arch as Syscalls>::syscall4(SYS_ACCEPT4, fd as i64, addr as i64, addrlen as i64, flags as i64)) as i32
16682}
16683
16684// getifaddrs / freeifaddrs
16685// ============================================================
16686// epoll/eventfd/signalfd/timerfd
16687// ============================================================
16688
16689#[no_mangle]
16690pub unsafe extern "C" fn epoll_create(size: i32) -> i32 {
16691    #[cfg(target_arch = "x86_64")]
16692    { syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE, size as i64)) as i32 }
16693    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
16694    {
16695        if size < 1 {
16696            ERRNO!() = EINVAL;
16697            return -1;
16698        }
16699        syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE1, 0)) as i32
16700    }
16701}
16702
16703#[no_mangle]
16704pub unsafe extern "C" fn epoll_create1(flags: i32) -> i32 {
16705    syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE1, flags as i64)) as i32
16706}
16707
16708#[no_mangle]
16709pub unsafe extern "C" fn epoll_ctl(epfd: i32, op: i32, fd: i32, event: *mut core::ffi::c_void) -> i32 {
16710    syscall_ret(<Arch as Syscalls>::syscall4(SYS_EPOLL_CTL, epfd as i64, op as i64, fd as i64, event as i64)) as i32
16711}
16712
16713#[no_mangle]
16714pub unsafe extern "C" fn epoll_wait(epfd: i32, events: *mut core::ffi::c_void, maxevents: i32, timeout: i32) -> i32 {
16715    #[cfg(target_arch = "x86_64")]
16716    {
16717        syscall_ret(<Arch as Syscalls>::syscall4(
16718            SYS_EPOLL_WAIT,
16719            epfd as i64,
16720            events as i64,
16721            maxevents as i64,
16722            timeout as i64,
16723        )) as i32
16724    }
16725    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
16726    {
16727        epoll_pwait(epfd, events, maxevents, timeout, core::ptr::null())
16728    }
16729}
16730
16731#[no_mangle]
16732pub unsafe extern "C" fn epoll_pwait(
16733    epfd: i32,
16734    events: *mut core::ffi::c_void,
16735    maxevents: i32,
16736    timeout: i32,
16737    sigmask: *const u64,
16738) -> i32 {
16739    syscall_ret(<Arch as Syscalls>::syscall6(
16740        SYS_EPOLL_PWAIT,
16741        epfd as i64,
16742        events as i64,
16743        maxevents as i64,
16744        timeout as i64,
16745        sigmask as i64,
16746        8,
16747    )) as i32
16748}
16749
16750#[no_mangle]
16751pub unsafe extern "C" fn eventfd(initval: u32, flags: i32) -> i32 {
16752    syscall_ret(<Arch as Syscalls>::syscall2(SYS_EVENTFD2, initval as i64, flags as i64)) as i32
16753}
16754
16755#[no_mangle]
16756pub unsafe extern "C" fn eventfd_read(fd: i32, value: *mut u64) -> i32 {
16757    let n = crate::read(fd, value as *mut core::ffi::c_void, 8);
16758    if n == 8 { 0 } else { -1 }
16759}
16760
16761#[no_mangle]
16762pub unsafe extern "C" fn eventfd_write(fd: i32, value: u64) -> i32 {
16763    let n = crate::write(fd, &value as *const u64 as *const core::ffi::c_void, 8);
16764    if n == 8 { 0 } else { -1 }
16765}
16766
16767#[no_mangle]
16768pub unsafe extern "C" fn signalfd(fd: i32, mask: *const u64, flags: i32) -> i32 {
16769    syscall_ret(<Arch as Syscalls>::syscall4(SYS_SIGNALFD4, fd as i64, mask as i64, 8, flags as i64)) as i32
16770}
16771
16772#[no_mangle]
16773pub unsafe extern "C" fn timerfd_create(clockid: i32, flags: i32) -> i32 {
16774    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMERFD_CREATE, clockid as i64, flags as i64)) as i32
16775}
16776
16777#[no_mangle]
16778pub unsafe extern "C" fn timerfd_settime(fd: i32, flags: i32, new_value: *const core::ffi::c_void, old_value: *mut core::ffi::c_void) -> i32 {
16779    syscall_ret(<Arch as Syscalls>::syscall4(SYS_TIMERFD_SETTIME, fd as i64, flags as i64, new_value as i64, old_value as i64)) as i32
16780}
16781
16782#[no_mangle]
16783pub unsafe extern "C" fn timerfd_gettime(fd: i32, curr_value: *mut core::ffi::c_void) -> i32 {
16784    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMERFD_GETTIME, fd as i64, curr_value as i64)) as i32
16785}
16786
16787// ============================================================
16788// System functions
16789// ============================================================
16790
16791#[no_mangle]
16792pub unsafe extern "C" fn prctl(option: i32, mut args: ...) -> i32 {
16793    let a1 = args.next_arg::<i64>();
16794    let a2 = args.next_arg::<i64>();
16795    let a3 = args.next_arg::<i64>();
16796    let a4 = args.next_arg::<i64>();
16797    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PRCTL, option as i64, a1, a2, a3, a4)) as i32
16798}
16799
16800#[no_mangle]
16801pub unsafe extern "C" fn quotactl(cmd: i32, special: *const core::ffi::c_char, id: i32, addr: *mut core::ffi::c_char) -> i32 {
16802    syscall_ret(<Arch as Syscalls>::syscall4(sysno(179, 60), cmd as i64, special as i64, id as i64, addr as i64)) as i32
16803}
16804
16805#[no_mangle]
16806pub unsafe extern "C" fn klogctl(type_: i32, bufp: *mut core::ffi::c_char, len: i32) -> i32 {
16807    syscall_ret(<Arch as Syscalls>::syscall3(sysno(103, 116), type_ as i64, bufp as i64, len as i64)) as i32
16808}
16809
16810static mut SYSLOG_IDENT: [core::ffi::c_char; 64] = [0; 64];
16811static mut SYSLOG_OPTIONS: i32 = 0;
16812static mut SYSLOG_FACILITY: i32 = 1;
16813
16814#[no_mangle]
16815pub unsafe extern "C" fn openlog(ident: *const core::ffi::c_char, option: i32, facility: i32) {
16816    SYSLOG_OPTIONS = option;
16817    SYSLOG_FACILITY = facility & 0x3f8;
16818    SYSLOG_IDENT[0] = 0;
16819    if !ident.is_null() {
16820        let mut i = 0;
16821        while i < 63 && *ident.add(i) != 0 {
16822            SYSLOG_IDENT[i] = *ident.add(i);
16823            i += 1;
16824        }
16825        SYSLOG_IDENT[i] = 0;
16826    }
16827}
16828
16829#[repr(C)]
16830struct SockAddrUn {
16831    sun_family: u16,
16832    sun_path: [core::ffi::c_char; 108],
16833}
16834
16835unsafe fn syslog_emit(priority: i32, msg: *const core::ffi::c_char, len: usize) {
16836    let mut out = [0u8; 1200];
16837    let mut o = 0usize;
16838    let pri = (SYSLOG_FACILITY | (priority & 7)) as u32;
16839    out[o] = b'<'; o += 1;
16840    if pri >= 100 { out[o] = b'0' + (pri / 100) as u8; o += 1; }
16841    if pri >= 10 { out[o] = b'0' + ((pri / 10) % 10) as u8; o += 1; }
16842    out[o] = b'0' + (pri % 10) as u8; o += 1;
16843    out[o] = b'>'; o += 1;
16844    let mut i = 0;
16845    while i < 63 && SYSLOG_IDENT[i] != 0 && o + 1 < out.len() {
16846        out[o] = SYSLOG_IDENT[i] as u8; o += 1; i += 1;
16847    }
16848    if SYSLOG_OPTIONS & 1 != 0 {
16849        out[o] = b'['; o += 1;
16850        let mut pid = crate::getpid() as u32;
16851        let mut digits = [0u8; 10];
16852        let mut d = 0;
16853        if pid == 0 { digits[0] = b'0'; d = 1; }
16854        while pid > 0 { digits[d] = b'0' + (pid % 10) as u8; pid /= 10; d += 1; }
16855        while d > 0 { d -= 1; out[o] = digits[d]; o += 1; }
16856        out[o] = b']'; o += 1;
16857    }
16858    out[o] = b':'; o += 1; out[o] = b' '; o += 1;
16859    let copy = core::cmp::min(len, out.len() - o - 1);
16860    core::ptr::copy_nonoverlapping(msg as *const u8, out.as_mut_ptr().add(o), copy);
16861    o += copy;
16862    let fd = crate::socket(AF_UNIX, SOCK_DGRAM, 0);
16863    if fd >= 0 {
16864        let mut sa: SockAddrUn = core::mem::zeroed();
16865        sa.sun_family = AF_UNIX as u16;
16866        let path = b"/dev/log";
16867        for i in 0..path.len() { sa.sun_path[i] = path[i] as core::ffi::c_char; }
16868        let r = crate::sendto(fd, out.as_ptr() as *const core::ffi::c_void, o, 0, &sa as *const SockAddrUn as *const crate::sockaddr, core::mem::size_of::<SockAddrUn>() as u32);
16869        crate::close(fd);
16870        if r >= 0 { return; }
16871    }
16872    crate::write(2, out.as_ptr() as *const core::ffi::c_void, o);
16873    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
16874}
16875
16876#[no_mangle]
16877pub unsafe extern "C" fn vsyslog(priority: c_int, fmt: *const c_char, ap: VaList) {
16878    let mut msg = [0 as c_char; 1024];
16879    let n = vsnprintf(msg.as_mut_ptr(), msg.len(), fmt, ap);
16880    if n > 0 { syslog_emit(priority, msg.as_ptr(), core::cmp::min(n as usize, msg.len() - 1)); }
16881}
16882
16883#[no_mangle]
16884pub unsafe extern "C" fn syslog(priority: c_int, fmt: *const c_char, args: ...) {
16885    vsyslog(priority, fmt, args);
16886}
16887
16888#[no_mangle]
16889pub unsafe extern "C" fn closelog() {
16890    // Nothing to do
16891}
16892
16893#[no_mangle]
16894pub unsafe extern "C" fn setlogmask(mask: i32) -> i32 {
16895    static mut LOG_MASK: i32 = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80;
16896    let old = LOG_MASK;
16897    if mask != 0 { LOG_MASK = mask; }
16898    old
16899}
16900
16901#[no_mangle]
16902pub unsafe extern "C" fn acct(filename: *const core::ffi::c_char) -> i32 {
16903    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ACCT, filename as i64)) as i32
16904}
16905
16906#[no_mangle]
16907pub unsafe extern "C" fn swapon(path: *const core::ffi::c_char, flags: i32) -> i32 {
16908    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SWAPON, path as i64, flags as i64)) as i32
16909}
16910
16911#[no_mangle]
16912pub unsafe extern "C" fn swapoff(path: *const core::ffi::c_char) -> i32 {
16913    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SWAPOFF, path as i64)) as i32
16914}
16915
16916#[no_mangle]
16917pub unsafe extern "C" fn syncfs(fd: i32) -> i32 {
16918    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SYNCFS, fd as i64)) as i32
16919}
16920
16921#[no_mangle]
16922pub unsafe extern "C" fn sync_file_range(fd: i32, offset: i64, nbytes: u64, flags: u32) -> i32 {
16923    syscall_ret(<Arch as Syscalls>::syscall4(sysno(277, 84), fd as i64, offset, nbytes as i64, flags as i64)) as i32
16924}
16925
16926#[no_mangle]
16927pub unsafe extern "C" fn posix_fadvise(fd: i32, offset: i64, len: u64, advice: i32) -> i32 {
16928    // POSIX returns the error number directly, not -1/errno.
16929    let r = <Arch as Syscalls>::syscall4(sysno(221, 223), fd as i64, offset, len as i64, advice as i64);
16930    if r < 0 { (-r) as i32 } else { 0 }
16931}
16932
16933#[no_mangle]
16934pub unsafe extern "C" fn posix_fallocate(fd: i32, offset: i64, len: u64) -> i32 {
16935    let r = <Arch as Syscalls>::syscall3(SYS_FALLOCATE, fd as i64, offset, len as i64);
16936    if r < 0 { (-r) as i32 } else { 0 }
16937}
16938
16939#[no_mangle]
16940pub unsafe extern "C" fn readahead(fd: i32, offset: i64, count: usize) -> isize {
16941    // musl declares readahead() as ssize_t; returning int leaves the upper
16942    // half of rax undefined for callers that expect a 64-bit result.
16943    syscall_ret(<Arch as Syscalls>::syscall3(sysno(187, 213), fd as i64, offset, count as i64)) as isize
16944}
16945
16946#[no_mangle]
16947pub unsafe extern "C" fn fallocate(fd: i32, mode: i32, offset: i64, len: u64) -> i32 {
16948    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FALLOCATE, fd as i64, mode as i64, offset, len as i64)) as i32
16949}
16950
16951// ============================================================
16952// Terminal functions
16953// ============================================================
16954
16955#[no_mangle]
16956pub unsafe extern "C" fn tcgetattr(fd: i32, termios_p: *mut core::ffi::c_void) -> i32 {
16957    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5401, termios_p as i64)) as i32
16958}
16959
16960#[no_mangle]
16961pub unsafe extern "C" fn tcsetattr(fd: i32, optional_actions: i32, termios_p: *const core::ffi::c_void) -> i32 {
16962    let cmd = match optional_actions {
16963        0 => 0x5402,
16964        1 => 0x5403,
16965        2 => 0x5404,
16966        _ => 0x5402,
16967    };
16968    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, cmd, termios_p as i64)) as i32
16969}
16970
16971#[no_mangle]
16972pub unsafe extern "C" fn tcdrain(fd: i32) -> i32 {
16973    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5409, 1)) as i32
16974}
16975
16976#[no_mangle]
16977pub unsafe extern "C" fn tcflush(fd: i32, queue_selector: i32) -> i32 {
16978    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540B, queue_selector as i64)) as i32
16979}
16980
16981#[no_mangle]
16982pub unsafe extern "C" fn tcflow(fd: i32, action: i32) -> i32 {
16983    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540A, action as i64)) as i32
16984}
16985
16986#[no_mangle]
16987pub unsafe extern "C" fn tcsendbreak(fd: i32, duration: i32) -> i32 {
16988    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5425, duration as i64)) as i32
16989}
16990
16991#[no_mangle]
16992pub unsafe extern "C" fn tcgetsid(fd: i32) -> i32 {
16993    let mut sid: i32 = 0;
16994    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5429, &mut sid as *mut i32 as i64);
16995    if r < 0 { -1 } else { sid }
16996}
16997
16998#[no_mangle]
16999pub unsafe extern "C" fn tcgetpgrp(fd: i32) -> i32 {
17000    let mut pgrp: i32 = 0;
17001    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540F, &mut pgrp as *mut i32 as i64);
17002    if r < 0 { -1 } else { pgrp }
17003}
17004
17005#[no_mangle]
17006pub unsafe extern "C" fn tcsetpgrp(fd: i32, pgrp: i32) -> i32 {
17007    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5410, &pgrp as *const i32 as i64)) as i32
17008}
17009
17010// ============================================================
17011// Memory locking functions
17012// ============================================================
17013
17014// ============================================================
17015
17016// ============================================================
17017// POSIX message queue functions
17018// ============================================================
17019
17020#[no_mangle]
17021pub unsafe extern "C" fn mq_open(name: *const core::ffi::c_char, oflag: i32, mut args: ...) -> i32 {
17022    if name.is_null() { ERRNO!() = EINVAL; return -1; }
17023    let mut p = name as *const u8;
17024    if *p == b'/' { p = p.add(1); }
17025    let mut mode: u32 = 0;
17026    let mut attr: *const core::ffi::c_void = core::ptr::null();
17027    if oflag & 0o100 != 0 {
17028        mode = args.next_arg::<u32>();
17029        attr = args.next_arg::<*const core::ffi::c_void>();
17030    }
17031    syscall_ret(<Arch as Syscalls>::syscall4(
17032        sysno(240, 180),
17033        p as i64,
17034        oflag as i64,
17035        mode as i64,
17036        attr as i64,
17037    )) as i32
17038}
17039
17040#[no_mangle]
17041pub unsafe extern "C" fn mq_close(mqdes: i32) -> i32 {
17042    crate::close(mqdes as i32)
17043}
17044
17045#[no_mangle]
17046pub unsafe extern "C" fn mq_unlink(name: *const core::ffi::c_char) -> i32 {
17047    if name.is_null() { ERRNO!() = EINVAL; return -1; }
17048    let mut p = name as *const u8;
17049    if *p == b'/' { p = p.add(1); }
17050    let r = <Arch as Syscalls>::syscall1(sysno(241, 181), p as i64);
17051    if r < 0 {
17052        // The kernel reports EPERM for an unlink while the queue is open.
17053        let e = if (-r) as c_int == 1 { 13 } else { (-r) as c_int };
17054        ERRNO!() = e;
17055        -1
17056    } else {
17057        0
17058    }
17059}
17060
17061#[no_mangle]
17062pub unsafe extern "C" fn mq_send(mqdes: i32, msg_ptr: *const core::ffi::c_char, msg_len: usize, msg_prio: u32) -> i32 {
17063    mq_timedsend(mqdes, msg_ptr, msg_len, msg_prio, core::ptr::null())
17064}
17065
17066#[no_mangle]
17067pub unsafe extern "C" fn mq_receive(mqdes: i32, msg_ptr: *mut core::ffi::c_char, msg_len: usize, msg_prio: *mut u32) -> isize {
17068    mq_timedreceive(mqdes, msg_ptr, msg_len, msg_prio, core::ptr::null())
17069}
17070
17071#[no_mangle]
17072pub unsafe extern "C" fn mq_timedsend(
17073    mqdes: i32,
17074    msg_ptr: *const core::ffi::c_char,
17075    msg_len: usize,
17076    msg_prio: u32,
17077    abs_timeout: *const core::ffi::c_void,
17078) -> i32 {
17079    syscall_ret(<Arch as Syscalls>::syscall5(
17080        sysno(242, 182),
17081        mqdes as i64,
17082        msg_ptr as i64,
17083        msg_len as i64,
17084        msg_prio as i64,
17085        abs_timeout as i64,
17086    )) as i32
17087}
17088
17089#[no_mangle]
17090pub unsafe extern "C" fn mq_timedreceive(
17091    mqdes: i32,
17092    msg_ptr: *mut core::ffi::c_char,
17093    msg_len: usize,
17094    msg_prio: *mut u32,
17095    abs_timeout: *const core::ffi::c_void,
17096) -> isize {
17097    syscall_ret(<Arch as Syscalls>::syscall5(
17098        sysno(243, 183),
17099        mqdes as i64,
17100        msg_ptr as i64,
17101        msg_len as i64,
17102        msg_prio as i64,
17103        abs_timeout as i64,
17104    )) as isize
17105}
17106
17107#[repr(C)]
17108pub struct SigEventFull {
17109    sigev_value: usize,
17110    sigev_signo: i32,
17111    sigev_notify: i32,
17112    sigev_function: usize,
17113    sigev_attributes: usize,
17114    sigev_pad: [u8; 32],
17115}
17116
17117struct MqNotifyArgs {
17118    sem: sem_t,
17119    sock: i32,
17120    mqd: i32,
17121    err: i32,
17122    func: usize,
17123    value: usize,
17124}
17125
17126unsafe extern "C" fn mq_notify_thread(arg: *mut c_void) -> *mut c_void {
17127    let a = &mut *(arg as *mut MqNotifyArgs);
17128    let sock = a.sock;
17129    let mqd = a.mqd;
17130    let func = a.func;
17131    let value = a.value;
17132    let zeros = [0u8; 32];
17133    let sev2 = SigEventFull {
17134        sigev_value: zeros.as_ptr() as usize,
17135        sigev_signo: sock,
17136        sigev_notify: 2, // SIGEV_THREAD, consumed by the kernel as a netlink fd
17137        sigev_function: 0,
17138        sigev_attributes: 0,
17139        sigev_pad: [0; 32],
17140    };
17141    let r = <Arch as Syscalls>::syscall2(sysno(244, 184), mqd as i64, &sev2 as *const SigEventFull as i64);
17142    a.err = if r < 0 { (-r) as i32 } else { 0 };
17143    sem_post(&mut a.sem);
17144    if a.err != 0 { return core::ptr::null_mut(); }
17145    pthread_detach(pthread_self());
17146    let mut buf = [0u8; 32];
17147    let n = recv(sock, buf.as_mut_ptr() as *mut c_void, buf.len(), 0x4000 | 0x100);
17148    crate::close(sock);
17149    if n as usize == buf.len() && buf[buf.len() - 1] == 1 && func != 0 {
17150        let f: extern "C" fn(usize) = core::mem::transmute(func);
17151        f(value);
17152    }
17153    core::ptr::null_mut()
17154}
17155
17156#[no_mangle]
17157pub unsafe extern "C" fn mq_notify(mqdes: i32, sev: *const core::ffi::c_void) -> i32 {
17158    if sev.is_null() {
17159        return syscall_ret(<Arch as Syscalls>::syscall2(sysno(244, 184), mqdes as i64, 0)) as i32;
17160    }
17161    let ev = &*(sev as *const SigEventFull);
17162    if ev.sigev_notify != 2 {
17163        return syscall_ret(<Arch as Syscalls>::syscall2(sysno(244, 184), mqdes as i64, sev as i64)) as i32;
17164    }
17165
17166    // SIGEV_THREAD is emulated with a netlink socket and a helper thread,
17167    // matching musl. The kernel only deals with the socket.
17168    let sock = socket(16 /* AF_NETLINK */, 3 | 0x80000 /* SOCK_RAW|SOCK_CLOEXEC */, 0);
17169    if sock < 0 { return -1; }
17170    let mut a = MqNotifyArgs {
17171        sem: core::mem::zeroed(),
17172        sock,
17173        mqd: mqdes,
17174        err: 0,
17175        func: ev.sigev_function,
17176        value: ev.sigev_value,
17177    };
17178    sem_init(&mut a.sem, 0, 0);
17179
17180    let mut attr: pthread_attr_t = core::mem::zeroed();
17181    if ev.sigev_attributes != 0 {
17182        attr = core::ptr::read(ev.sigev_attributes as *const pthread_attr_t);
17183    } else {
17184        pthread_attr_init(&mut attr);
17185    }
17186    pthread_attr_setdetachstate(&mut attr, PTHREAD_CREATE_JOINABLE);
17187
17188    let mut all: SigSetT = 0;
17189    sigfillset(&mut all);
17190    let mut orig: SigSetT = 0;
17191    pthread_sigmask(0 /* SIG_BLOCK */, &all, &mut orig);
17192
17193    let mut td: PthreadT = 0;
17194    let r = pthread_create(&mut td, &attr, mq_notify_thread as *const () as usize, &mut a as *mut MqNotifyArgs as *mut c_void);
17195    pthread_sigmask(2 /* SIG_SETMASK */, &orig, core::ptr::null_mut());
17196    if r != 0 {
17197        crate::close(sock);
17198        ERRNO!() = 11;
17199        return -1;
17200    }
17201    sem_wait(&mut a.sem);
17202    sem_destroy(&mut a.sem);
17203    if a.err != 0 {
17204        crate::close(sock);
17205        pthread_join(td, core::ptr::null_mut());
17206        ERRNO!() = a.err;
17207        return -1;
17208    }
17209    0
17210}
17211
17212#[no_mangle]
17213pub unsafe extern "C" fn mq_getattr(mqdes: i32, attr: *mut core::ffi::c_void) -> i32 {
17214    mq_setattr(mqdes, core::ptr::null(), attr)
17215}
17216
17217#[no_mangle]
17218pub unsafe extern "C" fn mq_setattr(
17219    mqdes: i32,
17220    new: *const core::ffi::c_void,
17221    old: *mut core::ffi::c_void,
17222) -> i32 {
17223    syscall_ret(<Arch as Syscalls>::syscall3(
17224        sysno(245, 185),
17225        mqdes as i64,
17226        new as i64,
17227        old as i64,
17228    )) as i32
17229}
17230
17231// ============================================================
17232// pthread functions
17233// ============================================================
17234
17235#[no_mangle]
17236pub unsafe extern "C" fn pthread_getaffinity_np(thread: usize, cpusetsize: usize, cpuset: *mut u8) -> i32 {
17237    sched_getaffinity(thread as i32, cpusetsize, cpuset)
17238}
17239
17240#[no_mangle]
17241pub unsafe extern "C" fn pthread_setaffinity_np(thread: usize, cpusetsize: usize, cpuset: *const u8) -> i32 {
17242    sched_setaffinity(thread as i32, cpusetsize, cpuset)
17243}
17244
17245// ============================================================
17246// sched functions
17247// ============================================================
17248
17249#[no_mangle]
17250pub unsafe extern "C" fn sched_yield() -> i32 {
17251    syscall_ret(<Arch as Syscalls>::syscall0(sysno(24, 124))) as i32
17252}
17253
17254#[no_mangle]
17255pub unsafe extern "C" fn sched_get_priority_max(policy: i32) -> i32 {
17256    syscall_ret(<Arch as Syscalls>::syscall1(sysno(146, 125), policy as i64)) as i32
17257}
17258
17259#[no_mangle]
17260pub unsafe extern "C" fn sched_get_priority_min(policy: i32) -> i32 {
17261    syscall_ret(<Arch as Syscalls>::syscall1(sysno(147, 126), policy as i64)) as i32
17262}
17263
17264#[no_mangle]
17265pub unsafe extern "C" fn sched_getparam(pid: i32, param: *mut core::ffi::c_void) -> i32 {
17266    syscall_ret(<Arch as Syscalls>::syscall2(sysno(143, 121), pid as i64, param as i64)) as i32
17267}
17268
17269#[no_mangle]
17270pub unsafe extern "C" fn sched_setparam(pid: i32, param: *const core::ffi::c_void) -> i32 {
17271    syscall_ret(<Arch as Syscalls>::syscall2(sysno(142, 118), pid as i64, param as i64)) as i32
17272}
17273
17274#[no_mangle]
17275pub unsafe extern "C" fn sched_getscheduler(pid: i32) -> i32 {
17276    syscall_ret(<Arch as Syscalls>::syscall1(sysno(145, 120), pid as i64)) as i32
17277}
17278
17279#[no_mangle]
17280pub unsafe extern "C" fn sched_setscheduler(pid: i32, policy: i32, param: *const core::ffi::c_void) -> i32 {
17281    syscall_ret(<Arch as Syscalls>::syscall3(sysno(144, 119), pid as i64, policy as i64, param as i64)) as i32
17282}
17283
17284#[no_mangle]
17285pub unsafe extern "C" fn sched_setaffinity(pid: i32, cpusetsize: usize, cpuset: *const u8) -> i32 {
17286    syscall_ret(<Arch as Syscalls>::syscall3(sysno(203, 122), pid as i64, cpusetsize as i64, cpuset as i64)) as i32
17287}
17288
17289#[no_mangle]
17290pub unsafe extern "C" fn sched_getaffinity(pid: i32, cpusetsize: usize, cpuset: *mut u8) -> i32 {
17291    let r = <Arch as Syscalls>::syscall3(sysno(204, 123), pid as i64, cpusetsize as i64, cpuset as i64);
17292    if r < 0 {
17293        ERRNO!() = (-r) as c_int;
17294        return -1;
17295    }
17296    // The kernel returns the number of bytes copied, not 0.
17297    0
17298}
17299
17300#[cold]
17301unsafe fn sched_getcpu_syscall(cpu: *mut u32) -> i32 {
17302    let r = <Arch as Syscalls>::syscall3(sysno(309, 168), cpu as i64, 0, 0);
17303    if r == 0 {
17304        core::ptr::read_unaligned(cpu) as i32
17305    } else {
17306        syscall_ret(r) as i32
17307    }
17308}
17309
17310#[no_mangle]
17311pub unsafe extern "C" fn sched_getcpu() -> i32 {
17312    // Both the vDSO and the syscall fill the slot on success.  A 16-byte
17313    // scratch area keeps the write away from the return address; a 4-byte
17314    // slot overlaps the compiler's push and triggers a store-forwarding
17315    // stall on the vDSO write (measured ~2.5 ns).
17316    let mut cpu = core::mem::MaybeUninit::<[u64; 2]>::uninit();
17317    let cpu_ptr = cpu.as_mut_ptr() as *mut u32;
17318    if vdso_getcpu(cpu_ptr) {
17319        return core::ptr::read_unaligned(cpu_ptr) as i32;
17320    }
17321    sched_getcpu_syscall(cpu_ptr)
17322}
17323
17324#[no_mangle]
17325pub unsafe extern "C" fn sched_rr_get_interval(pid: i32, tp: *mut core::ffi::c_void) -> i32 {
17326    syscall_ret(<Arch as Syscalls>::syscall2(sysno(148, 127), pid as i64, tp as i64)) as i32
17327}
17328
17329// ============================================================
17330// timer/clock functions
17331// ============================================================
17332
17333#[no_mangle]
17334pub unsafe extern "C" fn timer_create(clockid: i32, sevp: *mut core::ffi::c_void, timerid: *mut i32) -> i32 {
17335    syscall_ret(<Arch as Syscalls>::syscall3(sysno(222, 107), clockid as i64, sevp as i64, timerid as i64)) as i32
17336}
17337
17338#[no_mangle]
17339pub unsafe extern "C" fn timer_delete(timerid: i32) -> i32 {
17340    syscall_ret(<Arch as Syscalls>::syscall1(sysno(226, 111), timerid as i64)) as i32
17341}
17342
17343#[no_mangle]
17344pub unsafe extern "C" fn timer_settime(timerid: i32, flags: i32, new_value: *const core::ffi::c_void, old_value: *mut core::ffi::c_void) -> i32 {
17345    syscall_ret(<Arch as Syscalls>::syscall4(sysno(223, 110), timerid as i64, flags as i64, new_value as i64, old_value as i64)) as i32
17346}
17347
17348#[no_mangle]
17349pub unsafe extern "C" fn timer_gettime(timerid: i32, curr_value: *mut core::ffi::c_void) -> i32 {
17350    syscall_ret(<Arch as Syscalls>::syscall2(sysno(224, 108), timerid as i64, curr_value as i64)) as i32
17351}
17352
17353#[no_mangle]
17354pub unsafe extern "C" fn timer_getoverrun(timerid: i32) -> i32 {
17355    syscall_ret(<Arch as Syscalls>::syscall1(sysno(225, 109), timerid as i64)) as i32
17356}
17357
17358#[no_mangle]
17359pub unsafe extern "C" fn clock_adjtime(_clockid: i32, buf: *mut core::ffi::c_void) -> i32 {
17360    syscall_ret(<Arch as Syscalls>::syscall2(SYS_ADJTIMEX, buf as i64, 0)) as i32
17361}
17362
17363#[no_mangle]
17364pub unsafe extern "C" fn clock_getcpuclockid(pid: i32, clockid: *mut i32) -> i32 {
17365    if clockid.is_null() { return EINVAL; }
17366    let id: i32 = ((-(pid as i64) - 1) * 8 + 2) as i32;
17367    let mut ts: timespec = core::mem::zeroed();
17368    let r = <Arch as Syscalls>::syscall2(SYS_CLOCK_GETRES, id as i64, &mut ts as *mut timespec as i64);
17369    if r < 0 {
17370        let e = (-r) as c_int;
17371        return if e == EINVAL { 3 } else { e };
17372    }
17373    *clockid = id;
17374    0
17375}
17376
17377// ============================================================
17378// String functions
17379// ============================================================
17380
17381#[no_mangle]
17382pub unsafe extern "C" fn strcoll(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> i32 {
17383    // ponytail: simplified collation - just strcmp
17384    let mut i = 0;
17385    loop {
17386        let c1 = *s1.add(i) as u8;
17387        let c2 = *s2.add(i) as u8;
17388        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
17389        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
17390        i += 1;
17391    }
17392}
17393
17394#[no_mangle]
17395pub unsafe extern "C" fn strxfrm(dest: *mut core::ffi::c_char, src: *const core::ffi::c_char, n: usize) -> usize {
17396    let mut i = 0;
17397    while i < n {
17398        let c = *src.add(i);
17399        *dest.add(i) = c;
17400        if c == 0 { break; }
17401        i += 1;
17402    }
17403    i
17404}
17405
17406// ============================================================
17407// Directory functions
17408// ============================================================
17409
17410#[no_mangle]
17411pub unsafe extern "C" fn scandir(dirp: *const core::ffi::c_char, _namelist: *mut *mut *mut core::ffi::c_void, _filter: Option<unsafe extern "C" fn(*const core::ffi::c_void) -> i32>, _compar: Option<unsafe extern "C" fn(*const core::ffi::c_void, *const core::ffi::c_void) -> i32>) -> i32 {
17412    let dir = opendir(dirp);
17413    if dir.is_null() { return -1; }
17414    let mut count = 0;
17415    loop {
17416        let ent = readdir(dir);
17417        if ent.is_null() { break; }
17418        count += 1;
17419    }
17420    closedir(dir);
17421    count
17422}
17423
17424#[no_mangle]
17425pub unsafe extern "C" fn alphasort(a: *const *const core::ffi::c_void, b: *const *const core::ffi::c_void) -> i32 {
17426    let s1 = *a as *const core::ffi::c_char;
17427    let s2 = *b as *const core::ffi::c_char;
17428    crate::strcmp(s1 as *const u8, s2 as *const u8)
17429}
17430
17431#[no_mangle]
17432pub unsafe extern "C" fn versionsort(a: *const *const core::ffi::c_void, b: *const *const core::ffi::c_void) -> i32 {
17433    let s1 = *a as *const core::ffi::c_char;
17434    let s2 = *b as *const core::ffi::c_char;
17435    crate::strcmp(s1 as *const u8, s2 as *const u8)
17436}
17437
17438// ============================================================
17439
17440
17441// ============================================================
17442// err functions
17443// ============================================================
17444
17445unsafe fn vwarn_impl(fmt: *const c_char, ap: VaList, with_errno: bool) {
17446    let mut buf = [0 as c_char; 1024];
17447    let n = vsnprintf(buf.as_mut_ptr(), buf.len(), fmt, ap);
17448    if n > 0 {
17449        let l = core::cmp::min(n as usize, buf.len() - 1);
17450        crate::write(2, buf.as_ptr() as *const c_void, l);
17451    }
17452    if with_errno {
17453        let e = ERRNO!();
17454        crate::write(2, b": ".as_ptr() as *const c_void, 2);
17455        let msg = strerror(e);
17456        crate::write(2, msg as *const c_void, crate::strlen(msg));
17457    }
17458    crate::write(2, b"\n".as_ptr() as *const c_void, 1);
17459}
17460
17461#[no_mangle]
17462pub unsafe extern "C" fn verr(eval: c_int, fmt: *const c_char, ap: VaList) {
17463    vwarn_impl(fmt, ap, true);
17464    crate::exit(eval);
17465}
17466
17467#[no_mangle]
17468pub unsafe extern "C" fn verrx(eval: c_int, fmt: *const c_char, ap: VaList) {
17469    vwarn_impl(fmt, ap, false);
17470    crate::exit(eval);
17471}
17472
17473#[no_mangle]
17474pub unsafe extern "C" fn vwarn(fmt: *const c_char, ap: VaList) {
17475    vwarn_impl(fmt, ap, true);
17476}
17477
17478#[no_mangle]
17479pub unsafe extern "C" fn vwarnx(fmt: *const c_char, ap: VaList) {
17480    vwarn_impl(fmt, ap, false);
17481}
17482
17483#[no_mangle]
17484pub unsafe extern "C" fn err(eval: c_int, fmt: *const c_char, args: ...) {
17485    verr(eval, fmt, args);
17486}
17487
17488#[no_mangle]
17489pub unsafe extern "C" fn errx(eval: c_int, fmt: *const c_char, args: ...) {
17490    verrx(eval, fmt, args);
17491}
17492
17493#[no_mangle]
17494pub unsafe extern "C" fn warn(fmt: *const c_char, args: ...) {
17495    vwarn(fmt, args);
17496}
17497
17498#[no_mangle]
17499pub unsafe extern "C" fn warnx(fmt: *const c_char, args: ...) {
17500    vwarnx(fmt, args);
17501}
17502
17503// ============================================================
17504// ecvt functions
17505// ============================================================
17506
17507#[no_mangle]
17508pub unsafe extern "C" fn ecvt(value: f64, ndigit: i32, decpt: *mut i32, sign: *mut i32) -> *mut core::ffi::c_char {
17509    static mut BUF: [core::ffi::c_char; 80] = [0; 80];
17510    if value < 0.0 { *sign = 1; } else { *sign = 0; }
17511    let v = if value < 0.0 { -value } else { value };
17512    if v == 0.0 { *decpt = 0; BUF[0] = 0; return BUF.as_mut_ptr(); }
17513    let mut d = 0i32;
17514    let mut tmp = v;
17515    while tmp >= 10.0 { tmp /= 10.0; d += 1; }
17516    while tmp < 1.0 { tmp *= 10.0; d -= 1; }
17517    *decpt = d + 1;
17518    let mut i = 0;
17519    let mut val = tmp;
17520    while i < ndigit as usize && i < 79 {
17521        let digit = val as i32;
17522        BUF[i] = (b'0' + digit as u8) as c_char;
17523        val = (val - digit as f64) * 10.0;
17524        i += 1;
17525    }
17526    BUF[i] = 0;
17527    BUF.as_mut_ptr()
17528}
17529
17530#[no_mangle]
17531pub unsafe extern "C" fn fcvt(value: f64, ndigit: i32, decpt: *mut i32, sign: *mut i32) -> *mut core::ffi::c_char {
17532    static mut BUF: [core::ffi::c_char; 80] = [0; 80];
17533    if value < 0.0 { *sign = 1; } else { *sign = 0; }
17534    let v = if value < 0.0 { -value } else { value };
17535    if v == 0.0 { *decpt = 0; BUF[0] = 0; return BUF.as_mut_ptr(); }
17536    let mut d = 0i32;
17537    let mut tmp = v;
17538    while tmp >= 10.0 { tmp /= 10.0; d += 1; }
17539    while tmp < 1.0 { tmp *= 10.0; d -= 1; }
17540    *decpt = d + 1;
17541    let mut val = tmp;
17542    let mut i = 0;
17543    while i < (*decpt) as usize && i < 79 {
17544        let digit = val as i32;
17545        BUF[i] = (b'0' + digit as u8) as c_char;
17546        val = (val - digit as f64) * 10.0;
17547        i += 1;
17548    }
17549    if ndigit > 0 && i < 79 {
17550        BUF[i] = '.' as c_char;
17551        i += 1;
17552        let mut frac = val;
17553        let mut j = 0;
17554        while j < ndigit as usize && i < 79 {
17555            let digit = frac as i32;
17556            BUF[i] = (b'0' + digit as u8) as c_char;
17557            frac = (frac - digit as f64) * 10.0;
17558            i += 1;
17559            j += 1;
17560        }
17561    }
17562    BUF[i] = 0;
17563    BUF.as_mut_ptr()
17564}
17565
17566#[no_mangle]
17567pub unsafe extern "C" fn gcvt(value: f64, _ndigit: i32, buf: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
17568    // Simple implementation - convert to string
17569    if value == 0.0 {
17570        *buf = '0' as c_char;
17571        *buf.add(1) = 0;
17572        return buf;
17573    }
17574    let mut i = 0;
17575    let v = if value < 0.0 { *buf = '-' as c_char; i = 1; -value } else { value };
17576    // Integer part
17577    let mut int_part = v as i64;
17578    let mut digits = [0u8; 32];
17579    let mut di = 0;
17580    if int_part == 0 {
17581        digits[0] = 0;
17582        di = 1;
17583    } else {
17584        while int_part > 0 && di < 32 {
17585            digits[di] = (int_part % 10) as u8;
17586            int_part /= 10;
17587            di += 1;
17588        }
17589    }
17590    while di > 0 && i < 79 {
17591        di -= 1;
17592        *buf.add(i) = (b'0' + digits[di]) as c_char;
17593        i += 1;
17594    }
17595    *buf.add(i) = 0;
17596    buf
17597}
17598
17599// ============================================================
17600// usershell functions
17601// ============================================================
17602
17603static mut SHELLS: [*const core::ffi::c_char; 3] = [
17604    b"/bin/sh\0".as_ptr() as *const core::ffi::c_char,
17605    b"/bin/bash\0".as_ptr() as *const core::ffi::c_char,
17606    core::ptr::null(),
17607];
17608static mut SHELL_IDX: usize = 0;
17609
17610#[no_mangle]
17611pub unsafe extern "C" fn getusershell() -> *mut core::ffi::c_char {
17612    let s = SHELLS[SHELL_IDX];
17613    if s.is_null() {
17614        SHELL_IDX = 0;
17615        return core::ptr::null_mut();
17616    }
17617    SHELL_IDX += 1;
17618    s as *mut core::ffi::c_char
17619}
17620
17621#[no_mangle]
17622pub unsafe extern "C" fn setusershell() {
17623    SHELL_IDX = 0;
17624}
17625
17626#[no_mangle]
17627pub unsafe extern "C" fn endusershell() {
17628    SHELL_IDX = 0;
17629}
17630
17631// ============================================================
17632// ether functions
17633// ============================================================
17634
17635#[no_mangle]
17636pub unsafe extern "C" fn ether_aton(s: *const core::ffi::c_char) -> *mut u8 {
17637    static mut EA: [u8; 6] = [0; 6];
17638    if ether_aton_r(s, EA.as_mut_ptr()).is_null() { core::ptr::null_mut() } else { EA.as_mut_ptr() }
17639}
17640
17641#[no_mangle]
17642pub unsafe extern "C" fn ether_aton_r(s: *const core::ffi::c_char, ea: *mut u8) -> *mut u8 {
17643    if ea.is_null() { return core::ptr::null_mut(); }
17644    let mut i = 0;
17645    let mut j = 0;
17646    let mut val: u32 = 0;
17647    let mut digits = 0;
17648    while *s.add(i) != 0 && j < 6 {
17649        let c = *s.add(i);
17650        if c == ':' as c_char {
17651            if digits == 0 { return core::ptr::null_mut(); }
17652            *ea.add(j) = val as u8;
17653            j += 1;
17654            val = 0;
17655            digits = 0;
17656        } else if (c >= '0' as c_char && c <= '9' as c_char) || (c >= 'a' as c_char && c <= 'f' as c_char) || (c >= 'A' as c_char && c <= 'F' as c_char) {
17657            let d = if c >= '0' as c_char && c <= '9' as c_char { (c - '0' as c_char) as u32 }
17658                   else if c >= 'a' as c_char { (c - 'a' as c_char + 10) as u32 }
17659                   else { (c - 'A' as c_char + 10) as u32 };
17660            val = val * 16 + d;
17661            if val > 255 { return core::ptr::null_mut(); }
17662            digits += 1;
17663            if digits > 2 { return core::ptr::null_mut(); }
17664        } else {
17665            return core::ptr::null_mut();
17666        }
17667        i += 1;
17668    }
17669    if digits == 0 || j != 5 { return core::ptr::null_mut(); }
17670    *ea.add(j) = val as u8;
17671    ea
17672}
17673
17674#[no_mangle]
17675pub unsafe extern "C" fn ether_ntoa(ea: *const u8) -> *mut core::ffi::c_char {
17676    static mut BUF: [core::ffi::c_char; 18] = [0; 18];
17677    ether_ntoa_r(ea, BUF.as_mut_ptr());
17678    BUF.as_mut_ptr()
17679}
17680
17681#[no_mangle]
17682pub unsafe extern "C" fn ether_ntoa_r(ea: *const u8, buf: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
17683    let a = *ea.add(0); let b = *ea.add(1); let c = *ea.add(2);
17684    let d = *ea.add(3); let e = *ea.add(4); let f = *ea.add(5);
17685    let hex = b"0123456789abcdef\0".as_ptr() as *const u8;
17686    let mut i = 0;
17687    *buf.add(i) = *hex.add((a >> 4) as usize) as c_char; i += 1;
17688    *buf.add(i) = *hex.add((a & 0xf) as usize) as c_char; i += 1;
17689    *buf.add(i) = ':' as c_char; i += 1;
17690    *buf.add(i) = *hex.add((b >> 4) as usize) as c_char; i += 1;
17691    *buf.add(i) = *hex.add((b & 0xf) as usize) as c_char; i += 1;
17692    *buf.add(i) = ':' as c_char; i += 1;
17693    *buf.add(i) = *hex.add((c >> 4) as usize) as c_char; i += 1;
17694    *buf.add(i) = *hex.add((c & 0xf) as usize) as c_char; i += 1;
17695    *buf.add(i) = ':' as c_char; i += 1;
17696    *buf.add(i) = *hex.add((d >> 4) as usize) as c_char; i += 1;
17697    *buf.add(i) = *hex.add((d & 0xf) as usize) as c_char; i += 1;
17698    *buf.add(i) = ':' as c_char; i += 1;
17699    *buf.add(i) = *hex.add((e >> 4) as usize) as c_char; i += 1;
17700    *buf.add(i) = *hex.add((e & 0xf) as usize) as c_char; i += 1;
17701    *buf.add(i) = ':' as c_char; i += 1;
17702    *buf.add(i) = *hex.add((f >> 4) as usize) as c_char; i += 1;
17703    *buf.add(i) = *hex.add((f & 0xf) as usize) as c_char; i += 1;
17704    *buf.add(i) = 0;
17705    buf
17706}
17707
17708// ============================================================
17709// utmpx functions
17710// ============================================================
17711
17712#[no_mangle]
17713pub unsafe extern "C" fn getutxent() -> *mut core::ffi::c_void {
17714    getutent()
17715}
17716
17717#[no_mangle]
17718pub unsafe extern "C" fn getutxid(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
17719    getutid(ut)
17720}
17721
17722#[no_mangle]
17723pub unsafe extern "C" fn getutxline(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
17724    getutline(ut)
17725}
17726
17727#[no_mangle]
17728pub unsafe extern "C" fn pututxline(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
17729    pututline(ut)
17730}
17731
17732#[no_mangle]
17733pub unsafe extern "C" fn setutxent() {
17734    setutent()
17735}
17736
17737#[no_mangle]
17738pub unsafe extern "C" fn endutxent() {
17739    endutent()
17740}
17741
17742// ============================================================
17743// exec functions
17744// ============================================================
17745
17746#[no_mangle]
17747pub unsafe extern "C" fn execv(path: *const core::ffi::c_char, argv: *const *const core::ffi::c_char) -> i32 {
17748    crate::execve(path, argv, __environ as *const *const core::ffi::c_char)
17749}
17750
17751#[no_mangle]
17752pub unsafe extern "C" fn execlp(file: *const core::ffi::c_char, _args: ...) -> i32 {
17753    let mut cap = 16usize;
17754    let mut argv = malloc(cap * core::mem::size_of::<*const core::ffi::c_char>()) as *mut *const core::ffi::c_char;
17755    if argv.is_null() { ERRNO!() = ENOMEM; return -1; }
17756    let mut i = 0usize;
17757    let mut args = _args;
17758    loop {
17759        let arg = args.next_arg::<*const core::ffi::c_char>();
17760        if arg.is_null() { break; }
17761        if i + 1 >= cap {
17762            cap = match cap.checked_mul(2) { Some(v) => v, None => { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; } };
17763            let grown = realloc(argv as *mut c_void, cap * core::mem::size_of::<*const core::ffi::c_char>()) as *mut *const core::ffi::c_char;
17764            if grown.is_null() { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; }
17765            argv = grown;
17766        }
17767        *argv.add(i) = arg;
17768        i += 1;
17769    }
17770    *argv.add(i) = core::ptr::null();
17771    let r = execvp(file, argv);
17772    free(argv as *mut c_void);
17773    r
17774}
17775
17776#[no_mangle]
17777pub unsafe extern "C" fn execvp(file: *const core::ffi::c_char, argv: *const *const core::ffi::c_char) -> i32 {
17778    execvpe(file, argv, __environ as *const *const core::ffi::c_char)
17779}
17780
17781#[no_mangle]
17782pub unsafe extern "C" fn fexecve(fd: i32, argv: *const *const core::ffi::c_char, envp: *const *const core::ffi::c_char) -> i32 {
17783    // Read /proc/self/fd/N to get the path
17784    let mut path: [core::ffi::c_char; 64] = [0; 64];
17785    let mut i = 0;
17786    let src = b"/proc/self/fd/\0".as_ptr() as *const core::ffi::c_char;
17787    while i < 63 && *src.add(i) != 0 { path[i] = *src.add(i); i += 1; }
17788    let mut n = fd as usize;
17789    if n == 0 { path[i] = '0' as c_char; i += 1; }
17790    while n > 0 && i < 63 {
17791        path[i] = (b'0' + (n % 10) as u8) as c_char;
17792        n /= 10;
17793        i += 1;
17794    }
17795    path[i] = 0;
17796    crate::execve(path.as_ptr(), argv, envp)
17797}
17798
17799// ============================================================
17800// conf functions
17801// ============================================================
17802
17803#[no_mangle]
17804pub unsafe extern "C" fn confstr(name: i32, buf: *mut core::ffi::c_char, len: usize) -> usize {
17805    // _CS_PATH is the only value with content; the POSIX_V6/V7 option
17806    // strings are empty on Linux. Truncation follows snprintf semantics.
17807    let value: &[u8] = if name == 0 {
17808        b"/bin:/usr/bin"
17809    } else if (1..=37).contains(&name) {
17810        b""
17811    } else {
17812        ERRNO!() = EINVAL;
17813        return 0;
17814    };
17815    let need = value.len() + 1;
17816    if !buf.is_null() && len > 0 {
17817        let n = core::cmp::min(value.len(), len - 1);
17818        core::ptr::copy_nonoverlapping(value.as_ptr(), buf as *mut u8, n);
17819        *buf.add(n) = 0;
17820    }
17821    need
17822}
17823
17824#[no_mangle]
17825pub unsafe extern "C" fn pathconf(_path: *const core::ffi::c_char, name: i32) -> i64 {
17826    // Return default values
17827    match name {
17828        0 => 4096, // _PC_LINK_MAX
17829        1 => 255,  // _PC_MAX_CANON
17830        2 => 255,  // _PC_MAX_INPUT
17831        3 => 255,  // _PC_NAME_MAX
17832        4 => 4096, // _PC_PATH_MAX
17833        5 => 4096, // _PC_PIPE_BUF
17834        6 => 1,    // _PC_CHOWN_RESTRICTED
17835        7 => 0,    // _PC_NO_TRUNC
17836        8 => 0,    // _PC_VDISABLE
17837        _ => -1,
17838    }
17839}
17840
17841#[no_mangle]
17842pub unsafe extern "C" fn fpathconf(_fd: i32, name: i32) -> i64 {
17843    // Return default values
17844    match name {
17845        0 => 4096, // _PC_LINK_MAX
17846        1 => 255,  // _PC_MAX_CANON
17847        2 => 255,  // _PC_MAX_INPUT
17848        3 => 255,  // _PC_NAME_MAX
17849        4 => 4096, // _PC_PATH_MAX
17850        5 => 4096, // _PC_PIPE_BUF
17851        6 => 1,    // _PC_CHOWN_RESTRICTED
17852        7 => 0,    // _PC_NO_TRUNC
17853        8 => 0,    // _PC_VDISABLE
17854        _ => -1,
17855    }
17856}
17857
17858// ============================================================
17859// exp10 functions
17860// ============================================================
17861
17862#[no_mangle]
17863pub unsafe extern "C" fn exp10(x: f64) -> f64 {
17864    libm::pow(10.0, x)
17865}
17866
17867#[no_mangle]
17868pub unsafe extern "C" fn exp10f(x: f32) -> f32 {
17869    libm::powf(10.0, x)
17870}
17871
17872// ============================================================
17873// memory functions
17874// ============================================================
17875
17876#[no_mangle]
17877pub unsafe extern "C" fn explicit_bzero(s: *mut u8, n: usize) {
17878    core::ptr::write_bytes(s, 0, n);
17879    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
17880}
17881
17882#[no_mangle]
17883pub unsafe extern "C" fn memccpy(dest: *mut u8, src: *const u8, c: i32, n: usize) -> *mut u8 {
17884    let mut i = 0;
17885    while i < n {
17886        let byte = *src.add(i);
17887        *dest.add(i) = byte;
17888        if byte == c as u8 {
17889            return dest.add(i + 1);
17890        }
17891        i += 1;
17892    }
17893    core::ptr::null_mut()
17894}
17895
17896// ============================================================
17897// *at functions
17898// ============================================================
17899
17900#[no_mangle]
17901pub unsafe extern "C" fn faccessat(dirfd: i32, pathname: *const core::ffi::c_char, mode: i32, flags: i32) -> i32 {
17902    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FACCESSAT, dirfd as i64, pathname as i64, mode as i64, flags as i64)) as i32
17903}
17904
17905#[no_mangle]
17906pub unsafe extern "C" fn fchmodat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32, flags: i32) -> i32 {
17907    if flags == 0 {
17908        return syscall_ret(<Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, pathname as i64, mode as i64, 0)) as i32;
17909    }
17910    if flags != 0x100 {
17911        // Only AT_SYMLINK_NOFOLLOW is defined for fchmodat.
17912        ERRNO!() = EINVAL;
17913        return -1;
17914    }
17915    syscall_ret(<Arch as Syscalls>::syscall4(sysno(452, 452), dirfd as i64, pathname as i64, mode as i64, flags as i64)) as i32
17916}
17917
17918#[no_mangle]
17919pub unsafe extern "C" fn fchownat(dirfd: i32, pathname: *const core::ffi::c_char, uid: u32, gid: u32, flags: i32) -> i32 {
17920    syscall_ret(<Arch as Syscalls>::syscall5(sysno(260, 54), dirfd as i64, pathname as i64, uid as i64, gid as i64, flags as i64)) as i32
17921}
17922
17923#[no_mangle]
17924pub unsafe extern "C" fn linkat(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char, flags: i32) -> i32 {
17925    syscall_ret(<Arch as Syscalls>::syscall5(SYS_LINKAT, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)) as i32
17926}
17927
17928#[no_mangle]
17929pub unsafe extern "C" fn mkdirat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32) -> i32 {
17930    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, pathname as i64, mode as i64)) as i32
17931}
17932
17933#[no_mangle]
17934pub unsafe extern "C" fn mkfifoat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32) -> i32 {
17935    mknodat(dirfd, pathname, mode | 0o010000, 0)
17936}
17937
17938#[no_mangle]
17939pub unsafe extern "C" fn mknodat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
17940    syscall_ret(<Arch as Syscalls>::syscall4(sysno(259, 33), dirfd as i64, pathname as i64, mode as i64, dev as i64)) as i32
17941}
17942
17943#[no_mangle]
17944pub unsafe extern "C" fn readlinkat(dirfd: i32, pathname: *const core::ffi::c_char, buf: *mut core::ffi::c_char, bufsiz: usize) -> isize {
17945    syscall_ret(<Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, pathname as i64, buf as i64, bufsiz as i64)) as isize
17946}
17947
17948#[no_mangle]
17949pub unsafe extern "C" fn renameat(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char) -> i32 {
17950    syscall_ret(<Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, 0)) as i32
17951}
17952
17953#[no_mangle]
17954pub unsafe extern "C" fn renameat2(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char, flags: u32) -> i32 {
17955    syscall_ret(<Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)) as i32
17956}
17957
17958#[no_mangle]
17959pub unsafe extern "C" fn symlinkat(target: *const core::ffi::c_char, newdirfd: i32, linkpath: *const core::ffi::c_char) -> i32 {
17960    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)) as i32
17961}
17962
17963#[no_mangle]
17964pub unsafe extern "C" fn unlinkat(dirfd: i32, pathname: *const core::ffi::c_char, flags: i32) -> i32 {
17965    syscall_ret(<Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, pathname as i64, flags as i64)) as i32
17966}
17967
17968#[no_mangle]
17969pub unsafe extern "C" fn utimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
17970    utimensat(AT_FDCWD, filename, times as *const timespec, 0)
17971}
17972
17973#[no_mangle]
17974pub unsafe extern "C" fn futimes(fd: i32, times: *const core::ffi::c_void) -> i32 {
17975    utimensat(fd, core::ptr::null(), times as *const timespec, 0)
17976}
17977
17978// ============================================================
17979// inotify functions
17980// ============================================================
17981
17982#[no_mangle]
17983pub unsafe extern "C" fn inotify_init() -> i32 {
17984    syscall_ret(<Arch as Syscalls>::syscall1(sysno(253, 26), 0)) as i32
17985}
17986
17987#[no_mangle]
17988pub unsafe extern "C" fn inotify_init1(flags: i32) -> i32 {
17989    syscall_ret(<Arch as Syscalls>::syscall1(sysno(294, 26), flags as i64)) as i32
17990}
17991
17992#[no_mangle]
17993pub unsafe extern "C" fn inotify_add_watch(fd: i32, pathname: *const core::ffi::c_char, mask: u32) -> i32 {
17994    syscall_ret(<Arch as Syscalls>::syscall3(sysno(254, 27), fd as i64, pathname as i64, mask as i64)) as i32
17995}
17996
17997#[no_mangle]
17998pub unsafe extern "C" fn inotify_rm_watch(fd: i32, wd: i32) -> i32 {
17999    syscall_ret(<Arch as Syscalls>::syscall2(sysno(255, 28), fd as i64, wd as i64)) as i32
18000}
18001
18002#[no_mangle]
18003pub unsafe extern "C" fn fanotify_init(flags: i32, event_f_flags: i32) -> i32 {
18004    syscall_ret(<Arch as Syscalls>::syscall2(sysno(300, 262), flags as i64, event_f_flags as i64)) as i32
18005}
18006
18007#[no_mangle]
18008pub unsafe extern "C" fn fanotify_mark(fd: i32, flags: i32, mask: u64, dirfd: i32, pathname: *const core::ffi::c_char) -> i32 {
18009    syscall_ret(<Arch as Syscalls>::syscall5(sysno(301, 263), fd as i64, flags as i64, mask as i64, dirfd as i64, pathname as i64)) as i32
18010}
18011
18012// ============================================================
18013// ffs functions
18014// ============================================================
18015
18016#[no_mangle]
18017pub unsafe extern "C" fn ffs(x: i32) -> i32 {
18018    if x == 0 { return 0; }
18019    x.trailing_zeros() as i32 + 1
18020}
18021
18022#[no_mangle]
18023pub unsafe extern "C" fn ffsl(x: i64) -> i32 {
18024    if x == 0 { return 0; }
18025    x.trailing_zeros() as i32 + 1
18026}
18027
18028#[no_mangle]
18029pub unsafe extern "C" fn ffsll(x: i64) -> i32 {
18030    if x == 0 { return 0; }
18031    x.trailing_zeros() as i32 + 1
18032}
18033
18034// ============================================================
18035// More system functions
18036// ============================================================
18037
18038#[no_mangle]
18039pub unsafe extern "C" fn fchdir(fd: i32) -> i32 {
18040    syscall_ret(<Arch as Syscalls>::syscall1(SYS_FCHDIR, fd as i64)) as i32
18041}
18042
18043#[no_mangle]
18044pub unsafe extern "C" fn fchown(fd: i32, uid: u32, gid: u32) -> i32 {
18045    syscall_ret(<Arch as Syscalls>::syscall3(SYS_FCHOWN, fd as i64, uid as i64, gid as i64)) as i32
18046}
18047
18048#[no_mangle]
18049pub unsafe extern "C" fn fdopendir(fd: i32) -> *mut core::ffi::c_void {
18050    if fd < 0 { ERRNO!() = 9; return core::ptr::null_mut(); }
18051    dir_stream_new(fd)
18052}
18053
18054#[no_mangle]
18055pub unsafe extern "C" fn getdtablesize() -> i32 {
18056    let mut rlim: Rlimit = core::mem::zeroed();
18057    if getrlimit(RLIMIT_NOFILE, &mut rlim) == 0 {
18058        rlim.rlim_cur as i32
18059    } else {
18060        1024
18061    }
18062}
18063
18064#[no_mangle]
18065pub unsafe extern "C" fn getentropy(buf: *mut u8, buflen: usize) -> i32 {
18066    if buflen > 256 {
18067        ERRNO!() = EIO_VAL;
18068        return -1;
18069    }
18070    let mut pos = buf;
18071    let mut left = buflen;
18072    while left > 0 {
18073        let r = getrandom(pos, left, 0);
18074        if r < 0 {
18075            if ERRNO!() == EINTR_VAL {
18076                continue;
18077            }
18078            return -1;
18079        }
18080        pos = pos.add(r as usize);
18081        left -= r as usize;
18082    }
18083    0
18084}
18085
18086#[no_mangle]
18087pub unsafe extern "C" fn getrandom(buf: *mut u8, buflen: usize, flags: u32) -> isize {
18088    if let Some(r) = vgetrandom(buf, buflen, flags) {
18089        return if r < 0 {
18090            ERRNO!() = (-r) as c_int;
18091            -1
18092        } else {
18093            r
18094        };
18095    }
18096    let r = <Arch as Syscalls>::syscall3(sysno(318, 278), buf as i64, buflen as i64, flags as i64);
18097    if r < 0 {
18098        ERRNO!() = (-r) as c_int;
18099        -1
18100    } else {
18101        r as isize
18102    }
18103}
18104
18105#[no_mangle]
18106pub unsafe extern "C" fn killpg(pgrp: i32, sig: i32) -> i32 {
18107    syscall_ret(<Arch as Syscalls>::syscall2(SYS_KILL, -pgrp as i64, sig as i64)) as i32
18108}
18109
18110#[no_mangle]
18111pub unsafe extern "C" fn mkfifo(pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18112    mknod(pathname, 0o010000 | mode, 0)
18113}
18114
18115// ============================================================
18116// Memory allocation functions
18117// ============================================================
18118
18119#[no_mangle]
18120pub unsafe extern "C" fn aligned_alloc(alignment: usize, size: usize) -> *mut core::ffi::c_void {
18121    alloc_aligned_impl(alignment, size) as *mut core::ffi::c_void
18122}
18123
18124#[no_mangle]
18125pub unsafe extern "C" fn memalign(alignment: usize, size: usize) -> *mut core::ffi::c_void {
18126    alloc_aligned_impl(alignment, size) as *mut core::ffi::c_void
18127}
18128
18129#[no_mangle]
18130pub unsafe extern "C" fn posix_memalign(memptr: *mut *mut core::ffi::c_void, alignment: usize, size: usize) -> i32 {
18131    if memptr.is_null() { return EINVAL; }
18132    if alignment < core::mem::size_of::<*mut core::ffi::c_void>() || !alignment.is_power_of_two() {
18133        return EINVAL;
18134    }
18135    let p = alloc_aligned_impl(alignment, size);
18136    if p.is_null() { return ENOMEM; }
18137    *memptr = p as *mut core::ffi::c_void;
18138    0
18139}
18140
18141#[no_mangle]
18142pub unsafe extern "C" fn valloc(size: usize) -> *mut core::ffi::c_void {
18143    alloc_aligned_impl(PAGE, size) as *mut core::ffi::c_void
18144}
18145
18146// ============================================================
18147// glob functions
18148// ============================================================
18149
18150// ============================================================
18151// wordexp functions
18152// ============================================================
18153
18154// ============================================================
18155// gettext functions
18156// ============================================================
18157
18158#[no_mangle]
18159pub unsafe extern "C" fn gettext(msgid: *const core::ffi::c_char) -> *const core::ffi::c_char {
18160    msgid
18161}
18162
18163#[no_mangle]
18164pub unsafe extern "C" fn dgettext(_domainname: *const core::ffi::c_char, msgid: *const core::ffi::c_char) -> *const core::ffi::c_char {
18165    msgid
18166}
18167
18168#[no_mangle]
18169pub unsafe extern "C" fn dcgettext(_domainname: *const core::ffi::c_char, msgid: *const core::ffi::c_char, _category: i32) -> *const core::ffi::c_char {
18170    msgid
18171}
18172
18173#[no_mangle]
18174pub unsafe extern "C" fn ngettext(msgid1: *const core::ffi::c_char, msgid2: *const core::ffi::c_char, n: u64) -> *const core::ffi::c_char {
18175    if n == 1 { msgid1 } else { msgid2 }
18176}
18177
18178#[no_mangle]
18179pub unsafe extern "C" fn dngettext(_domainname: *const core::ffi::c_char, msgid1: *const core::ffi::c_char, msgid2: *const core::ffi::c_char, n: u64) -> *const core::ffi::c_char {
18180    if n == 1 { msgid1 } else { msgid2 }
18181}
18182
18183#[no_mangle]
18184pub unsafe extern "C" fn dcngettext(_domainname: *const core::ffi::c_char, msgid1: *const core::ffi::c_char, msgid2: *const core::ffi::c_char, n: u64, _category: i32) -> *const core::ffi::c_char {
18185    if n == 1 { msgid1 } else { msgid2 }
18186}
18187
18188#[no_mangle]
18189pub unsafe extern "C" fn textdomain(domainname: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18190    static mut DOMAIN: [core::ffi::c_char; 256] = [0; 256];
18191    if domainname.is_null() { return DOMAIN.as_mut_ptr(); }
18192    let mut i = 0;
18193    while i < 255 && *domainname.add(i) != 0 {
18194        DOMAIN[i] = *domainname.add(i);
18195        i += 1;
18196    }
18197    DOMAIN[i] = 0;
18198    DOMAIN.as_mut_ptr()
18199}
18200
18201#[no_mangle]
18202pub unsafe extern "C" fn bindtextdomain(_domainname: *const core::ffi::c_char, dirname: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18203    dirname as *mut core::ffi::c_char
18204}
18205
18206#[no_mangle]
18207pub unsafe extern "C" fn bind_textdomain_codeset(_domainname: *const core::ffi::c_char, codeset: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18208    codeset as *mut core::ffi::c_char
18209}
18210
18211// ============================================================
18212// Wide string functions
18213// ============================================================
18214
18215#[no_mangle]
18216pub unsafe extern "C" fn wmemcpy(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18217    let mut i = 0;
18218    while i < n {
18219        *dest.add(i) = *src.add(i);
18220        i += 1;
18221    }
18222    dest
18223}
18224
18225#[no_mangle]
18226pub unsafe extern "C" fn wmemmove(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18227    if dest as usize <= src as usize {
18228        let mut i = 0;
18229        while i < n {
18230            *dest.add(i) = *src.add(i);
18231            i += 1;
18232        }
18233    } else {
18234        let mut i = n;
18235        while i > 0 {
18236            i -= 1;
18237            *dest.add(i) = *src.add(i);
18238        }
18239    }
18240    dest
18241}
18242
18243#[no_mangle]
18244pub unsafe extern "C" fn wmemset(dest: *mut u32, c: u32, n: usize) -> *mut u32 {
18245    let mut i = 0;
18246    while i < n {
18247        *dest.add(i) = c;
18248        i += 1;
18249    }
18250    dest
18251}
18252
18253#[no_mangle]
18254pub unsafe extern "C" fn wmemcmp(s1: *const u32, s2: *const u32, n: usize) -> i32 {
18255    let mut i = 0;
18256    while i < n {
18257        let c1 = *s1.add(i);
18258        let c2 = *s2.add(i);
18259        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
18260        i += 1;
18261    }
18262    0
18263}
18264
18265#[no_mangle]
18266pub unsafe extern "C" fn wmemchr(s: *const u32, c: u32, n: usize) -> *mut u32 {
18267    let mut i = 0;
18268    while i < n {
18269        if *s.add(i) == c { return s.add(i) as *mut u32; }
18270        i += 1;
18271    }
18272    core::ptr::null_mut()
18273}
18274
18275#[no_mangle]
18276pub unsafe extern "C" fn wcpcpy(dest: *mut u32, src: *const u32) -> *mut u32 {
18277    let mut i = 0;
18278    loop {
18279        let c = *src.add(i);
18280        *dest.add(i) = c;
18281        if c == 0 { return dest.add(i); }
18282        i += 1;
18283    }
18284}
18285
18286#[no_mangle]
18287pub unsafe extern "C" fn wcpncpy(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18288    let mut i = 0;
18289    while i < n {
18290        let c = *src.add(i);
18291        *dest.add(i) = c;
18292        if c == 0 { return dest.add(i); }
18293        i += 1;
18294    }
18295    dest.add(n)
18296}
18297
18298#[no_mangle]
18299pub unsafe extern "C" fn wprintf(fmt: *const wchar_t, args: ...) -> c_int {
18300    vfwprintf(stdout, fmt, args)
18301}
18302
18303#[no_mangle]
18304pub unsafe extern "C" fn vwprintf(fmt: *const wchar_t, ap: core::ffi::VaList) -> c_int {
18305    vfwprintf(stdout, fmt, ap)
18306}
18307
18308// ============================================================
18309// C32 functions
18310// ============================================================
18311
18312#[no_mangle]
18313pub unsafe extern "C" fn c16rtomb(s: *mut u8, c16: u16, ps: *mut core::ffi::c_void) -> usize {
18314    // UTF-16 to UTF-8, with surrogate pairs tracked in the mbstate.
18315    let state = ps as *mut u32;
18316    let saved: u32 = if state.is_null() { 0 } else { *state };
18317    if s.is_null() {
18318        if !state.is_null() { *state = 0; }
18319        return 1;
18320    }
18321    let cp: u32;
18322    if saved != 0 {
18323        if c16 < 0xdc00 || c16 > 0xdfff {
18324            if !state.is_null() { *state = 0; }
18325            ERRNO!() = EILSEQ;
18326            return !0usize;
18327        }
18328        cp = 0x10000 + (((saved - 0xd800) << 10) | ((c16 as u32) - 0xdc00));
18329        if !state.is_null() { *state = 0; }
18330    } else if c16 >= 0xd800 && c16 <= 0xdbff {
18331        if !state.is_null() { *state = c16 as u32; }
18332        return 0;
18333    } else if c16 >= 0xdc00 && c16 <= 0xdfff {
18334        ERRNO!() = EILSEQ;
18335        return !0usize;
18336    } else {
18337        cp = c16 as u32;
18338    }
18339    if cp < 0x80 {
18340        *s = cp as u8;
18341        1
18342    } else if cp < 0x800 {
18343        *s = (0xc0 | (cp >> 6)) as u8;
18344        *s.add(1) = (0x80 | (cp & 0x3f)) as u8;
18345        2
18346    } else if cp < 0x10000 {
18347        *s = (0xe0 | (cp >> 12)) as u8;
18348        *s.add(1) = (0x80 | ((cp >> 6) & 0x3f)) as u8;
18349        *s.add(2) = (0x80 | (cp & 0x3f)) as u8;
18350        3
18351    } else {
18352        *s = (0xf0 | (cp >> 18)) as u8;
18353        *s.add(1) = (0x80 | ((cp >> 12) & 0x3f)) as u8;
18354        *s.add(2) = (0x80 | ((cp >> 6) & 0x3f)) as u8;
18355        *s.add(3) = (0x80 | (cp & 0x3f)) as u8;
18356        4
18357    }
18358}
18359
18360#[no_mangle]
18361pub unsafe extern "C" fn c32rtomb(s: *mut u8, c32: u32, _ps: *mut core::ffi::c_void) -> usize {
18362    if s.is_null() { return 1; }
18363    if c32 > 0x10ffff || (c32 >= 0xd800 && c32 <= 0xdfff) {
18364        ERRNO!() = EILSEQ;
18365        return !0usize;
18366    }
18367    if c32 < 0x80 {
18368        *s = c32 as u8;
18369        1
18370    } else if c32 < 0x800 {
18371        *s = (0xc0 | (c32 >> 6)) as u8;
18372        *s.add(1) = (0x80 | (c32 & 0x3f)) as u8;
18373        2
18374    } else if c32 < 0x10000 {
18375        *s = (0xe0 | (c32 >> 12)) as u8;
18376        *s.add(1) = (0x80 | ((c32 >> 6) & 0x3f)) as u8;
18377        *s.add(2) = (0x80 | (c32 & 0x3f)) as u8;
18378        3
18379    } else {
18380        *s = (0xf0 | (c32 >> 18)) as u8;
18381        *s.add(1) = (0x80 | ((c32 >> 12) & 0x3f)) as u8;
18382        *s.add(2) = (0x80 | ((c32 >> 6) & 0x3f)) as u8;
18383        *s.add(3) = (0x80 | (c32 & 0x3f)) as u8;
18384        4
18385    }
18386}
18387
18388#[no_mangle]
18389pub unsafe extern "C" fn mbrtoc16(pc16: *mut u16, s: *const u8, n: usize, _ps: *mut core::ffi::c_void) -> usize {
18390    if s.is_null() { return 0; }
18391    if n == 0 { return 1; }
18392    let c = *s;
18393    if c == 0 { return 0; }
18394    if c < 0x80 {
18395        if !pc16.is_null() { *pc16 = c as u16; }
18396        return 1;
18397    }
18398    if c < 0xC2 { return 1; } // Invalid
18399    if c < 0xE0 {
18400        if n < 2 { return 1; }
18401        let c2 = *s.add(1);
18402        if (c2 & 0xC0) != 0x80 { return 1; }
18403        if !pc16.is_null() { *pc16 = ((((c & 0x1F) as u32) << 6) | ((c2 & 0x3F) as u32)) as u16; }
18404        return 2;
18405    }
18406    if c < 0xF0 {
18407        if n < 3 { return 1; }
18408        let c2 = *s.add(1);
18409        let c3 = *s.add(2);
18410        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 { return 1; }
18411        if !pc16.is_null() { *pc16 = ((((c & 0x0F) as u32) << 12) | (((c2 & 0x3F) as u32) << 6) | ((c3 & 0x3F) as u32)) as u16; }
18412        return 3;
18413    }
18414    1
18415}
18416
18417#[no_mangle]
18418pub unsafe extern "C" fn mbrtoc32(pc32: *mut u32, s: *const u8, n: usize, _ps: *mut core::ffi::c_void) -> usize {
18419    if s.is_null() { return 0; }
18420    if n == 0 { return 1; }
18421    let c = *s;
18422    if c == 0 { return 0; }
18423    if c < 0x80 {
18424        if !pc32.is_null() { *pc32 = c as u32; }
18425        return 1;
18426    }
18427    if c < 0xC2 { return 1; } // Invalid
18428    if c < 0xE0 {
18429        if n < 2 { return 1; }
18430        let c2 = *s.add(1);
18431        if (c2 & 0xC0) != 0x80 { return 1; }
18432        if !pc32.is_null() { *pc32 = (((c & 0x1F) as u32) << 6) | ((c2 & 0x3F) as u32); }
18433        return 2;
18434    }
18435    if c < 0xF0 {
18436        if n < 3 { return 1; }
18437        let c2 = *s.add(1);
18438        let c3 = *s.add(2);
18439        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 { return 1; }
18440        if !pc32.is_null() { *pc32 = (((c & 0x0F) as u32) << 12) | (((c2 & 0x3F) as u32) << 6) | ((c3 & 0x3F) as u32); }
18441        return 3;
18442    }
18443    if c < 0xF5 {
18444        if n < 4 { return 1; }
18445        let c2 = *s.add(1);
18446        let c3 = *s.add(2);
18447        let c4 = *s.add(3);
18448        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80 { return 1; }
18449        if !pc32.is_null() { *pc32 = (((c & 0x07) as u32) << 18) | (((c2 & 0x3F) as u32) << 12) | (((c3 & 0x3F) as u32) << 6) | ((c4 & 0x3F) as u32); }
18450        return 4;
18451    }
18452    1
18453}
18454
18455// ============================================================
18456// Shadow functions
18457// ============================================================
18458
18459
18460
18461
18462// ============================================================
18463// chown functions
18464// ============================================================
18465
18466#[no_mangle]
18467pub unsafe extern "C" fn chown(path: *const core::ffi::c_char, uid: u32, gid: u32) -> i32 {
18468    syscall_ret(<Arch as Syscalls>::syscall5(
18469        SYS_FCHOWNAT,
18470        AT_FDCWD as i64,
18471        path as i64,
18472        uid as i64,
18473        gid as i64,
18474        0,
18475    )) as i32
18476}
18477
18478#[no_mangle]
18479pub unsafe extern "C" fn lchown(path: *const core::ffi::c_char, uid: u32, gid: u32) -> i32 {
18480    syscall_ret(<Arch as Syscalls>::syscall5(
18481        SYS_FCHOWNAT,
18482        AT_FDCWD as i64,
18483        path as i64,
18484        uid as i64,
18485        gid as i64,
18486        0x100, // AT_SYMLINK_NOFOLLOW
18487    )) as i32
18488}
18489
18490// ============================================================
18491// chroot functions
18492// ============================================================
18493
18494#[no_mangle]
18495pub unsafe extern "C" fn chroot(path: *const core::ffi::c_char) -> i32 {
18496    syscall_ret(<Arch as Syscalls>::syscall1(SYS_CHROOT, path as i64)) as i32
18497}
18498
18499#[no_mangle]
18500pub unsafe extern "C" fn get_current_dir_name() -> *mut core::ffi::c_char {
18501    static mut BUF: [core::ffi::c_char; 4096] = [0; 4096];
18502    let r = getcwd(BUF.as_mut_ptr(), 4096);
18503    if r.is_null() { core::ptr::null_mut() } else { BUF.as_mut_ptr() }
18504}
18505
18506// ============================================================
18507// I/O functions
18508// ============================================================
18509
18510#[no_mangle]
18511pub unsafe extern "C" fn creat(pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18512    // O_WRONLY | O_CREAT | O_TRUNC. The previous flags included O_EXCL.
18513    open(pathname, 1 | 0o100 | 0o1000, mode as i32)
18514}
18515
18516#[no_mangle]
18517pub unsafe extern "C" fn openat(dirfd: i32, pathname: *const core::ffi::c_char, flags: i32, mode: u32) -> i32 {
18518    syscall_ret(<Arch as Syscalls>::syscall4(SYS_OPENAT, dirfd as i64, pathname as i64, flags as i64, mode as i64)) as i32
18519}
18520
18521#[no_mangle]
18522pub unsafe extern "C" fn pwrite(fd: i32, buf: *const u8, count: usize, offset: i64) -> isize {
18523    syscall_ret(<Arch as Syscalls>::syscall4(sysno(18, 68), fd as i64, buf as i64, count as i64, offset)) as isize
18524}
18525
18526#[no_mangle]
18527pub unsafe extern "C" fn readv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32) -> isize {
18528    syscall_ret(<Arch as Syscalls>::syscall3(sysno(19, 65), fd as i64, iov as i64, iovcnt as i64)) as isize
18529}
18530
18531#[no_mangle]
18532pub unsafe extern "C" fn writev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32) -> isize {
18533    syscall_ret(<Arch as Syscalls>::syscall3(sysno(20, 66), fd as i64, iov as i64, iovcnt as i64)) as isize
18534}
18535
18536// ============================================================
18537// Lock functions
18538// ============================================================
18539
18540#[no_mangle]
18541pub unsafe extern "C" fn flock(fd: i32, operation: i32) -> i32 {
18542    syscall_ret(<Arch as Syscalls>::syscall2(SYS_FLOCK, fd as i64, operation as i64)) as i32
18543}
18544
18545#[no_mangle]
18546pub unsafe extern "C" fn lockf(fd: i32, cmd: i32, len: i64) -> i32 {
18547    let r = <Arch as Syscalls>::syscall3(SYS_FCNTL, fd as i64, if cmd == 0 { 7 } else if cmd == 1 { 6 } else { 5 } , len);
18548    if r < 0 { return -1; }
18549    0
18550}
18551
18552// ============================================================
18553// Hostname/login functions
18554// ============================================================
18555
18556#[no_mangle]
18557pub unsafe extern "C" fn getdomainname(name: *mut core::ffi::c_char, len: usize) -> i32 {
18558    if name.is_null() || len == 0 {
18559        ERRNO!() = EINVAL;
18560        return -1;
18561    }
18562    let mut uts: UtsName = core::mem::zeroed();
18563    let r = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
18564    if r < 0 {
18565        ERRNO!() = (-r) as c_int;
18566        return -1;
18567    }
18568    let mut n = 0usize;
18569    while n < uts.domainname.len() && uts.domainname[n] != 0 { n += 1; }
18570    if n >= len {
18571        ERRNO!() = EINVAL;
18572        return -1;
18573    }
18574    core::ptr::copy_nonoverlapping(uts.domainname.as_ptr(), name as *mut u8, n);
18575    *name.add(n) = 0;
18576    0
18577}
18578
18579#[no_mangle]
18580pub unsafe extern "C" fn setdomainname(name: *const core::ffi::c_char, len: usize) -> i32 {
18581    syscall_ret(<Arch as Syscalls>::syscall2(sysno(171, 162), name as i64, len as i64)) as i32
18582}
18583
18584#[no_mangle]
18585pub unsafe extern "C" fn sethostname(name: *const core::ffi::c_char, len: usize) -> i32 {
18586    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)) as i32
18587}
18588
18589#[no_mangle]
18590pub unsafe extern "C" fn getlogin_r(name: *mut core::ffi::c_char, bufsize: usize) -> i32 {
18591    let user = getlogin();
18592    if user.is_null() { return ENXIO_VAL; }
18593    let len = crate::strlen(user);
18594    if len >= bufsize { return 34; } // ERANGE
18595    core::ptr::copy_nonoverlapping(user, name, len + 1);
18596    0
18597}
18598
18599#[no_mangle]
18600pub unsafe extern "C" fn cuserid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
18601    let user = crate::getenv(b"USER\0".as_ptr() as *const core::ffi::c_char);
18602    if user.is_null() { return core::ptr::null_mut(); }
18603    if s.is_null() {
18604        static mut BUF: [core::ffi::c_char; 32] = [0; 32];
18605        let mut i = 0;
18606        while i < 31 && *user.add(i) != 0 { BUF[i] = *user.add(i); i += 1; }
18607        BUF[i] = 0;
18608        BUF.as_mut_ptr()
18609    } else {
18610        let mut i = 0;
18611        while i < 31 && *user.add(i) != 0 { *s.add(i) = *user.add(i); i += 1; }
18612        *s.add(i) = 0;
18613        s
18614    }
18615}
18616
18617// ============================================================
18618// Group and passwd functions
18619// ============================================================
18620
18621#[repr(C)]
18622#[derive(Copy, Clone)]
18623pub struct Passwd {
18624    pub pw_name: *mut c_char,
18625    pub pw_passwd: *mut c_char,
18626    pub pw_uid: u32,
18627    pub pw_gid: u32,
18628    pub pw_gecos: *mut c_char,
18629    pub pw_dir: *mut c_char,
18630    pub pw_shell: *mut c_char,
18631}
18632
18633#[repr(C)]
18634#[derive(Copy, Clone)]
18635pub struct Group {
18636    pub gr_name: *mut c_char,
18637    pub gr_passwd: *mut c_char,
18638    pub gr_gid: u32,
18639    pub gr_mem: *mut *mut c_char,
18640}
18641
18642static mut PWD_ENT: Passwd = Passwd {
18643    pw_name: core::ptr::null_mut(), pw_passwd: core::ptr::null_mut(),
18644    pw_uid: 0, pw_gid: 0, pw_gecos: core::ptr::null_mut(),
18645    pw_dir: core::ptr::null_mut(), pw_shell: core::ptr::null_mut(),
18646};
18647static mut PWD_LINE: *mut c_char = core::ptr::null_mut();
18648static mut PWD_LINE_CAP: usize = 0;
18649static mut PWD_BUF: *mut c_char = core::ptr::null_mut();
18650static mut PWD_BUF_CAP: usize = 0;
18651static mut PWD_FILE: *mut FILE = core::ptr::null_mut();
18652
18653unsafe fn ensure_pwd_buf(n: usize) -> bool {
18654    if n <= PWD_BUF_CAP {
18655        return true;
18656    }
18657    let mut cap = if PWD_BUF_CAP == 0 { 1024 } else { PWD_BUF_CAP };
18658    while cap < n {
18659        cap *= 2;
18660    }
18661    let p = realloc(PWD_BUF as *mut c_void, cap) as *mut c_char;
18662    if p.is_null() {
18663        return false;
18664    }
18665    PWD_BUF = p;
18666    PWD_BUF_CAP = cap;
18667    true
18668}
18669
18670static mut GRP_ENT: Group = Group {
18671    gr_name: core::ptr::null_mut(), gr_passwd: core::ptr::null_mut(),
18672    gr_gid: 0, gr_mem: core::ptr::null_mut(),
18673};
18674static mut GRP_LINE: *mut c_char = core::ptr::null_mut();
18675static mut GRP_LINE_CAP: usize = 0;
18676static mut GRP_BUF: *mut c_char = core::ptr::null_mut();
18677static mut GRP_BUF_CAP: usize = 0;
18678static mut GRP_MEM: *mut *mut c_char = core::ptr::null_mut();
18679static mut GRP_MEM_CAP: usize = 0;
18680static mut GRP_FILE: *mut FILE = core::ptr::null_mut();
18681
18682unsafe fn ensure_grp_buf(n: usize) -> bool {
18683    if n <= GRP_BUF_CAP {
18684        return true;
18685    }
18686    let mut cap = if GRP_BUF_CAP == 0 { 2048 } else { GRP_BUF_CAP };
18687    while cap < n {
18688        cap *= 2;
18689    }
18690    let p = realloc(GRP_BUF as *mut c_void, cap) as *mut c_char;
18691    if p.is_null() {
18692        return false;
18693    }
18694    GRP_BUF = p;
18695    GRP_BUF_CAP = cap;
18696    true
18697}
18698
18699unsafe fn ensure_grp_mem(n: usize) -> bool {
18700    if n <= GRP_MEM_CAP {
18701        return true;
18702    }
18703    let mut cap = if GRP_MEM_CAP == 0 { 32 } else { GRP_MEM_CAP };
18704    while cap < n {
18705        cap *= 2;
18706    }
18707    let p = realloc(
18708        GRP_MEM as *mut c_void,
18709        cap * core::mem::size_of::<*mut c_char>(),
18710    ) as *mut *mut c_char;
18711    if p.is_null() {
18712        return false;
18713    }
18714    GRP_MEM = p;
18715    GRP_MEM_CAP = cap;
18716    true
18717}
18718
18719unsafe fn parse_passwd(line: *const c_char, ent: *mut Passwd, buf: *mut c_char, buflen: usize) -> bool {
18720    let mut src = line;
18721    let mut o = 0usize;
18722    let mut fields: [*mut c_char; 7] = [core::ptr::null_mut(); 7];
18723    let mut n = 0usize;
18724    while n < 7 {
18725        let start = o;
18726        while *src != 0 && *src != b':' as c_char {
18727            if o + 1 >= buflen { return false; }
18728            *buf.add(o) = *src;
18729            o += 1;
18730            src = src.add(1);
18731        }
18732        *buf.add(o) = 0;
18733        o += 1;
18734        fields[n] = buf.add(start);
18735        n += 1;
18736        if *src == 0 { break; }
18737        src = src.add(1);
18738    }
18739    if n < 7 { return false; }
18740    (*ent).pw_name = fields[0];
18741    (*ent).pw_passwd = fields[1];
18742    (*ent).pw_uid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
18743    (*ent).pw_gid = crate::strtol(fields[3], core::ptr::null_mut(), 10) as u32;
18744    (*ent).pw_gecos = fields[4];
18745    (*ent).pw_dir = fields[5];
18746    (*ent).pw_shell = fields[6];
18747    true
18748}
18749
18750unsafe fn parse_group(line: *const c_char, ent: *mut Group, buf: *mut c_char, buflen: usize) -> bool {
18751    let mut src = line;
18752    let mut o = 0usize;
18753    let mut fields: [*mut c_char; 4] = [core::ptr::null_mut(); 4];
18754    let mut n = 0usize;
18755    while n < 4 {
18756        let start = o;
18757        while *src != 0 && *src != b':' as c_char {
18758            if o + 1 >= buflen { return false; }
18759            *buf.add(o) = *src;
18760            o += 1;
18761            src = src.add(1);
18762        }
18763        *buf.add(o) = 0;
18764        o += 1;
18765        fields[n] = buf.add(start);
18766        n += 1;
18767        if *src == 0 { break; }
18768        src = src.add(1);
18769    }
18770    if n < 4 { return false; }
18771    (*ent).gr_name = fields[0];
18772    (*ent).gr_passwd = fields[1];
18773    (*ent).gr_gid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
18774    let mut count = 1usize;
18775    let mut m = fields[3];
18776    while *m != 0 {
18777        if *m == b',' as c_char { count += 1; }
18778        m = m.add(1);
18779    }
18780    if !ensure_grp_mem(count + 1) { return false; }
18781    let mut mi = 0usize;
18782    m = fields[3];
18783    if *m != 0 {
18784        loop {
18785            *GRP_MEM.add(mi) = m;
18786            mi += 1;
18787            while *m != 0 && *m != b',' as c_char { m = m.add(1); }
18788            if *m == 0 { break; }
18789            *m = 0;
18790            m = m.add(1);
18791        }
18792    }
18793    *GRP_MEM.add(mi) = core::ptr::null_mut();
18794    (*ent).gr_mem = GRP_MEM;
18795    true
18796}
18797
18798#[no_mangle]
18799pub unsafe extern "C" fn getpwnam(name: *const c_char) -> *mut Passwd {
18800    if name.is_null() { return core::ptr::null_mut(); }
18801    setpwent();
18802    loop {
18803        let p = getpwent();
18804        if p.is_null() { break; }
18805        if crate::strcmp((*p).pw_name as *const u8, name as *const u8) == 0 { endpwent(); return p; }
18806    }
18807    endpwent();
18808    core::ptr::null_mut()
18809}
18810
18811#[no_mangle]
18812pub unsafe extern "C" fn getpwuid(uid: u32) -> *mut Passwd {
18813    setpwent();
18814    loop {
18815        let p = getpwent();
18816        if p.is_null() { break; }
18817        if (*p).pw_uid == uid { endpwent(); return p; }
18818    }
18819    endpwent();
18820    core::ptr::null_mut()
18821}
18822
18823#[no_mangle]
18824pub unsafe extern "C" fn setpwent() {
18825    endpwent();
18826    PWD_FILE = crate::fopen(b"/etc/passwd\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
18827}
18828
18829#[no_mangle]
18830pub unsafe extern "C" fn getpwent() -> *mut Passwd {
18831    if PWD_FILE.is_null() { setpwent(); if PWD_FILE.is_null() { return core::ptr::null_mut(); } }
18832    loop {
18833        let n = crate::getline(&raw mut PWD_LINE, &raw mut PWD_LINE_CAP, PWD_FILE);
18834        if n < 0 { return core::ptr::null_mut(); }
18835        let mut len = n as usize;
18836        if len > 0 && *PWD_LINE.add(len - 1) == b'\n' as c_char {
18837            *PWD_LINE.add(len - 1) = 0;
18838            len -= 1;
18839        }
18840        let need = len + 1;
18841        if !ensure_pwd_buf(need) { return core::ptr::null_mut(); }
18842        if parse_passwd(PWD_LINE, &raw mut PWD_ENT, PWD_BUF, need) {
18843            return &raw mut PWD_ENT;
18844        }
18845    }
18846}
18847
18848#[no_mangle]
18849pub unsafe extern "C" fn endpwent() {
18850    if !PWD_FILE.is_null() { crate::fclose(PWD_FILE); PWD_FILE = core::ptr::null_mut(); }
18851}
18852
18853#[no_mangle]
18854pub unsafe extern "C" fn getpwnam_r(name: *const c_char, pwd: *mut Passwd, _buf: *mut c_char, _buflen: usize, result: *mut *mut Passwd) -> c_int {
18855    if result.is_null() { return EINVAL; }
18856    let p = getpwnam(name);
18857    if p.is_null() { *result = core::ptr::null_mut(); 0 } else { *pwd = *p; *result = pwd; 0 }
18858}
18859
18860#[no_mangle]
18861pub unsafe extern "C" fn getpwuid_r(uid: u32, pwd: *mut Passwd, _buf: *mut c_char, _buflen: usize, result: *mut *mut Passwd) -> c_int {
18862    if result.is_null() { return EINVAL; }
18863    let p = getpwuid(uid);
18864    if p.is_null() { *result = core::ptr::null_mut(); 0 } else { *pwd = *p; *result = pwd; 0 }
18865}
18866
18867#[no_mangle]
18868pub unsafe extern "C" fn fgetpwent(f: *mut FILE) -> *mut Passwd {
18869    if f.is_null() { return core::ptr::null_mut(); }
18870    loop {
18871        let n = crate::getline(&raw mut PWD_LINE, &raw mut PWD_LINE_CAP, f);
18872        if n < 0 { return core::ptr::null_mut(); }
18873        let mut len = n as usize;
18874        if len > 0 && *PWD_LINE.add(len - 1) == b'\n' as c_char {
18875            *PWD_LINE.add(len - 1) = 0;
18876            len -= 1;
18877        }
18878        let need = len + 1;
18879        if !ensure_pwd_buf(need) { return core::ptr::null_mut(); }
18880        if parse_passwd(PWD_LINE, &raw mut PWD_ENT, PWD_BUF, need) {
18881            return &raw mut PWD_ENT;
18882        }
18883    }
18884}
18885
18886#[no_mangle]
18887pub unsafe extern "C" fn putpwent(f: *mut FILE, p: *const Passwd) -> c_int {
18888    if f.is_null() || p.is_null() { return -1; }
18889    crate::fprintf(f, b"%s:%s:%u:%u:%s:%s:%s\n\0".as_ptr() as *const c_char,
18890        (*p).pw_name, (*p).pw_passwd, (*p).pw_uid, (*p).pw_gid,
18891        (*p).pw_gecos, (*p).pw_dir, (*p).pw_shell)
18892}
18893
18894#[no_mangle]
18895pub unsafe extern "C" fn getgrnam(name: *const c_char) -> *mut Group {
18896    if name.is_null() { return core::ptr::null_mut(); }
18897    setgrent();
18898    loop {
18899        let g = getgrent();
18900        if g.is_null() { break; }
18901        if crate::strcmp((*g).gr_name as *const u8, name as *const u8) == 0 { endgrent(); return g; }
18902    }
18903    endgrent();
18904    core::ptr::null_mut()
18905}
18906
18907#[no_mangle]
18908pub unsafe extern "C" fn getgrgid(gid: u32) -> *mut Group {
18909    setgrent();
18910    loop {
18911        let g = getgrent();
18912        if g.is_null() { break; }
18913        if (*g).gr_gid == gid { endgrent(); return g; }
18914    }
18915    endgrent();
18916    core::ptr::null_mut()
18917}
18918
18919#[no_mangle]
18920pub unsafe extern "C" fn setgrent() {
18921    endgrent();
18922    GRP_FILE = crate::fopen(b"/etc/group\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
18923}
18924
18925#[no_mangle]
18926pub unsafe extern "C" fn getgrent() -> *mut Group {
18927    if GRP_FILE.is_null() { setgrent(); if GRP_FILE.is_null() { return core::ptr::null_mut(); } }
18928    loop {
18929        let n = crate::getline(&raw mut GRP_LINE, &raw mut GRP_LINE_CAP, GRP_FILE);
18930        if n < 0 { return core::ptr::null_mut(); }
18931        let mut len = n as usize;
18932        if len > 0 && *GRP_LINE.add(len - 1) == b'\n' as c_char {
18933            *GRP_LINE.add(len - 1) = 0;
18934            len -= 1;
18935        }
18936        let need = len + 1;
18937        if !ensure_grp_buf(need) { return core::ptr::null_mut(); }
18938        if parse_group(GRP_LINE, &raw mut GRP_ENT, GRP_BUF, need) {
18939            return &raw mut GRP_ENT;
18940        }
18941    }
18942}
18943
18944#[no_mangle]
18945pub unsafe extern "C" fn endgrent() {
18946    if !GRP_FILE.is_null() { crate::fclose(GRP_FILE); GRP_FILE = core::ptr::null_mut(); }
18947}
18948
18949#[no_mangle]
18950pub unsafe extern "C" fn getgrnam_r(name: *const c_char, grp: *mut Group, _buf: *mut c_char, _buflen: usize, result: *mut *mut Group) -> c_int {
18951    if result.is_null() { return EINVAL; }
18952    let g = getgrnam(name);
18953    if g.is_null() { *result = core::ptr::null_mut(); 0 } else { *grp = *g; *result = grp; 0 }
18954}
18955
18956#[no_mangle]
18957pub unsafe extern "C" fn getgrgid_r(gid: u32, grp: *mut Group, _buf: *mut c_char, _buflen: usize, result: *mut *mut Group) -> c_int {
18958    if result.is_null() { return EINVAL; }
18959    let g = getgrgid(gid);
18960    if g.is_null() { *result = core::ptr::null_mut(); 0 } else { *grp = *g; *result = grp; 0 }
18961}
18962
18963#[no_mangle]
18964pub unsafe extern "C" fn fgetgrent(f: *mut FILE) -> *mut Group {
18965    if f.is_null() { return core::ptr::null_mut(); }
18966    loop {
18967        let n = crate::getline(&raw mut GRP_LINE, &raw mut GRP_LINE_CAP, f);
18968        if n < 0 { return core::ptr::null_mut(); }
18969        let mut len = n as usize;
18970        if len > 0 && *GRP_LINE.add(len - 1) == b'\n' as c_char {
18971            *GRP_LINE.add(len - 1) = 0;
18972            len -= 1;
18973        }
18974        let need = len + 1;
18975        if !ensure_grp_buf(need) { return core::ptr::null_mut(); }
18976        if parse_group(GRP_LINE, &raw mut GRP_ENT, GRP_BUF, need) {
18977            return &raw mut GRP_ENT;
18978        }
18979    }
18980}
18981
18982#[no_mangle]
18983pub unsafe extern "C" fn putgrent(f: *mut FILE, g: *const Group) -> c_int {
18984    if f.is_null() || g.is_null() { return -1; }
18985    crate::fprintf(f, b"%s:%s:%u:\0".as_ptr() as *const c_char, (*g).gr_name, (*g).gr_passwd, (*g).gr_gid);
18986    if !(*g).gr_mem.is_null() {
18987        let mut i = 0;
18988        while !(*(*g).gr_mem.add(i)).is_null() {
18989            if i > 0 { crate::fputc(b',' as c_int, f); }
18990            crate::fputs(*(*g).gr_mem.add(i), f);
18991            i += 1;
18992        }
18993    }
18994    crate::fputc(b'\n' as c_int, f);
18995    0
18996}
18997
18998// ============================================================
18999// User/group functions
19000// ============================================================
19001
19002#[no_mangle]
19003pub unsafe extern "C" fn setgroups(ngroups: usize, gidset: *const u32) -> i32 {
19004    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETGROUPS, ngroups as i64, gidset as i64)) as i32
19005}
19006
19007#[no_mangle]
19008pub unsafe extern "C" fn setresuid(ruid: u32, euid: u32, suid: u32) -> i32 {
19009    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETRESUID, ruid as i64, euid as i64, suid as i64)) as i32
19010}
19011
19012#[no_mangle]
19013pub unsafe extern "C" fn setresgid(rgid: u32, egid: u32, sgid: u32) -> i32 {
19014    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETRESGID, rgid as i64, egid as i64, sgid as i64)) as i32
19015}
19016
19017#[no_mangle]
19018pub unsafe extern "C" fn getresuid(ruid: *mut u32, euid: *mut u32, suid: *mut u32) -> i32 {
19019    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETRESUID, ruid as i64, euid as i64, suid as i64)) as i32
19020}
19021
19022#[no_mangle]
19023pub unsafe extern "C" fn getresgid(rgid: *mut u32, egid: *mut u32, sgid: *mut u32) -> i32 {
19024    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETRESGID, rgid as i64, egid as i64, sgid as i64)) as i32
19025}
19026
19027// ============================================================
19028// Socket functions
19029// ============================================================
19030
19031// musl's public struct msghdr uses 32-bit msg_iovlen/msg_controllen followed
19032// by padding on 64-bit little-endian. The kernel reads 64-bit fields, so the
19033// padding must be zero; callers (nginx, for example) do not initialize it.
19034#[repr(C)]
19035struct KernelMsgHdr {
19036    msg_name: *mut c_void,
19037    msg_namelen: u32,
19038    __pad0: u32,
19039    msg_iov: *mut c_void,
19040    msg_iovlen: u64,
19041    msg_control: *mut c_void,
19042    msg_controllen: u64,
19043    msg_flags: u32,
19044    __pad1: u32,
19045}
19046
19047#[repr(C)]
19048struct UserMsgHdr {
19049    msg_name: *mut c_void,
19050    msg_namelen: u32,
19051    msg_iov: *mut c_void,
19052    msg_iovlen: i32,
19053    __pad1: i32,
19054    msg_control: *mut c_void,
19055    msg_controllen: u32,
19056    __pad2: i32,
19057    msg_flags: i32,
19058}
19059
19060unsafe fn msg_to_kernel(msg: *const UserMsgHdr, out: &mut KernelMsgHdr) {
19061    *out = KernelMsgHdr {
19062        msg_name: (*msg).msg_name,
19063        msg_namelen: (*msg).msg_namelen,
19064        __pad0: 0,
19065        msg_iov: (*msg).msg_iov,
19066        msg_iovlen: (*msg).msg_iovlen as u32 as u64,
19067        msg_control: (*msg).msg_control,
19068        msg_controllen: (*msg).msg_controllen as u64,
19069        msg_flags: (*msg).msg_flags as u32,
19070        __pad1: 0,
19071    };
19072}
19073
19074#[no_mangle]
19075pub unsafe extern "C" fn sendmsg(fd: i32, msg: *const core::ffi::c_void, flags: i32) -> isize {
19076    if msg.is_null() {
19077        ERRNO!() = EINVAL;
19078        return -1;
19079    }
19080    let mut k: KernelMsgHdr = core::mem::zeroed();
19081    msg_to_kernel(msg as *const UserMsgHdr, &mut k);
19082    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SENDMSG, fd as i64, &k as *const KernelMsgHdr as i64, flags as i64)) as isize
19083}
19084
19085#[no_mangle]
19086pub unsafe extern "C" fn recvmsg(fd: i32, msg: *mut core::ffi::c_void, flags: i32) -> isize {
19087    if msg.is_null() {
19088        ERRNO!() = EINVAL;
19089        return -1;
19090    }
19091    let user = msg as *mut UserMsgHdr;
19092    let mut k: KernelMsgHdr = core::mem::zeroed();
19093    msg_to_kernel(user, &mut k);
19094    let r = syscall_ret(<Arch as Syscalls>::syscall3(SYS_RECVMSG, fd as i64, &mut k as *mut KernelMsgHdr as i64, flags as i64));
19095    (*user).msg_flags = k.msg_flags as i32;
19096    (*user).msg_controllen = k.msg_controllen as u32;
19097    r as isize
19098}
19099
19100#[no_mangle]
19101pub unsafe extern "C" fn sendmmsg(fd: i32, msgvec: *mut core::ffi::c_void, vlen: u32, flags: i32) -> i32 {
19102    syscall_ret(<Arch as Syscalls>::syscall4(sysno(307, 269), fd as i64, msgvec as i64, vlen as i64, flags as i64)) as i32
19103}
19104
19105#[no_mangle]
19106pub unsafe extern "C" fn recvmmsg(fd: i32, msgvec: *mut core::ffi::c_void, vlen: u32, flags: i32, timeout: *mut core::ffi::c_void) -> i32 {
19107    syscall_ret(<Arch as Syscalls>::syscall5(sysno(299, 243), fd as i64, msgvec as i64, vlen as i64, flags as i64, timeout as i64)) as i32
19108}
19109
19110#[no_mangle]
19111pub unsafe extern "C" fn getpeername(fd: i32, addr: *mut core::ffi::c_void, addrlen: *mut u32) -> i32 {
19112    syscall_ret(<Arch as Syscalls>::syscall3(sysno(52, 205), fd as i64, addr as i64, addrlen as i64)) as i32
19113}
19114
19115#[no_mangle]
19116pub unsafe extern "C" fn getsockopt(fd: i32, level: i32, optname: i32, optval: *mut core::ffi::c_void, optlen: *mut u32) -> i32 {
19117    syscall_ret(<Arch as Syscalls>::syscall5(sysno(55, 209), fd as i64, level as i64, optname as i64, optval as i64, optlen as i64)) as i32
19118}
19119
19120// ============================================================
19121// stdio unlocked functions
19122// ============================================================
19123
19124#[no_mangle]
19125pub unsafe extern "C" fn ftrylockfile(file: *mut FILE) -> i32 {
19126    if file.is_null() { return EINVAL; }
19127    if (*file).lock < 0 { return 0; }
19128    let tid = sys_gettid() as c_int;
19129    let v = a_load(&raw const (*file).lock);
19130    if v == tid {
19131        (*file).lockcount += 1;
19132        return 0;
19133    }
19134    if v == 0 && a_cas(&raw mut (*file).lock, 0, tid) == 0 {
19135        (*file).lockcount = 1;
19136        return 0;
19137    }
19138    EBUSY
19139}
19140
19141#[no_mangle]
19142pub unsafe extern "C" fn getc_unlocked(file: *mut core::ffi::c_char) -> i32 {
19143    getc(file as *mut FILE)
19144}
19145
19146#[no_mangle]
19147pub unsafe extern "C" fn getchar_unlocked() -> i32 {
19148    getchar()
19149}
19150
19151#[no_mangle]
19152pub unsafe extern "C" fn putc_unlocked(c: i32, file: *mut core::ffi::c_char) -> i32 {
19153    putc(c, file as *mut FILE)
19154}
19155
19156#[no_mangle]
19157pub unsafe extern "C" fn putchar_unlocked(c: i32) -> i32 {
19158    putchar(c)
19159}
19160
19161// ============================================================
19162// getopt functions
19163// ============================================================
19164
19165#[no_mangle] pub static mut optarg: *mut core::ffi::c_char = core::ptr::null_mut();
19166#[no_mangle] pub static mut optind: i32 = 1;
19167#[no_mangle] pub static mut opterr: i32 = 1;
19168#[no_mangle] pub static mut optopt: i32 = '?' as i32;
19169#[no_mangle] pub static mut optreset: i32 = 0;
19170
19171// ============================================================
19172// Timer functions
19173// ============================================================
19174
19175#[no_mangle]
19176pub unsafe extern "C" fn getitimer(which: i32, curr_value: *mut core::ffi::c_void) -> i32 {
19177    syscall_ret(<Arch as Syscalls>::syscall2(sysno(36, 102), which as i64, curr_value as i64)) as i32
19178}
19179
19180#[no_mangle]
19181pub unsafe extern "C" fn setitimer(which: i32, new_value: *const core::ffi::c_void, old_value: *mut core::ffi::c_void) -> i32 {
19182    syscall_ret(<Arch as Syscalls>::syscall3(sysno(38, 103), which as i64, new_value as i64, old_value as i64)) as i32
19183}
19184
19185// ============================================================
19186// System info functions
19187// ============================================================
19188
19189#[no_mangle]
19190pub unsafe extern "C" fn getloadavg(loadavg: *mut f64, nelem: i32) -> i32 {
19191    let fd = crate::open(b"/proc/loadavg\0".as_ptr() as *const core::ffi::c_char, 0, 0);
19192    if fd < 0 { return -1; }
19193    let mut buf: [u8; 64] = [0; 64];
19194    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
19195    crate::close(fd);
19196    if n <= 0 { return -1; }
19197    buf[n as usize] = 0;
19198    let mut i = 0;
19199    while i < nelem as usize && i < 3 {
19200        let val = crate::strtod((buf.as_ptr() as *const core::ffi::c_char).add(i * 5), core::ptr::null_mut());
19201        *loadavg.add(i) = val;
19202        i += 1;
19203    }
19204    i as i32
19205}
19206
19207#[no_mangle]
19208pub unsafe extern "C" fn get_nprocs() -> i32 {
19209    sysconf(84) as i32 // _SC_NPROCESSORS_ONLN
19210}
19211
19212#[no_mangle]
19213pub unsafe extern "C" fn get_nprocs_conf() -> i32 {
19214    sysconf(83) as i32 // _SC_NPROCESSORS_CONF
19215}
19216
19217#[no_mangle]
19218pub unsafe extern "C" fn get_avphys_pages() -> i64 {
19219    sysconf(86) // _SC_AVPHYS_PAGES
19220}
19221
19222#[no_mangle]
19223pub unsafe extern "C" fn get_phys_pages() -> i64 {
19224    sysconf(85) // _SC_PHYS_PAGES
19225}
19226
19227// ============================================================
19228// Capability functions
19229// ============================================================
19230
19231#[no_mangle]
19232pub unsafe extern "C" fn capget(header: *mut core::ffi::c_void, data: *mut core::ffi::c_void) -> i32 {
19233    syscall_ret(<Arch as Syscalls>::syscall2(SYS_CAPGET, header as i64, data as i64)) as i32
19234}
19235
19236#[no_mangle]
19237pub unsafe extern "C" fn capset(header: *const core::ffi::c_void, data: *const core::ffi::c_void) -> i32 {
19238    syscall_ret(<Arch as Syscalls>::syscall2(SYS_CAPSET, header as i64, data as i64)) as i32
19239}
19240
19241#[no_mangle]
19242pub unsafe extern "C" fn arch_prctl(code: i32, addr: u64) -> i32 {
19243    if cfg!(target_arch = "x86_64") { syscall_ret(<Arch as Syscalls>::syscall2(158, code as i64, addr as i64)) as i32 } else { ERRNO!() = 38; -1 }
19244}
19245
19246// ============================================================
19247// termios functions
19248// ============================================================
19249
19250#[no_mangle]
19251pub unsafe extern "C" fn cfgetospeed(termios_p: *const core::ffi::c_void) -> u32 {
19252    unsafe { *(termios_p as *const u32).add(1) }
19253}
19254
19255#[no_mangle]
19256pub unsafe extern "C" fn cfgetispeed(termios_p: *const core::ffi::c_void) -> u32 {
19257    unsafe { *(termios_p as *const u32).add(2) }
19258}
19259
19260#[no_mangle]
19261pub unsafe extern "C" fn cfsetospeed(termios_p: *mut core::ffi::c_void, speed: u32) -> i32 {
19262    unsafe { *(termios_p as *mut u32).add(1) = speed; }
19263    0
19264}
19265
19266#[no_mangle]
19267pub unsafe extern "C" fn cfsetispeed(termios_p: *mut core::ffi::c_void, speed: u32) -> i32 {
19268    unsafe { *(termios_p as *mut u32).add(2) = speed; }
19269    0
19270}
19271
19272#[no_mangle]
19273pub unsafe extern "C" fn cfmakeraw(termios_p: *mut core::ffi::c_void) {
19274    unsafe {
19275        let p = termios_p as *mut u32;
19276        *p.add(0) &= !0o37;
19277        *p.add(0) &= !(0o4000 | 0o2000 | 0o10000 | 0o20);
19278        *p.add(0) |= 0o60;
19279        *p.add(3) &= !0o17;
19280        *p.add(3) &= !(0o1000 | 0o40000000);
19281        *p.add(1) = 1;
19282        *p.add(2) = 0;
19283    }
19284}
19285
19286// ============================================================
19287// Resource functions
19288// ============================================================
19289
19290#[no_mangle]
19291pub unsafe extern "C" fn getrusage(who: i32, usage: *mut core::ffi::c_void) -> i32 {
19292    syscall_ret(<Arch as Syscalls>::syscall2(sysno(98, 165), who as i64, usage as i64)) as i32
19293}
19294
19295#[no_mangle]
19296pub unsafe extern "C" fn getpriority(which: i32, who: u32) -> i32 {
19297    // The kernel encodes nice as 20 - nice; musl converts it back.
19298    let r = <Arch as Syscalls>::syscall2(SYS_GETPRIORITY, which as i64, who as i64);
19299    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
19300    20 - r as i32
19301}
19302
19303#[no_mangle]
19304pub unsafe extern "C" fn setpriority(which: i32, who: u32, prio: i32) -> i32 {
19305    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETPRIORITY, which as i64, who as i64, prio as i64)) as i32
19306}
19307
19308#[no_mangle]
19309pub unsafe extern "C" fn prlimit(pid: u32, resource: i32, new_limit: *const core::ffi::c_void, old_limit: *mut core::ffi::c_void) -> i32 {
19310    syscall_ret(<Arch as Syscalls>::syscall4(sysno(302, 261), pid as i64, resource as i64, new_limit as i64, old_limit as i64)) as i32
19311}
19312
19313// ============================================================
19314// fork/clone functions
19315// ============================================================
19316
19317#[no_mangle]
19318pub unsafe extern "C" fn clone(
19319    func: usize,
19320    stack: *mut u8,
19321    flags: c_int,
19322    arg: *mut c_void,
19323    mut args: ...
19324) -> c_int {
19325    // musl-compatible signature: clone(fn, stack, flags, arg, ptid, tls, ctid).
19326    const CLONE_PIDFD_C: c_int = 0x00001000;
19327    const CLONE_VM_C: c_int = 0x00000100;
19328    const CLONE_THREAD_C: c_int = 0x00010000;
19329    const CLONE_SETTLS_C: c_int = 0x00080000;
19330    const CLONE_PARENT_SETTID_C: c_int = 0x00100000;
19331    const CLONE_CHILD_SETTID_C: c_int = 0x01000000;
19332    const CLONE_CHILD_CLEARTID_C: c_int = 0x00200000;
19333    let _ = CLONE_VM_C;
19334    if flags & (CLONE_THREAD_C | CLONE_SETTLS_C | CLONE_CHILD_CLEARTID_C) != 0
19335        || stack.is_null()
19336    {
19337        ERRNO!() = EINVAL;
19338        return -1;
19339    }
19340    let mut ptid: *mut c_int = core::ptr::null_mut();
19341    let mut tls: c_ulong = 0;
19342    let mut ctid: *mut c_int = core::ptr::null_mut();
19343    if flags & (CLONE_PIDFD_C | CLONE_PARENT_SETTID_C | CLONE_CHILD_SETTID_C) != 0 {
19344        ptid = args.next_arg::<*mut c_int>();
19345    }
19346    if flags & CLONE_CHILD_SETTID_C != 0 {
19347        tls = args.next_arg::<c_ulong>();
19348        ctid = args.next_arg::<*mut c_int>();
19349    }
19350    let r = __keel_clone(func, stack, flags as c_ulong, arg, ptid, tls, ctid);
19351    if r < 0 {
19352        ERRNO!() = (-r) as c_int;
19353        -1
19354    } else {
19355        r as c_int
19356    }
19357}
19358
19359#[no_mangle]
19360pub unsafe extern "C" fn _Fork() -> i32 {
19361    crate::fork()
19362}
19363
19364#[no_mangle]
19365pub unsafe extern "C" fn forkpty(amaster: *mut i32, name: *mut core::ffi::c_char, termp: *const core::ffi::c_void, winp: *const core::ffi::c_void) -> i32 {
19366    let mut master: i32 = 0;
19367    let mut slave: i32 = 0;
19368    if openpty(&mut master, &mut slave, name, termp, winp) < 0 { return -1; }
19369    let pid = crate::fork();
19370    if pid < 0 { crate::close(master); crate::close(slave); return -1; }
19371    if pid == 0 {
19372        crate::close(master);
19373        crate::setsid();
19374        crate::dup2(slave, 0);
19375        crate::dup2(slave, 1);
19376        crate::dup2(slave, 2);
19377    } else {
19378        crate::close(slave);
19379        if !amaster.is_null() { *amaster = master; }
19380    }
19381    pid
19382}
19383
19384#[no_mangle]
19385pub unsafe extern "C" fn openpty(amaster: *mut i32, aslave: *mut i32, name: *mut core::ffi::c_char, _termp: *const core::ffi::c_void, _winp: *const core::ffi::c_void) -> i32 {
19386    let master = crate::open(b"/dev/ptmx\0".as_ptr() as *const core::ffi::c_char, 0o2000, 0);
19387    if master < 0 { return -1; }
19388    grantpt(master);
19389    unlockpt(master);
19390    let slave_name = ptsname(master);
19391    if slave_name.is_null() { crate::close(master); return -1; }
19392    let slave = crate::open(slave_name, 0o2000, 0);
19393    if slave < 0 { crate::close(master); return -1; }
19394    if !amaster.is_null() { *amaster = master; }
19395    if !aslave.is_null() { *aslave = slave; }
19396    if !name.is_null() { crate::strcpy(name as *mut u8, slave_name as *const u8); }
19397    0
19398}
19399
19400#[no_mangle]
19401pub unsafe extern "C" fn login_tty(fd: i32) -> i32 {
19402    crate::setsid();
19403    crate::dup2(fd, 0);
19404    crate::dup2(fd, 1);
19405    crate::dup2(fd, 2);
19406    0
19407}
19408
19409// ============================================================
19410// dl functions
19411// ============================================================
19412
19413#[no_mangle]
19414pub unsafe extern "C" fn __dls2b() {}
19415#[no_mangle]
19416pub unsafe extern "C" fn __dls3() {}
19417#[no_mangle]
19418pub unsafe extern "C" fn _dlstart() {}
19419
19420// ============================================================
19421// string functions
19422// ============================================================
19423
19424#[no_mangle]
19425pub unsafe extern "C" fn index(s: *const core::ffi::c_char, c: i32) -> *mut core::ffi::c_char {
19426    let mut i = 0;
19427    loop {
19428        let ch = *s.add(i);
19429        if ch == c as core::ffi::c_char { return s.add(i) as *mut core::ffi::c_char; }
19430        if ch == 0 { return core::ptr::null_mut(); }
19431        i += 1;
19432    }
19433}
19434
19435#[no_mangle]
19436pub unsafe extern "C" fn rindex(s: *const core::ffi::c_char, c: i32) -> *mut core::ffi::c_char {
19437    let mut last = core::ptr::null_mut();
19438    let mut i = 0;
19439    loop {
19440        let ch = *s.add(i);
19441        if ch == 0 { return last; }
19442        if ch == c as core::ffi::c_char { last = s.add(i) as *mut core::ffi::c_char; }
19443        i += 1;
19444    }
19445}
19446
19447// ============================================================
19448// intmax functions
19449// ============================================================
19450
19451#[no_mangle]
19452pub unsafe extern "C" fn imaxabs(j: i64) -> i64 {
19453    j.abs()
19454}
19455
19456#[no_mangle]
19457pub unsafe extern "C" fn imaxdiv(numer: i64, denom: i64) -> (i64, i64) {
19458    (numer / denom, numer % denom)
19459}
19460
19461// ============================================================
19462// herror functions
19463// ============================================================
19464
19465#[no_mangle]
19466pub static mut h_errno: i32 = 0;
19467
19468#[no_mangle]
19469pub unsafe extern "C" fn __h_errno_location() -> *mut i32 {
19470    &mut h_errno
19471}
19472
19473#[no_mangle]
19474pub unsafe extern "C" fn herror(s: *const core::ffi::c_char) {
19475    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
19476    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
19477    crate::write(2, hstrerror(*__h_errno_location()) as *const core::ffi::c_void, crate::strlen(hstrerror(*__h_errno_location())));
19478    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
19479}
19480
19481#[no_mangle]
19482pub unsafe extern "C" fn hstrerror(_err: i32) -> *const core::ffi::c_char {
19483    b"Unknown error\0".as_ptr() as *const core::ffi::c_char
19484}
19485
19486// ============================================================
19487// gettid function
19488// ============================================================
19489
19490#[no_mangle]
19491pub unsafe extern "C" fn gettid() -> i32 {
19492    syscall_ret(<Arch as Syscalls>::syscall0(SYS_GETTID)) as i32
19493}
19494
19495// ============================================================
19496// ioctl functions
19497// ============================================================
19498
19499#[no_mangle]
19500pub unsafe extern "C" fn ioctl(fd: i32, request: u32, mut args: ...) -> i32 {
19501    let arg = args.next_arg::<i64>();
19502    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg)) as i32
19503}
19504
19505#[no_mangle]
19506pub unsafe extern "C" fn ioperm(from: u64, num: u64, turn_on: i32) -> i32 {
19507    #[cfg(target_arch = "x86_64")]
19508    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOPERM, from as i64, num as i64, turn_on as i64)) as i32 }
19509    #[cfg(not(target_arch = "x86_64"))]
19510    {
19511        let _ = (from, num, turn_on);
19512        ERRNO!() = ENOSYS_VAL;
19513        -1
19514    }
19515}
19516
19517#[no_mangle]
19518pub unsafe extern "C" fn iopl(level: i32) -> i32 {
19519    #[cfg(target_arch = "x86_64")]
19520    { syscall_ret(<Arch as Syscalls>::syscall1(SYS_IOPL, level as i64)) as i32 }
19521    #[cfg(not(target_arch = "x86_64"))]
19522    {
19523        let _ = level;
19524        ERRNO!() = ENOSYS_VAL;
19525        -1
19526    }
19527}
19528
19529// ============================================================
19530// xattr functions
19531// ============================================================
19532
19533#[no_mangle]
19534pub unsafe extern "C" fn getxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
19535    syscall_ret(<Arch as Syscalls>::syscall4(sysno(191, 8), path as i64, name as i64, value as i64, size as i64)) as isize
19536}
19537
19538#[no_mangle]
19539pub unsafe extern "C" fn lgetxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
19540    syscall_ret(<Arch as Syscalls>::syscall4(sysno(192, 9), path as i64, name as i64, value as i64, size as i64)) as isize
19541}
19542
19543#[no_mangle]
19544pub unsafe extern "C" fn fgetxattr(fd: i32, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
19545    syscall_ret(<Arch as Syscalls>::syscall4(sysno(193, 10), fd as i64, name as i64, value as i64, size as i64)) as isize
19546}
19547
19548#[no_mangle]
19549pub unsafe extern "C" fn listxattr(path: *const core::ffi::c_char, list: *mut u8, size: usize) -> isize {
19550    syscall_ret(<Arch as Syscalls>::syscall3(sysno(194, 11), path as i64, list as i64, size as i64)) as isize
19551}
19552
19553#[no_mangle]
19554pub unsafe extern "C" fn llistxattr(path: *const core::ffi::c_char, list: *mut u8, size: usize) -> isize {
19555    syscall_ret(<Arch as Syscalls>::syscall3(sysno(195, 12), path as i64, list as i64, size as i64)) as isize
19556}
19557
19558#[no_mangle]
19559pub unsafe extern "C" fn flistxattr(fd: i32, list: *mut u8, size: usize) -> isize {
19560    syscall_ret(<Arch as Syscalls>::syscall3(sysno(196, 13), fd as i64, list as i64, size as i64)) as isize
19561}
19562
19563#[no_mangle]
19564pub unsafe extern "C" fn setxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *const u8, size: usize, flags: i32) -> i32 {
19565    syscall_ret(<Arch as Syscalls>::syscall5(sysno(188, 5), path as i64, name as i64, value as i64, size as i64, flags as i64)) as i32
19566}
19567
19568#[no_mangle]
19569pub unsafe extern "C" fn lsetxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *const u8, size: usize, flags: i32) -> i32 {
19570    syscall_ret(<Arch as Syscalls>::syscall5(sysno(189, 6), path as i64, name as i64, value as i64, size as i64, flags as i64)) as i32
19571}
19572
19573#[no_mangle]
19574pub unsafe extern "C" fn fsetxattr(fd: i32, name: *const core::ffi::c_char, value: *const u8, size: usize, flags: i32) -> i32 {
19575    syscall_ret(<Arch as Syscalls>::syscall5(sysno(190, 7), fd as i64, name as i64, value as i64, size as i64, flags as i64)) as i32
19576}
19577
19578#[no_mangle]
19579pub unsafe extern "C" fn removexattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char) -> i32 {
19580    syscall_ret(<Arch as Syscalls>::syscall2(sysno(197, 14), path as i64, name as i64)) as i32
19581}
19582
19583#[no_mangle]
19584pub unsafe extern "C" fn lremovexattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char) -> i32 {
19585    syscall_ret(<Arch as Syscalls>::syscall2(sysno(198, 15), path as i64, name as i64)) as i32
19586}
19587
19588#[no_mangle]
19589pub unsafe extern "C" fn fremovexattr(fd: i32, name: *const core::ffi::c_char) -> i32 {
19590    syscall_ret(<Arch as Syscalls>::syscall2(sysno(199, 16), fd as i64, name as i64)) as i32
19591}
19592
19593// ============================================================
19594// adjtime functions
19595// ============================================================
19596
19597#[no_mangle]
19598pub unsafe extern "C" fn adjtime(_delta: *const core::ffi::c_void, olddelta: *mut core::ffi::c_void) -> i32 {
19599    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ADJTIMEX, olddelta as i64)) as i32
19600}
19601
19602#[no_mangle]
19603pub unsafe extern "C" fn adjtimex(buf: *mut core::ffi::c_void) -> i32 {
19604    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ADJTIMEX, buf as i64)) as i32
19605}
19606
19607// ============================================================
19608// pty functions
19609// ============================================================
19610
19611// Linux devpts ioctls (asm-generic/ioctls.h): TIOCGPTN = _IOR('T', 0x30, int),
19612// TIOCSPTLCK = _IOW('T', 0x31, int). The old 0x541x values are the window-size
19613// and process-group requests, which both return the wrong data and write more
19614// bytes than the int the caller supplied.
19615const TIOCGPTN: i64 = 0x80045430;
19616const TIOCSPTLCK: i64 = 0x40045431;
19617
19618#[no_mangle]
19619pub unsafe extern "C" fn grantpt(_fd: i32) -> i32 {
19620    // devpts creates the slave already owned by the caller.
19621    0
19622}
19623
19624#[no_mangle]
19625pub unsafe extern "C" fn unlockpt(fd: i32) -> i32 {
19626    let mut unlock: i32 = 0;
19627    let r = <Arch as Syscalls>::syscall3(
19628        SYS_IOCTL,
19629        fd as i64,
19630        TIOCSPTLCK,
19631        &mut unlock as *mut i32 as i64,
19632    );
19633    if r < 0 { -1 } else { 0 }
19634}
19635
19636#[no_mangle]
19637pub unsafe extern "C" fn ptsname(fd: i32) -> *mut core::ffi::c_char {
19638    static mut BUF: [core::ffi::c_char; 32] = [0; 32];
19639    let mut pty_nr: i32 = 0;
19640    if <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, TIOCGPTN, &mut pty_nr as *mut i32 as i64) < 0 {
19641        return core::ptr::null_mut();
19642    }
19643    // Format /dev/pts/N
19644    BUF[0] = '/' as c_char; BUF[1] = 'd' as c_char; BUF[2] = 'e' as c_char; BUF[3] = 'v' as c_char;
19645    BUF[4] = '/' as c_char; BUF[5] = 'p' as c_char; BUF[6] = 't' as c_char; BUF[7] = 's' as c_char;
19646    BUF[8] = '/' as c_char;
19647    let mut n = pty_nr as usize;
19648    let mut i = 9;
19649    if n == 0 { BUF[i] = '0' as c_char; i += 1; }
19650    while n > 0 && i < 31 {
19651        BUF[i] = (b'0' + (n % 10) as u8) as c_char;
19652        n /= 10;
19653        i += 1;
19654    }
19655    BUF[i] = 0;
19656    BUF.as_mut_ptr()
19657}
19658
19659// ============================================================
19660// fpclassify functions
19661// ============================================================
19662
19663#[no_mangle]
19664pub unsafe extern "C" fn finite(x: f64) -> i32 {
19665    (!x.is_nan() && !x.is_infinite()) as i32
19666}
19667
19668#[no_mangle]
19669pub unsafe extern "C" fn finitef(x: f32) -> i32 {
19670    (!x.is_nan() && !x.is_infinite()) as i32
19671}
19672
19673#[no_mangle]
19674pub unsafe extern "C" fn __fpclassifyl(x: f64) -> i32 {
19675    __fpclassify(x)
19676}
19677
19678#[no_mangle]
19679pub unsafe extern "C" fn __signbitl(x: f64) -> i32 {
19680    __signbit(x)
19681}
19682
19683// ============================================================
19684// ftw functions
19685// ============================================================
19686
19687// ============================================================
19688// Bessel functions
19689// ============================================================
19690
19691#[no_mangle]
19692pub unsafe extern "C" fn j0(x: f64) -> f64 {
19693    j0_impl(x)
19694}
19695
19696#[no_mangle]
19697pub unsafe extern "C" fn j0f(x: f32) -> f32 {
19698    libm::j0f(x)
19699}
19700
19701#[no_mangle]
19702pub unsafe extern "C" fn j1(x: f64) -> f64 {
19703    libm::j1(x)
19704}
19705
19706#[no_mangle]
19707pub unsafe extern "C" fn j1f(x: f32) -> f32 {
19708    libm::j1f(x)
19709}
19710
19711#[no_mangle]
19712pub unsafe extern "C" fn jn(n: i32, x: f64) -> f64 {
19713    libm::jn(n, x)
19714}
19715
19716#[no_mangle]
19717pub unsafe extern "C" fn jnf(n: i32, x: f32) -> f32 {
19718    libm::jnf(n, x)
19719}
19720
19721#[no_mangle]
19722pub unsafe extern "C" fn y0(x: f64) -> f64 {
19723    y0_impl(x)
19724}
19725
19726#[no_mangle]
19727pub unsafe extern "C" fn y0f(x: f32) -> f32 {
19728    if x.is_nan() { return x; }
19729    if x < 0.0 { return __math_invalidf(x); }
19730    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f32::NEG_INFINITY; }
19731    libm::y0f(x)
19732}
19733
19734#[no_mangle]
19735pub unsafe extern "C" fn y1(x: f64) -> f64 {
19736    if x.is_nan() { return x; }
19737    if x < 0.0 { return __math_invalid(x); }
19738    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f64::NEG_INFINITY; }
19739    libm::y1(x)
19740}
19741
19742#[no_mangle]
19743pub unsafe extern "C" fn y1f(x: f32) -> f32 {
19744    if x.is_nan() { return x; }
19745    if x < 0.0 { return __math_invalidf(x); }
19746    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f32::NEG_INFINITY; }
19747    libm::y1f(x)
19748}
19749
19750#[no_mangle]
19751pub unsafe extern "C" fn yn(n: i32, x: f64) -> f64 {
19752    if x.is_nan() { return x; }
19753    if x < 0.0 { return __math_invalid(x); }
19754    if x == 0.0 {
19755        feraiseexcept(FE_DIVBYZERO);
19756        if n >= 0 { return f64::NEG_INFINITY; }
19757    }
19758    libm::yn(n, x)
19759}
19760
19761#[no_mangle]
19762pub unsafe extern "C" fn ynf(n: i32, x: f32) -> f32 {
19763    if x.is_nan() { return x; }
19764    if x < 0.0 { return __math_invalidf(x); }
19765    if x == 0.0 {
19766        feraiseexcept(FE_DIVBYZERO);
19767        if n >= 0 { return f32::NEG_INFINITY; }
19768    }
19769    libm::ynf(n, x)
19770}
19771
19772// ============================================================
19773// ctype locale functions
19774// ============================================================
19775
19776#[no_mangle]
19777pub unsafe extern "C" fn __ctype_b_loc() -> *mut *const u16 {
19778    static mut TABLE: *const u16 = core::ptr::null();
19779    &mut TABLE
19780}
19781
19782#[no_mangle]
19783pub unsafe extern "C" fn __ctype_tolower_loc() -> *mut *const i32 {
19784    static mut TABLE: *const i32 = core::ptr::null();
19785    &mut TABLE
19786}
19787
19788#[no_mangle]
19789pub unsafe extern "C" fn __ctype_toupper_loc() -> *mut *const i32 {
19790    static mut TABLE: *const i32 = core::ptr::null();
19791    &mut TABLE
19792}
19793
19794#[no_mangle]
19795pub unsafe extern "C" fn __isalnum_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19796    (c >= '0' as i32 && c <= '9' as i32 || c >= 'A' as i32 && c <= 'Z' as i32 || c >= 'a' as i32 && c <= 'z' as i32) as i32
19797}
19798
19799#[no_mangle]
19800pub unsafe extern "C" fn __isalpha_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19801    (c >= 'A' as i32 && c <= 'Z' as i32 || c >= 'a' as i32 && c <= 'z' as i32) as i32
19802}
19803
19804#[no_mangle]
19805pub unsafe extern "C" fn __isblank_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19806    (c == ' ' as i32 || c == '\t' as i32) as i32
19807}
19808
19809#[no_mangle]
19810pub unsafe extern "C" fn __iscntrl_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19811    (c < 0x20 || c == 0x7f) as i32
19812}
19813
19814#[no_mangle]
19815pub unsafe extern "C" fn __isdigit_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19816    (c >= '0' as i32 && c <= '9' as i32) as i32
19817}
19818
19819#[no_mangle]
19820pub unsafe extern "C" fn __isgraph_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19821    (c > 0x20 && c < 0x7f) as i32
19822}
19823
19824#[no_mangle]
19825pub unsafe extern "C" fn __islower_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19826    (c >= 'a' as i32 && c <= 'z' as i32) as i32
19827}
19828
19829#[no_mangle]
19830pub unsafe extern "C" fn __isprint_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19831    (c >= 0x20 && c < 0x7f) as i32
19832}
19833
19834#[no_mangle]
19835pub unsafe extern "C" fn __ispunct_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19836    (c >= 0x21 && c <= 0x2f || c >= 0x3a && c <= 0x40 || c >= 0x5b && c <= 0x60 || c >= 0x7b && c <= 0x7e) as i32
19837}
19838
19839#[no_mangle]
19840pub unsafe extern "C" fn __isspace_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19841    (c == ' ' as i32 || c >= 0x09 && c <= 0x0d) as i32
19842}
19843
19844#[no_mangle]
19845pub unsafe extern "C" fn __isupper_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19846    (c >= 'A' as i32 && c <= 'Z' as i32) as i32
19847}
19848
19849#[no_mangle]
19850pub unsafe extern "C" fn __isxdigit_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19851    (c >= '0' as i32 && c <= '9' as i32 || c >= 'A' as i32 && c <= 'F' as i32 || c >= 'a' as i32 && c <= 'f' as i32) as i32
19852}
19853
19854// ============================================================
19855// wide char locale functions
19856// ============================================================
19857
19858#[no_mangle]
19859pub unsafe extern "C" fn __iswalnum_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19860    (c >= '0' as u32 && c <= '9' as u32 || c >= 'A' as u32 && c <= 'Z' as u32 || c >= 'a' as u32 && c <= 'z' as u32) as i32
19861}
19862
19863#[no_mangle]
19864pub unsafe extern "C" fn __iswalpha_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19865    (c >= 'A' as u32 && c <= 'Z' as u32 || c >= 'a' as u32 && c <= 'z' as u32) as i32
19866}
19867
19868#[no_mangle]
19869pub unsafe extern "C" fn __iswblank_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19870    (c == ' ' as u32 || c == '\t' as u32) as i32
19871}
19872
19873#[no_mangle]
19874pub unsafe extern "C" fn __iswcntrl_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19875    (c < 0x20 || c == 0x7f) as i32
19876}
19877
19878#[no_mangle]
19879pub unsafe extern "C" fn __iswdigit_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19880    (c >= '0' as u32 && c <= '9' as u32) as i32
19881}
19882
19883#[no_mangle]
19884pub unsafe extern "C" fn __iswgraph_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19885    (c > 0x20 && c < 0x7f) as i32
19886}
19887
19888#[no_mangle]
19889pub unsafe extern "C" fn __iswlower_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19890    (c >= 'a' as u32 && c <= 'z' as u32) as i32
19891}
19892
19893#[no_mangle]
19894pub unsafe extern "C" fn __iswprint_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19895    (c >= 0x20 && c < 0x7f) as i32
19896}
19897
19898#[no_mangle]
19899pub unsafe extern "C" fn __iswpunct_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19900    (c >= 0x21 && c <= 0x2f || c >= 0x3a && c <= 0x40 || c >= 0x5b && c <= 0x60 || c >= 0x7b && c <= 0x7e) as i32
19901}
19902
19903#[no_mangle]
19904pub unsafe extern "C" fn __iswspace_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19905    (c == ' ' as u32 || c >= 0x09 && c <= 0x0d) as i32
19906}
19907
19908#[no_mangle]
19909pub unsafe extern "C" fn __iswupper_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19910    (c >= 'A' as u32 && c <= 'Z' as u32) as i32
19911}
19912
19913#[no_mangle]
19914pub unsafe extern "C" fn __iswxdigit_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19915    (c >= '0' as u32 && c <= '9' as u32 || c >= 'A' as u32 && c <= 'F' as u32 || c >= 'a' as u32 && c <= 'f' as u32) as i32
19916}
19917
19918#[no_mangle]
19919pub unsafe extern "C" fn __iswctype_l(c: u32, ctype: u32, _loc: *mut core::ffi::c_void) -> i32 {
19920    crate::iswctype(c as wint_t, ctype as wctype_t)
19921}
19922
19923#[no_mangle]
19924pub unsafe extern "C" fn __towlower_l(c: u32, _loc: *mut core::ffi::c_void) -> u32 {
19925    crate::towlower(c)
19926}
19927
19928#[no_mangle]
19929pub unsafe extern "C" fn __towupper_l(c: u32, _loc: *mut core::ffi::c_void) -> u32 {
19930    crate::towupper(c)
19931}
19932
19933#[no_mangle]
19934pub unsafe extern "C" fn __towctrans_l(c: u32, _trans: u32, _loc: *mut core::ffi::c_void) -> u32 {
19935    c
19936}
19937
19938// ============================================================
19939// _r functions
19940// ============================================================
19941
19942// ============================================================
19943// stdio internal functions
19944// ============================================================
19945
19946// ============================================================
19947// Misc functions
19948// ============================================================
19949
19950#[no_mangle]
19951pub 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) {
19952    crate::write(2, b"Assertion failed: ".as_ptr() as *const core::ffi::c_void, 18);
19953    if !expr.is_null() { crate::write(2, expr as *const core::ffi::c_void, crate::strlen(expr)); }
19954    crate::write(2, b" (".as_ptr() as *const core::ffi::c_void, 2);
19955    if !file.is_null() { crate::write(2, file as *const core::ffi::c_void, crate::strlen(file)); }
19956    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
19957    let mut n = line as usize;
19958    let mut digits: [u8; 32] = [0; 32];
19959    let mut di = 0;
19960    if n == 0 { digits[0] = 0; di = 1; }
19961    while n > 0 && di < 32 { digits[di] = (n % 10) as u8; n /= 10; di += 1; }
19962    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); }
19963    crate::write(2, b")".as_ptr() as *const core::ffi::c_void, 1);
19964    if !func.is_null() { crate::write(2, func as *const core::ffi::c_void, crate::strlen(func)); }
19965    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
19966    crate::abort()
19967}
19968
19969#[no_mangle]
19970pub unsafe extern "C" fn at_quick_exit(_func: Option<unsafe extern "C" fn()>) -> i32 {
19971    // Register for quick exit - simplified
19972    0
19973}
19974
19975#[no_mangle]
19976pub unsafe extern "C" fn brk(addr: *mut u8) -> i32 {
19977    syscall_ret(<Arch as Syscalls>::syscall1(sysno(12, 214), addr as i64)) as i32
19978}
19979
19980#[no_mangle]
19981pub 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 {
19982    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
19983}
19984
19985#[no_mangle]
19986pub unsafe extern "C" fn ctermid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
19987    static mut BUF: [core::ffi::c_char; 20] = [0; 20];
19988    let dst = if s.is_null() { BUF.as_mut_ptr() } else { s };
19989    let src = b"/dev/tty\0".as_ptr() as *const core::ffi::c_char;
19990    let mut i = 0;
19991    while i < 9 { *dst.add(i) = *src.add(i); i += 1; }
19992    dst
19993}
19994
19995#[no_mangle]
19996pub unsafe extern "C" fn delete_module(name: *const core::ffi::c_char, flags: u32) -> i32 {
19997    syscall_ret(<Arch as Syscalls>::syscall2(SYS_DELETE_MODULE, name as i64, flags as i64)) as i32
19998}
19999
20000
20001
20002
20003
20004#[no_mangle]
20005pub unsafe extern "C" fn __duplocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
20006    loc
20007}
20008
20009#[no_mangle]
20010pub unsafe extern "C" fn euidaccess(pathname: *const core::ffi::c_char, mode: i32) -> i32 {
20011    faccessat(AT_FDCWD, pathname, mode, 0x200)
20012}
20013
20014#[no_mangle]
20015pub unsafe extern "C" fn fgetln(f: *mut core::ffi::c_void, lenp: *mut usize) -> *mut core::ffi::c_char {
20016    static mut BUF: *mut core::ffi::c_char = core::ptr::null_mut();
20017    static mut CAP: usize = 0;
20018    let n = getline(&raw mut BUF, &raw mut CAP, f as *mut FILE);
20019    if n <= 0 {
20020        if !lenp.is_null() { *lenp = 0; }
20021        return core::ptr::null_mut();
20022    }
20023    if !lenp.is_null() { *lenp = n as usize; }
20024    BUF
20025}
20026
20027#[no_mangle]
20028pub unsafe extern "C" fn fgetws(ws: *mut u32, n: i32, f: *mut core::ffi::c_void) -> *mut u32 {
20029    let mut i = 0;
20030    while i < n - 1 {
20031        let c = getwc(f as *mut core::ffi::c_void);
20032        if c == 0 { break; }
20033        *ws.add(i as usize) = c;
20034        i += 1;
20035        if c == '\n' as u32 { break; }
20036    }
20037    *ws.add(i as usize) = 0;
20038    if i == 0 { core::ptr::null_mut() } else { ws }
20039}
20040
20041#[no_mangle]
20042pub 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 {
20043    if !label.is_null() { crate::write(2, label as *const core::ffi::c_void, crate::strlen(label)); }
20044    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20045    if !text.is_null() { crate::write(2, text as *const core::ffi::c_void, crate::strlen(text)); }
20046    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20047    0
20048}
20049
20050#[no_mangle]
20051pub unsafe extern "C" fn ftime(tp: *mut core::ffi::c_void) -> i32 {
20052    let mut tv: timeval = core::mem::zeroed();
20053    if gettimeofday(&mut tv, core::ptr::null_mut()) == 0 {
20054        let tb = tp as *mut Timeb;
20055        (*tb).time = tv.tv_sec;
20056        (*tb).millitm = (tv.tv_usec / 1000) as u16;
20057        (*tb).timezone = 0;
20058        (*tb).dstflag = 0;
20059        0
20060    } else {
20061        -1
20062    }
20063}
20064
20065#[no_mangle]
20066pub unsafe extern "C" fn getdents(fd: i32, dirp: *mut u8, count: usize) -> isize {
20067    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, dirp as i64, count as i64)) as isize
20068}
20069
20070#[no_mangle]
20071pub unsafe extern "C" fn gethostid() -> i64 {
20072    // Read from /proc/sys/kernel/random/boot_id or similar
20073    let fd = crate::open(b"/proc/sys/kernel/random/boot_id\0".as_ptr() as *const core::ffi::c_char, 0, 0);
20074    if fd < 0 { return 0; }
20075    let mut buf: [u8; 64] = [0; 64];
20076    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
20077    crate::close(fd);
20078    if n <= 0 { return 0; }
20079    buf[n as usize] = 0;
20080    crate::strtol(buf.as_ptr() as *const core::ffi::c_char, core::ptr::null_mut(), 16)
20081}
20082
20083#[no_mangle]
20084pub unsafe extern "C" fn getpass(prompt: *const core::ffi::c_char) -> *mut core::ffi::c_char {
20085    static mut BUF: [core::ffi::c_char; 256] = [0; 256];
20086    // Write prompt
20087    crate::write(2, prompt as *const core::ffi::c_void, crate::strlen(prompt));
20088    // Read password (simplified - no echo disable)
20089    let n = crate::read(0, BUF.as_mut_ptr() as *mut core::ffi::c_void, 255);
20090    if n > 0 {
20091        let end = if BUF[(n - 1) as usize] == '\n' as c_char { n - 1 } else { n };
20092        BUF[end as usize] = 0;
20093    } else {
20094        BUF[0] = 0;
20095    }
20096    BUF.as_mut_ptr()
20097}
20098
20099#[no_mangle]
20100pub 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 {
20101    let s = *optionp;
20102    if s.is_null() { return -1; }
20103    // Find end of suboption
20104    let mut end = s;
20105    while *end != 0 && *end != ',' as c_char && *end != '=' as c_char { end = end.add(1); }
20106    let eq = *end == '=' as c_char;
20107    if eq { *end = 0; *valuep = end.add(1); }
20108    // Find matching token
20109    let mut i = 0;
20110    loop {
20111        let tok = *tokens.add(i);
20112        if tok.is_null() { break; }
20113        if crate::strcmp(s as *const u8, tok as *const u8) == 0 {
20114            // Skip to next option
20115    while *end != 0 && *end != ',' as c_char { end = end.add(1); }
20116            if *end == ',' as c_char { end = end.add(1); }
20117            *optionp = end;
20118            return i as i32;
20119        }
20120        i += 1;
20121    }
20122    -1
20123}
20124
20125#[no_mangle]
20126pub unsafe extern "C" fn getw(f: *mut core::ffi::c_void) -> i32 {
20127    let c0 = getc(f as *mut FILE);
20128    if c0 < 0 { return -1; }
20129    let c1 = getc(f as *mut FILE);
20130    if c1 < 0 { return -1; }
20131    let c2 = getc(f as *mut FILE);
20132    if c2 < 0 { return -1; }
20133    let c3 = getc(f as *mut FILE);
20134    if c3 < 0 { return -1; }
20135    (c0 | (c1 << 8) | (c2 << 16) | (c3 << 24)) as i32
20136}
20137
20138#[no_mangle]
20139pub unsafe extern "C" fn getwc(f: *mut core::ffi::c_void) -> u32 {
20140    getc(f as *mut FILE) as u32
20141}
20142
20143#[no_mangle]
20144pub unsafe extern "C" fn init_module(module_image: *mut u8, len: usize, param_values: *const core::ffi::c_char) -> i32 {
20145    syscall_ret(<Arch as Syscalls>::syscall3(SYS_INIT_MODULE, module_image as i64, len as i64, param_values as i64)) as i32
20146}
20147
20148
20149
20150#[no_mangle]
20151pub unsafe extern "C" fn issetugid() -> i32 {
20152    let ruid = crate::getuid();
20153    let euid = crate::geteuid();
20154    let rgid = crate::getgid();
20155    let egid = crate::getegid();
20156    (ruid != euid || rgid != egid) as i32
20157}
20158
20159// ============================================================
20160// poll functions
20161// ============================================================
20162
20163#[repr(C)]
20164struct PollTimespec {
20165    tv_sec: i64,
20166    tv_nsec: i64,
20167}
20168
20169#[no_mangle]
20170pub unsafe extern "C" fn poll(fds: *mut core::ffi::c_void, nfds: u32, timeout: i32) -> i32 {
20171    #[cfg(target_arch = "x86_64")]
20172    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_POLL, fds as i64, nfds as i64, timeout as i64)) as i32 }
20173    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
20174    {
20175        // poll(2) does not exist on these architectures.  ppoll(2) takes a
20176        // struct timespec, not a millisecond count; passing the integer
20177        // directly made poll(..., 0) wait forever.
20178        let mut ts = PollTimespec { tv_sec: 0, tv_nsec: 0 };
20179        let ts_ptr = if timeout < 0 {
20180            core::ptr::null()
20181        } else {
20182            ts.tv_sec = (timeout / 1000) as i64;
20183            ts.tv_nsec = ((timeout % 1000) as i64) * 1_000_000;
20184            &ts as *const PollTimespec as *const core::ffi::c_void
20185        };
20186        syscall_ret(<Arch as Syscalls>::syscall5(
20187            SYS_PPOLL,
20188            fds as i64,
20189            nfds as i64,
20190            ts_ptr as i64,
20191            0,
20192            8,
20193        )) as i32
20194    }
20195}
20196
20197#[no_mangle]
20198pub unsafe extern "C" fn ppoll(fds: *mut core::ffi::c_void, nfds: u32, timeout: *const core::ffi::c_void, sigmask: *const u64) -> i32 {
20199    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PPOLL, fds as i64, nfds as i64, timeout as i64, sigmask as i64, 8)) as i32
20200}
20201
20202#[repr(C)]
20203struct PselectSigmask {
20204    ss: *const u64,
20205    ss_len: usize,
20206}
20207
20208#[no_mangle]
20209pub 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 {
20210    // pselect6 takes a { sigset_t *, size_t } pair, not the sigset pointer.
20211    // GNU make blocks SIGCHLD and depends on this temporary mask, so passing
20212    // the pointer directly deadlocks parallel builds.
20213    let arg = PselectSigmask {
20214        ss: sigmask,
20215        ss_len: core::mem::size_of::<SigSetT>(),
20216    };
20217    let arg_ptr = if sigmask.is_null() {
20218        0
20219    } else {
20220        &arg as *const PselectSigmask as i64
20221    };
20222    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
20223}
20224
20225// ============================================================
20226// realpath function
20227// ============================================================
20228
20229// ============================================================
20230// quick_exit function
20231// ============================================================
20232
20233#[no_mangle]
20234pub unsafe extern "C" fn quick_exit(status: i32) -> ! {
20235    crate::_exit(status)
20236}
20237
20238// ============================================================
20239// stat functions
20240// ============================================================
20241
20242#[no_mangle]
20243pub unsafe extern "C" fn lstat(path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
20244    let r = <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, buf as i64, 0x100);
20245    if r < 0 {
20246        ERRNO!() = (-r) as c_int;
20247        -1
20248    } else {
20249        0
20250    }
20251}
20252
20253#[no_mangle]
20254pub unsafe extern "C" fn __xstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
20255    crate::stat(path, buf as *mut Stat)
20256}
20257
20258#[no_mangle]
20259pub unsafe extern "C" fn __lxstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
20260    crate::lstat(path, buf)
20261}
20262
20263#[no_mangle]
20264pub unsafe extern "C" fn __fxstat(_ver: i32, fd: i32, buf: *mut core::ffi::c_void) -> i32 {
20265    crate::fstat(fd, buf as *mut Stat)
20266}
20267
20268#[no_mangle]
20269pub unsafe extern "C" fn __fxstatat(_ver: i32, _dirfd: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void, _flags: i32) -> i32 {
20270    crate::stat(path, buf as *mut Stat)
20271}
20272
20273// ============================================================
20274// mempcpy function
20275// ============================================================
20276
20277#[no_mangle]
20278pub unsafe extern "C" fn mempcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8 {
20279    core::ptr::copy_nonoverlapping(src, dest, n);
20280    dest.add(n)
20281}
20282
20283// ============================================================
20284// mktemp functions
20285// ============================================================
20286
20287#[no_mangle]
20288pub unsafe extern "C" fn mkostemp(template: *mut core::ffi::c_char, _flags: i32) -> i32 {
20289    mkstemp(template)
20290}
20291
20292#[no_mangle]
20293pub unsafe extern "C" fn mkstemps(template: *mut core::ffi::c_char, suffixlen: i32) -> i32 {
20294    mkstemps_impl(template, suffixlen)
20295}
20296
20297// ============================================================
20298// system functions
20299// ============================================================
20300
20301#[no_mangle]
20302pub unsafe extern "C" fn ptrace(request: i32, mut args: ...) -> i64 {
20303    let pid = args.next_arg::<c_long>();
20304    let addr = args.next_arg::<c_long>();
20305    let data = args.next_arg::<c_long>();
20306    // PEEKTEXT/PEEKDATA/PEEKUSER write the result through the data pointer
20307    // (the kernel returns EFAULT for a NULL pointer), so supply a local slot.
20308    if (1..=3).contains(&request) {
20309        let mut result: c_long = 0;
20310        let r = <Arch as Syscalls>::syscall4(
20311            sysno(101, 117),
20312            request as i64,
20313            pid,
20314            addr,
20315            &mut result as *mut c_long as i64,
20316        );
20317        if r < 0 {
20318            ERRNO!() = (-r) as c_int;
20319            return -1;
20320        }
20321        return result;
20322    }
20323    syscall_ret(<Arch as Syscalls>::syscall4(sysno(101, 117), request as i64, pid, addr, data))
20324}
20325
20326#[no_mangle]
20327pub unsafe extern "C" fn personality(persona: u64) -> i64 {
20328    <Arch as Syscalls>::syscall1(sysno(135, 92), persona as i64)
20329}
20330
20331#[no_mangle]
20332pub unsafe extern "C" fn reboot(cmd: c_int) -> i32 {
20333    // musl's public API is reboot(cmd), not the four-argument syscall.
20334    syscall_ret(<Arch as Syscalls>::syscall3(
20335        SYS_REBOOT,
20336        0xfee1dead,
20337        672274793,
20338        cmd as i64,
20339    )) as i32
20340}
20341
20342#[no_mangle]
20343pub unsafe extern "C" fn pivot_root(new_root: *const core::ffi::c_char, put_old: *const core::ffi::c_char) -> i32 {
20344    syscall_ret(<Arch as Syscalls>::syscall2(SYS_PIVOT_ROOT, new_root as i64, put_old as i64)) as i32
20345}
20346
20347#[no_mangle]
20348pub 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 {
20349    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
20350}
20351
20352#[no_mangle]
20353pub unsafe extern "C" fn umount(target: *const core::ffi::c_char) -> i32 {
20354    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, 0)) as i32
20355}
20356
20357#[no_mangle]
20358pub unsafe extern "C" fn umount2(target: *const core::ffi::c_char, flags: i32) -> i32 {
20359    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, flags as i64)) as i32
20360}
20361
20362// ============================================================
20363// resolver functions
20364// ============================================================
20365
20366
20367// ============================================================
20368// signal/error functions
20369// ============================================================
20370
20371#[no_mangle]
20372pub unsafe extern "C" fn psiginfo(_pinfo: *const core::ffi::c_void, s: *const core::ffi::c_char) {
20373    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
20374    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20375}
20376
20377#[no_mangle]
20378pub unsafe extern "C" fn psignal(sig: i32, s: *const core::ffi::c_char) {
20379    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
20380    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20381    crate::write(2, strsignal(sig) as *const core::ffi::c_void, crate::strlen(strsignal(sig)));
20382    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20383}
20384
20385#[no_mangle]
20386pub unsafe extern "C" fn strsignal(sig: c_int) -> *const c_char {
20387    static NAMES: [&[u8]; 32] = [
20388        b"Unknown signal\0",
20389        b"Hangup\0",
20390        b"Interrupt\0",
20391        b"Quit\0",
20392        b"Illegal instruction\0",
20393        b"Trace/breakpoint trap\0",
20394        b"Aborted\0",
20395        b"Bus error\0",
20396        b"Floating point exception\0",
20397        b"Killed\0",
20398        b"User defined signal 1\0",
20399        b"Segmentation fault\0",
20400        b"User defined signal 2\0",
20401        b"Broken pipe\0",
20402        b"Alarm clock\0",
20403        b"Terminated\0",
20404        b"Stack fault\0",
20405        b"Child process status\0",
20406        b"Continued\0",
20407        b"Stopped (signal)\0",
20408        b"Stopped\0",
20409        b"Stopped (tty input)\0",
20410        b"Stopped (tty output)\0",
20411        b"Urgent I/O condition\0",
20412        b"CPU time limit exceeded\0",
20413        b"File size limit exceeded\0",
20414        b"Virtual timer expired\0",
20415        b"Profiling timer expired\0",
20416        b"Window changed\0",
20417        b"I/O possible\0",
20418        b"Power failure\0",
20419        b"Bad system call\0",
20420    ];
20421    static mut RT_BUF: [c_char; 32] = [0; 32];
20422    if sig > 0 && sig < 32 {
20423        return NAMES[sig as usize].as_ptr() as *const c_char;
20424    }
20425    if sig >= 32 && sig < 65 {
20426        let mut o = 0usize;
20427        for &c in b"Real-time signal \0" {
20428            if c == 0 { break; }
20429            RT_BUF[o] = c as c_char;
20430            o += 1;
20431        }
20432        let mut v = (sig - 32) as u32;
20433        let mut digits = [0u8; 10];
20434        let mut d = 0usize;
20435        if v == 0 { digits[0] = b'0'; d = 1; }
20436        while v > 0 { digits[d] = b'0' + (v % 10) as u8; v /= 10; d += 1; }
20437        while d > 0 { d -= 1; RT_BUF[o] = digits[d] as c_char; o += 1; }
20438        RT_BUF[o] = 0;
20439        return RT_BUF.as_ptr();
20440    }
20441    b"Unknown signal\0".as_ptr() as *const c_char
20442}
20443
20444#[no_mangle]
20445pub unsafe extern "C" fn __strerror_l(errnum: i32, _loc: *mut core::ffi::c_void) -> *const core::ffi::c_char {
20446    crate::strerror(errnum)
20447}
20448
20449// ============================================================
20450// preadv functions
20451// ============================================================
20452
20453#[no_mangle]
20454pub unsafe extern "C" fn preadv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
20455    // preadv takes a 64-bit offset split into pos_l/pos_h on x86_64 and the
20456    // generic ABI; passing only pos_l leaves the high half undefined.
20457    syscall_ret(<Arch as Syscalls>::syscall5(
20458        sysno(295, 69),
20459        fd as i64,
20460        iov as i64,
20461        iovcnt as i64,
20462        offset,
20463        offset >> 32,
20464    )) as isize
20465}
20466
20467#[no_mangle]
20468pub unsafe extern "C" fn pwritev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
20469    syscall_ret(<Arch as Syscalls>::syscall5(
20470        sysno(296, 70),
20471        fd as i64,
20472        iov as i64,
20473        iovcnt as i64,
20474        offset,
20475        offset >> 32,
20476    )) as isize
20477}
20478
20479#[no_mangle]
20480pub unsafe extern "C" fn preadv2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
20481    // x86_64/generic preadv2 split the 64-bit offset into pos_l/pos_h and
20482    // take the flags as the sixth argument.
20483    syscall_ret(<Arch as Syscalls>::syscall6(
20484        sysno(327, 286),
20485        fd as i64,
20486        iov as i64,
20487        iovcnt as i64,
20488        offset,
20489        offset >> 32,
20490        flags as i64,
20491    )) as isize
20492}
20493
20494#[no_mangle]
20495pub unsafe extern "C" fn pwritev2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
20496    syscall_ret(<Arch as Syscalls>::syscall6(
20497        sysno(328, 287),
20498        fd as i64,
20499        iov as i64,
20500        iovcnt as i64,
20501        offset,
20502        offset >> 32,
20503        flags as i64,
20504    )) as isize
20505}
20506
20507// ============================================================
20508// nice function
20509// ============================================================
20510
20511#[no_mangle]
20512pub unsafe extern "C" fn nice(inc: i32) -> i32 {
20513    let mut prio = inc;
20514    if inc > -40 && inc < 40 {
20515        prio += getpriority(0, 0);
20516    }
20517    if prio > 19 { prio = 19; }
20518    if prio < -20 { prio = -20; }
20519    if setpriority(0, 0, prio) != 0 {
20520        if ERRNO!() == 13 { ERRNO!() = 1; } // EACCES -> EPERM, as musl does
20521        return -1;
20522    }
20523    prio
20524}
20525
20526// ============================================================
20527// misc functions
20528// ============================================================
20529
20530#[no_mangle]
20531pub unsafe extern "C" fn l64a(value: i64) -> *mut core::ffi::c_char {
20532    static mut BUF: [core::ffi::c_char; 7] = [0; 7];
20533    let mut v = value as u64;
20534    let mut i = 0;
20535    while v > 0 && i < 6 {
20536        let c = (v & 0x3f) as u8;
20537        BUF[i] = if c < 26 { c + b'A' } else if c < 52 { c - 26 + b'a' } else if c < 62 { c - 52 + b'0' } else if c == 62 { b'.' } else { b'/' } as core::ffi::c_char;
20538        v >>= 6;
20539        i += 1;
20540    }
20541    BUF[i] = 0;
20542    BUF.as_mut_ptr()
20543}
20544
20545#[no_mangle]
20546pub unsafe extern "C" fn lchmod(path: *const core::ffi::c_char, mode: u32) -> i32 {
20547    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FCHMODAT, AT_FDCWD as i64, path as i64, mode as i64, 0x100)) as i32
20548}
20549
20550#[no_mangle]
20551pub unsafe extern "C" fn lutimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
20552    utimensat(AT_FDCWD, filename, times as *const timespec, 0x100)
20553}
20554
20555#[no_mangle]
20556pub unsafe extern "C" fn mknod(pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
20557    #[cfg(target_arch = "x86_64")]
20558    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKNOD, pathname as i64, mode as i64, dev as i64)) as i32 }
20559    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
20560    {
20561        syscall_ret(<Arch as Syscalls>::syscall4(SYS_MKNODAT, AT_FDCWD as i64, pathname as i64, mode as i64, dev as i64)) as i32
20562    }
20563}
20564
20565#[no_mangle]
20566pub unsafe extern "C" fn memfd_create(name: *const core::ffi::c_char, flags: u32) -> i32 {
20567    syscall_ret(<Arch as Syscalls>::syscall2(sysno(319, 279), name as i64, flags as i64)) as i32
20568}
20569
20570#[no_mangle]
20571pub unsafe extern "C" fn mlock2(addr: *const core::ffi::c_void, len: usize, flags: u32) -> i32 {
20572    syscall_ret(<Arch as Syscalls>::syscall3(sysno(325, 284), addr as i64, len as i64, flags as i64)) as i32
20573}
20574
20575
20576
20577#[no_mangle]
20578pub unsafe extern "C" fn remap_file_pages(addr: *mut core::ffi::c_void, size: usize, prot: i32, pgoff: usize, flags: u32) -> i32 {
20579    syscall_ret(<Arch as Syscalls>::syscall5(sysno(216, 234), addr as i64, size as i64, prot as i64, pgoff as i64, flags as i64)) as i32
20580}
20581
20582// ============================================================
20583// nan functions
20584// ============================================================
20585
20586#[no_mangle]
20587pub unsafe extern "C" fn nan(_tagp: *const core::ffi::c_char) -> f64 {
20588    f64::NAN
20589}
20590
20591#[no_mangle]
20592pub unsafe extern "C" fn nanf(_tagp: *const core::ffi::c_char) -> f32 {
20593    f32::NAN
20594}
20595
20596// ============================================================
20597// Remaining symbols - batch 1
20598// ============================================================
20599
20600#[no_mangle]
20601pub unsafe extern "C" fn __lgammal_r(x: f64, signgamp: *mut i32) -> f64 {
20602    *signgamp = 1;
20603    lgamma(x)
20604}
20605
20606#[no_mangle]
20607pub unsafe extern "C" fn __libc_current_sigrtmax() -> i32 {
20608    64
20609}
20610
20611#[no_mangle]
20612pub unsafe extern "C" fn _longjmp(env: *mut core::ffi::c_void, val: i32) {
20613    crate::longjmp(env as *mut u64, val)
20614}
20615
20616#[no_mangle]
20617pub unsafe extern "C" fn __newlocale(_mask: i32, _name: *const core::ffi::c_char, base: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
20618    base
20619}
20620
20621#[no_mangle]
20622pub unsafe extern "C" fn __nl_langinfo(_item: i32) -> *mut core::ffi::c_char {
20623    b"\0".as_ptr() as *mut core::ffi::c_char
20624}
20625
20626#[no_mangle]
20627pub unsafe extern "C" fn __nl_langinfo_l(_item: i32, _loc: *mut core::ffi::c_void) -> *mut core::ffi::c_char {
20628    b"\0".as_ptr() as *mut core::ffi::c_char
20629}
20630
20631#[no_mangle]
20632pub unsafe extern "C" fn ns_get16(cp: *const u8) -> u16 {
20633    ((*cp.add(0) as u16) << 8) | *cp.add(1) as u16
20634}
20635
20636#[no_mangle]
20637pub unsafe extern "C" fn ns_get32(cp: *const u8) -> u32 {
20638    ((*cp.add(0) as u32) << 24) | ((*cp.add(1) as u32) << 16) | ((*cp.add(2) as u32) << 8) | *cp.add(3) as u32
20639}
20640
20641#[no_mangle]
20642pub unsafe extern "C" fn ns_put16(s: u16, dst: *mut u8) {
20643    *dst.add(0) = (s >> 8) as u8;
20644    *dst.add(1) = (s & 0xff) as u8;
20645}
20646
20647#[no_mangle]
20648pub unsafe extern "C" fn ns_put32(l: u32, dst: *mut u8) {
20649    *dst.add(0) = (l >> 24) as u8;
20650    *dst.add(1) = ((l >> 16) & 0xff) as u8;
20651    *dst.add(2) = ((l >> 8) & 0xff) as u8;
20652    *dst.add(3) = (l & 0xff) as u8;
20653}
20654
20655#[no_mangle]
20656pub unsafe extern "C" fn posix_close(fd: i32) -> i32 {
20657    crate::close(fd)
20658}
20659
20660#[no_mangle]
20661pub unsafe extern "C" fn posix_openpt(flags: i32) -> i32 {
20662    crate::open(b"/dev/ptmx\0".as_ptr() as *const core::ffi::c_char, flags, 0)
20663}
20664
20665#[no_mangle]
20666pub unsafe extern "C" fn putw(w: i32, f: *mut core::ffi::c_void) {
20667    putc((w & 0xff) as i32, f as *mut FILE);
20668    putc(((w >> 8) & 0xff) as i32, f as *mut FILE);
20669    putc(((w >> 16) & 0xff) as i32, f as *mut FILE);
20670    putc(((w >> 24) & 0xff) as i32, f as *mut FILE);
20671}
20672
20673
20674
20675#[no_mangle]
20676pub unsafe extern "C" fn rand_r(seedp: *mut u32) -> i32 {
20677    let seed = (*seedp).wrapping_mul(1103515245).wrapping_add(12345);
20678    *seedp = seed;
20679    ((seed >> 16) & 0x7fff) as i32
20680}
20681
20682#[no_mangle]
20683pub unsafe extern "C" fn reallocarray(ptr: *mut core::ffi::c_void, nmemb: usize, size: usize) -> *mut core::ffi::c_void {
20684    let total = match nmemb.checked_mul(size) {
20685        Some(v) => v,
20686        None => { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
20687    };
20688    crate::realloc(ptr, total)
20689}
20690
20691#[no_mangle]
20692pub unsafe extern "C" fn __res_state() -> *mut core::ffi::c_void {
20693    static mut STATE: [u8; 512] = [0; 512];
20694    STATE.as_mut_ptr() as *mut core::ffi::c_void
20695}
20696
20697#[no_mangle]
20698pub unsafe extern "C" fn sbrk(increment: isize) -> *mut u8 {
20699    // musl does not support growing the break directly (malloc uses mmap);
20700    // sbrk(nonzero) always fails with ENOMEM.
20701    if increment != 0 {
20702        ERRNO!() = ENOMEM;
20703        return -1isize as usize as *mut u8;
20704    }
20705    <Arch as Syscalls>::syscall1(sysno(12, 214), 0) as *mut u8
20706}
20707
20708#[no_mangle]
20709pub unsafe extern "C" fn scalb(x: f64, exp: f64) -> f64 {
20710    if x.is_nan() || exp.is_nan() { return x * exp; }
20711    if !exp.is_finite() {
20712        let r = if exp > 0.0 { x * exp } else { x / (-exp) };
20713        if r.is_nan() && !x.is_nan() {
20714            feraiseexcept(FE_INVALID);
20715        }
20716        return r;
20717    }
20718    if libm::rint(exp) != exp {
20719        return __math_invalid(exp);
20720    }
20721    if exp > 65000.0 { return libm::scalbn(x, 65000); }
20722    if -exp > 65000.0 { return libm::scalbn(x, -65000); }
20723    libm::scalbn(x, exp as i32)
20724}
20725
20726#[no_mangle]
20727pub unsafe extern "C" fn scalbf(x: f32, exp: f32) -> f32 {
20728    if x.is_nan() || exp.is_nan() { return x * exp; }
20729    if !exp.is_finite() {
20730        let r = if exp > 0.0 { x * exp } else { x / (-exp) };
20731        if r.is_nan() && !x.is_nan() {
20732            feraiseexcept(FE_INVALID);
20733        }
20734        return r;
20735    }
20736    if libm::rintf(exp) != exp {
20737        return __math_invalidf(exp);
20738    }
20739    if exp > 65000.0 { return libm::scalbnf(x, 65000); }
20740    if -exp > 65000.0 { return libm::scalbnf(x, -65000); }
20741    libm::scalbnf(x, exp as i32)
20742}
20743
20744#[no_mangle]
20745pub unsafe extern "C" fn __sched_cpucount(setsize: usize, setp: *const u8) -> i32 {
20746    let mut count = 0;
20747    let mut i = 0;
20748    while i < setsize * 8 {
20749        if (*setp.add(i / 8) >> (i % 8)) & 1 != 0 { count += 1; }
20750        i += 1;
20751    }
20752    count
20753}
20754
20755
20756
20757#[no_mangle]
20758pub unsafe extern "C" fn select(nfds: i32, readfds: *mut u8, writefds: *mut u8, exceptfds: *mut u8, timeout: *mut core::ffi::c_void) -> i32 {
20759    syscall_ret(<Arch as Syscalls>::syscall6(sysno(23, 72), nfds as i64, readfds as i64, writefds as i64, exceptfds as i64, timeout as i64, 0)) as i32
20760}
20761
20762
20763
20764#[no_mangle]
20765pub unsafe extern "C" fn sendfile(out_fd: i32, in_fd: i32, offset: *mut i64, count: usize) -> isize {
20766    syscall_ret(<Arch as Syscalls>::syscall4(sysno(40, 71), out_fd as i64, in_fd as i64, offset as i64, count as i64)) as isize
20767}
20768
20769
20770
20771
20772
20773#[no_mangle]
20774pub unsafe extern "C" fn __setjmp(env: *mut core::ffi::c_void) -> i32 {
20775    crate::setjmp(env as *mut u64)
20776}
20777
20778#[no_mangle]
20779pub unsafe extern "C" fn _setjmp(env: *mut core::ffi::c_void) -> i32 {
20780    crate::setjmp(env as *mut u64)
20781}
20782
20783#[no_mangle]
20784pub unsafe extern "C" fn setlinebuf(stream: *mut core::ffi::c_void) {
20785    setvbuf(stream as *mut FILE, core::ptr::null_mut(), 1, 0);
20786}
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802#[no_mangle]
20803pub unsafe extern "C" fn significand(x: f64) -> f64 {
20804    let bits = x.to_bits();
20805    let exp = ((bits >> 52) & 0x7ff) as i32;
20806    if exp == 0 || exp == 0x7ff { return x; }
20807    f64::from_bits((bits & 0x000fffffffffffff) | (1023u64 << 52))
20808}
20809
20810#[no_mangle]
20811pub unsafe extern "C" fn significandf(x: f32) -> f32 {
20812    let bits = x.to_bits();
20813    let exp = ((bits >> 23) & 0xff) as i32;
20814    if exp == 0 || exp == 0xff { return x; }
20815    f32::from_bits((bits & 0x007fffff) | (127u32 << 23))
20816}
20817
20818
20819
20820
20821
20822#[no_mangle]
20823pub unsafe extern "C" fn sigset(sig: i32, handler: usize) -> usize {
20824    // BSD/glibc-compatible sigset() is an alias for signal().
20825    signal(sig, handler)
20826}
20827
20828#[no_mangle]
20829pub unsafe extern "C" fn sincos(x: f64, sin: *mut f64, cos: *mut f64) {
20830    *sin = libm::sin(x);
20831    *cos = libm::cos(x);
20832}
20833
20834#[no_mangle]
20835pub unsafe extern "C" fn sincosf(x: f32, sin: *mut f32, cos: *mut f32) {
20836    *sin = libm::sinf(x);
20837    *cos = libm::cosf(x);
20838}
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848unsafe fn nd_ascii_lower(c: c_char) -> c_int {
20849    let b = c as u8;
20850    if b >= b'A' && b <= b'Z' { (b + 32) as c_int } else { b as c_int }
20851}
20852
20853unsafe fn nd_strncasecmp(s1: *const c_char, s2: *const c_char, n: usize) -> c_int {
20854    let mut i = 0usize;
20855    while i < n {
20856        let c1 = nd_ascii_lower(*s1.add(i));
20857        let c2 = nd_ascii_lower(*s2.add(i));
20858        if c1 != c2 || c1 == 0 { return c1 - c2; }
20859        i += 1;
20860    }
20861    0
20862}
20863
20864#[no_mangle]
20865pub unsafe extern "C" fn strcasecmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> i32 {
20866    nd_strncasecmp(s1, s2, usize::MAX)
20867}
20868
20869#[no_mangle]
20870pub unsafe extern "C" fn __strcasecmp_l(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char, _loc: *mut core::ffi::c_void) -> i32 {
20871    nd_strncasecmp(s1, s2, usize::MAX)
20872}
20873
20874#[no_mangle]
20875pub unsafe extern "C" fn strcasestr(haystack: *const core::ffi::c_char, needle: *const core::ffi::c_char) -> *mut core::ffi::c_char {
20876    let nlen = crate::strlen(needle);
20877    if nlen == 0 { return haystack as *mut core::ffi::c_char; }
20878    let mut i = 0;
20879    loop {
20880        let h = haystack.add(i);
20881        if *h == 0 { return core::ptr::null_mut(); }
20882        if crate::strncasecmp(h, needle, nlen) == 0 { return h as *mut core::ffi::c_char; }
20883        i += 1;
20884    }
20885}
20886
20887#[no_mangle]
20888pub unsafe extern "C" fn __strcoll_l(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char, _loc: *mut core::ffi::c_void) -> i32 {
20889    crate::strcmp(s1 as *const u8, s2 as *const u8)
20890}
20891
20892#[no_mangle]
20893pub unsafe extern "C" fn strncasecmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char, n: usize) -> i32 {
20894    nd_strncasecmp(s1, s2, n)
20895}
20896
20897#[no_mangle]
20898pub unsafe extern "C" fn __strncasecmp_l(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char, n: usize, _loc: *mut core::ffi::c_void) -> i32 {
20899    nd_strncasecmp(s1, s2, n)
20900}
20901
20902#[no_mangle]
20903pub unsafe extern "C" fn strsep(stringp: *mut *mut core::ffi::c_char, delim: *const core::ffi::c_char) -> *mut core::ffi::c_char {
20904    let s = *stringp;
20905    if s.is_null() { return core::ptr::null_mut(); }
20906    let mut p = s;
20907    while *p != 0 {
20908        let mut d = delim;
20909        while *d != 0 {
20910            if *p == *d { *p = 0; *stringp = p.add(1); return s; }
20911            d = d.add(1);
20912        }
20913        p = p.add(1);
20914    }
20915    *stringp = core::ptr::null_mut();
20916    s
20917}
20918
20919#[no_mangle]
20920pub unsafe extern "C" fn strtoimax(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, base: i32) -> i64 {
20921    crate::strtol(nptr, endptr, base)
20922}
20923
20924#[no_mangle]
20925pub unsafe extern "C" fn strtok_r(s: *mut core::ffi::c_char, delim: *const core::ffi::c_char, saveptr: *mut *mut core::ffi::c_char) -> *mut core::ffi::c_char {
20926    let mut s = if s.is_null() { *saveptr } else { s };
20927    if s.is_null() { return core::ptr::null_mut(); }
20928    // Skip leading delimiters
20929    while *s != 0 {
20930        let mut d = delim;
20931        let mut found = false;
20932        while *d != 0 {
20933            if *s == *d { found = true; break; }
20934            d = d.add(1);
20935        }
20936        if !found { break; }
20937        s = s.add(1);
20938    }
20939    if *s == 0 { *saveptr = s; return core::ptr::null_mut(); }
20940    let start = s;
20941    // Find end of token
20942    while *s != 0 {
20943        let mut d = delim;
20944        while *d != 0 {
20945            if *s == *d { *s = 0; *saveptr = s.add(1); return start; }
20946            d = d.add(1);
20947        }
20948        s = s.add(1);
20949    }
20950    *saveptr = s;
20951    start
20952}
20953
20954#[no_mangle]
20955pub unsafe extern "C" fn strtoumax(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, base: i32) -> u64 {
20956    crate::strtoul(nptr, endptr, base) as u64
20957}
20958
20959#[no_mangle]
20960pub unsafe extern "C" fn __strxfrm_l(dest: *mut core::ffi::c_char, src: *const core::ffi::c_char, n: usize, _loc: *mut core::ffi::c_void) -> usize {
20961    crate::strlcpy(dest as *mut u8, src as *const u8, n)
20962}
20963
20964#[no_mangle]
20965pub unsafe extern "C" fn swab(src: *const u8, dest: *mut u8, nbytes: isize) {
20966    let mut i = 0;
20967    while i + 1 < nbytes {
20968        let a = *src.add(i as usize);
20969        let b = *src.add(i as usize + 1);
20970        *dest.add(i as usize) = b;
20971        *dest.add(i as usize + 1) = a;
20972        i += 2;
20973    }
20974}
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986#[no_mangle]
20987pub unsafe extern "C" fn __tolower_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20988    if c >= 'A' as i32 && c <= 'Z' as i32 { c + 32 } else { c }
20989}
20990
20991#[no_mangle]
20992pub unsafe extern "C" fn __toupper_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20993    if c >= 'a' as i32 && c <= 'z' as i32 { c - 32 } else { c }
20994}
20995
20996#[no_mangle]
20997pub unsafe extern "C" fn ulimit(cmd: c_int, mut args: ...) -> c_long {
20998    let mut rl: Rlimit = core::mem::zeroed();
20999    if getrlimit(RLIMIT_FSIZE, &mut rl) != 0 { return -1; }
21000    if cmd == 2 {
21001        let val = args.next_arg::<c_long>();
21002        rl.rlim_cur = 512u64.wrapping_mul(val as u64);
21003        if setrlimit(RLIMIT_FSIZE, &rl) != 0 { return -1; }
21004    }
21005    (rl.rlim_cur / 512) as c_long
21006}
21007
21008#[repr(C)]
21009struct UtsName {
21010    sysname: [u8; 65],
21011    nodename: [u8; 65],
21012    release: [u8; 65],
21013    version: [u8; 65],
21014    machine: [u8; 65],
21015    domainname: [u8; 65],
21016}
21017
21018#[no_mangle]
21019pub unsafe extern "C" fn uname(buf: *mut c_void) -> c_int {
21020    // Let the kernel validate the user pointer: an invalid but non-null
21021    // address must produce EFAULT instead of a fault in a local copy.
21022    let r = <Arch as Syscalls>::syscall1(SYS_UNAME, buf as i64);
21023    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
21024    0
21025}
21026
21027#[no_mangle]
21028pub unsafe extern "C" fn unshare(flags: i32) -> i32 {
21029    let r = <Arch as Syscalls>::syscall1(SYS_UNSHARE, flags as i64);
21030    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21031}
21032
21033#[no_mangle]
21034pub unsafe extern "C" fn updwtmpx(wtmpx_file: *const core::ffi::c_char, utx: *const core::ffi::c_void) {
21035    updwtmp(wtmpx_file, utx)
21036}
21037
21038#[no_mangle]
21039pub unsafe extern "C" fn __uselocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
21040    loc
21041}
21042
21043#[repr(C)]
21044pub struct Utimbuf { actime: i64, modtime: i64 }
21045
21046#[no_mangle]
21047pub unsafe extern "C" fn utime(filename: *const c_char, times: *const Utimbuf) -> c_int {
21048    if times.is_null() {
21049        return utimensat(AT_FDCWD, filename, core::ptr::null(), 0);
21050    }
21051    let ts = [
21052        timespec { tv_sec: (*times).actime, tv_nsec: 0 },
21053        timespec { tv_sec: (*times).modtime, tv_nsec: 0 },
21054    ];
21055    utimensat(AT_FDCWD, filename, ts.as_ptr(), 0)
21056}
21057
21058#[no_mangle]
21059pub unsafe extern "C" fn vhangup() -> c_int {
21060    let r = <Arch as Syscalls>::syscall0(SYS_VHANGUP);
21061    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21062}
21063
21064#[no_mangle]
21065pub unsafe extern "C" fn vmsplice(fd: i32, iov: *const c_void, nr_segs: usize, flags: u32) -> isize {
21066    let r = <Arch as Syscalls>::syscall4(SYS_VMSPLICE, fd as i64, iov as i64, nr_segs as i64, flags as i64);
21067    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
21068}
21069
21070
21071
21072#[no_mangle]
21073pub unsafe extern "C" fn wait4(pid: i32, wstatus: *mut i32, options: i32, rusage: *mut core::ffi::c_void) -> i32 {
21074    syscall_ret(<Arch as Syscalls>::syscall4(SYS_WAIT4, pid as i64, wstatus as i64, options as i64, rusage as i64)) as i32
21075}
21076
21077#[no_mangle]
21078pub unsafe extern "C" fn waitid(idtype: i32, id: u32, infop: *mut core::ffi::c_void, options: i32) -> i32 {
21079    // The kernel takes a fifth rusage pointer; it must be NULL, not whatever
21080    // happens to be in r10.
21081    syscall_ret(<Arch as Syscalls>::syscall5(
21082        sysno(247, 95),
21083        idtype as i64,
21084        id as i64,
21085        infop as i64,
21086        options as i64,
21087        0,
21088    )) as i32
21089}
21090
21091#[no_mangle]
21092pub unsafe extern "C" fn __wcscoll_l(s1: *const u32, s2: *const u32, _loc: *mut core::ffi::c_void) -> i32 {
21093    crate::wcscmp(s1 as *const i32, s2 as *const i32)
21094}
21095
21096#[no_mangle]
21097pub unsafe extern "C" fn __wcsxfrm_l(dest: *mut u32, src: *const u32, n: usize, _loc: *mut core::ffi::c_void) -> usize {
21098    crate::wcscpy(dest as *mut i32, src as *const i32);
21099    n
21100}
21101
21102#[no_mangle]
21103pub unsafe extern "C" fn wcwidth(c: u32) -> i32 {
21104    if c == 0 { return 0; }
21105    if c < 32 || (c >= 0x7f && c < 0xa0) { return -1; }
21106    1
21107}
21108
21109
21110
21111
21112
21113// ============================================================
21114// Final missing symbols
21115// ============================================================
21116
21117
21118
21119#[no_mangle]
21120pub 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 {
21121    crate::strtod(nptr, endptr)
21122}
21123
21124#[no_mangle]
21125pub 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 {
21126    crate::strtof(nptr, endptr)
21127}
21128
21129#[no_mangle]
21130pub 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) -> f64 {
21131    crate::strtod(nptr, endptr)
21132}
21133
21134// ============================================================
21135// Directory operations - real implementations
21136// ============================================================
21137
21138#[repr(C)]
21139struct linux_dirent64 {
21140    d_ino: u64,
21141    d_off: i64,
21142    d_reclen: u16,
21143    d_type: u8,
21144    d_name: [u8; 0], // flexible array
21145}
21146
21147// Directory streams used to be a process-wide singleton, which broke any
21148// nested opendir/readdir sequence (git, find, glob, ...). Each DIR now owns
21149// its fd and read buffer, like musl's __dirstream.
21150const DIR_BUF_SIZE: usize = 4096;
21151
21152#[repr(C)]
21153struct DirStream {
21154    fd: i32,
21155    pos: usize,
21156    len: usize,
21157    last_off: i64,
21158    buf: [u8; DIR_BUF_SIZE],
21159}
21160
21161unsafe fn dir_stream_new(fd: i32) -> *mut core::ffi::c_void {
21162    let ds = malloc(core::mem::size_of::<DirStream>()) as *mut DirStream;
21163    if ds.is_null() {
21164        crate::close(fd);
21165        ERRNO!() = ENOMEM;
21166        return core::ptr::null_mut();
21167    }
21168    core::ptr::write_bytes(ds, 0, 1);
21169    (*ds).fd = fd;
21170    ds as *mut core::ffi::c_void
21171}
21172
21173#[no_mangle]
21174pub unsafe extern "C" fn opendir(dirname: *const core::ffi::c_char) -> *mut core::ffi::c_void {
21175    let fd = openat(AT_FDCWD, dirname, O_DIRECTORY, 0); // O_RDONLY | O_DIRECTORY
21176    if fd < 0 { return core::ptr::null_mut(); }
21177    dir_stream_new(fd)
21178}
21179
21180#[no_mangle]
21181pub unsafe extern "C" fn closedir(dirp: *mut core::ffi::c_void) -> i32 {
21182    if dirp.is_null() { ERRNO!() = 22; return -1; }
21183    let ds = dirp as *mut DirStream;
21184    let r = crate::close((*ds).fd);
21185    free(dirp);
21186    r
21187}
21188
21189#[no_mangle]
21190pub unsafe extern "C" fn readdir(dirp: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
21191    if dirp.is_null() { ERRNO!() = 22; return core::ptr::null_mut(); }
21192    let ds = &mut *(dirp as *mut DirStream);
21193
21194    loop {
21195        if ds.pos >= ds.len {
21196            let nread = syscall_ret(<Arch as Syscalls>::syscall3(
21197                SYS_GETDENTS64,
21198                ds.fd as i64,
21199                ds.buf.as_mut_ptr() as i64,
21200                DIR_BUF_SIZE as i64,
21201            )) as isize;
21202            if nread <= 0 { return core::ptr::null_mut(); }
21203            ds.len = nread as usize;
21204            ds.pos = 0;
21205        }
21206
21207        let ent = ds.buf.as_ptr().add(ds.pos) as *const linux_dirent64;
21208        let ent_ref = &*ent;
21209        if ent_ref.d_reclen as usize == 0 {
21210            ds.len = 0;
21211            return core::ptr::null_mut();
21212        }
21213        ds.pos += ent_ref.d_reclen as usize;
21214        ds.last_off = ent_ref.d_off;
21215
21216        // Return a pointer into this stream's buffer (valid until next call).
21217        return ent as *mut core::ffi::c_void;
21218    }
21219}
21220
21221#[no_mangle]
21222pub 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 {
21223    let ent = readdir(dirp);
21224    if ent.is_null() {
21225        *result = core::ptr::null_mut();
21226    } else {
21227        *result = ent;
21228    }
21229    0
21230}
21231
21232#[no_mangle]
21233pub unsafe extern "C" fn seekdir(dirp: *mut core::ffi::c_void, loc: i64) {
21234    if dirp.is_null() { return; }
21235    let ds = &mut *(dirp as *mut DirStream);
21236    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, loc, 0);
21237    ds.pos = 0;
21238    ds.len = 0;
21239}
21240
21241#[no_mangle]
21242pub unsafe extern "C" fn telldir(dirp: *mut core::ffi::c_void) -> i64 {
21243    if dirp.is_null() { return -1; }
21244    (*(dirp as *mut DirStream)).last_off
21245}
21246
21247#[no_mangle]
21248pub unsafe extern "C" fn rewinddir(dirp: *mut core::ffi::c_void) {
21249    if dirp.is_null() { return; }
21250    let ds = &mut *(dirp as *mut DirStream);
21251    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, 0, 0);
21252    ds.pos = 0;
21253    ds.len = 0;
21254    ds.last_off = 0;
21255}
21256
21257#[no_mangle]
21258pub unsafe extern "C" fn dirfd(dirp: *mut core::ffi::c_void) -> i32 {
21259    if dirp.is_null() { ERRNO!() = 22; return -1; }
21260    (*(dirp as *mut DirStream)).fd
21261}
21262
21263// ============================================================
21264// Memory management - real implementations
21265// ============================================================
21266
21267#[no_mangle]
21268pub unsafe extern "C" fn mprotect(addr: *mut u8, len: usize, prot: i32) -> i32 {
21269    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MPROTECT, addr as i64, len as i64, prot as i64)) as i32
21270}
21271
21272#[no_mangle]
21273pub unsafe extern "C" fn msync(addr: *mut u8, len: usize, flags: i32) -> i32 {
21274    syscall_ret(<Arch as Syscalls>::syscall3(sysno(26, 227), addr as i64, len as i64, flags as i64)) as i32
21275}
21276
21277#[no_mangle]
21278pub unsafe extern "C" fn mlock(addr: *const u8, len: usize) -> i32 {
21279    syscall_ret(<Arch as Syscalls>::syscall2(sysno(149, 228), addr as i64, len as i64)) as i32
21280}
21281
21282#[no_mangle]
21283pub unsafe extern "C" fn munlock(addr: *const u8, len: usize) -> i32 {
21284    syscall_ret(<Arch as Syscalls>::syscall2(sysno(150, 229), addr as i64, len as i64)) as i32
21285}
21286
21287#[no_mangle]
21288pub unsafe extern "C" fn mlockall(flags: i32) -> i32 {
21289    syscall_ret(<Arch as Syscalls>::syscall1(sysno(151, 230), flags as i64)) as i32
21290}
21291
21292#[no_mangle]
21293pub unsafe extern "C" fn munlockall() -> i32 {
21294    syscall_ret(<Arch as Syscalls>::syscall0(sysno(152, 231))) as i32
21295}
21296
21297#[no_mangle]
21298pub unsafe extern "C" fn madvise(addr: *mut u8, len: usize, advice: i32) -> i32 {
21299    syscall_ret(<Arch as Syscalls>::syscall3(sysno(28, 233), addr as i64, len as i64, advice as i64)) as i32
21300}
21301
21302#[no_mangle]
21303pub unsafe extern "C" fn mincore(addr: *mut u8, len: usize, vec: *mut u8) -> i32 {
21304    syscall_ret(<Arch as Syscalls>::syscall3(sysno(27, 232), addr as i64, len as i64, vec as i64)) as i32
21305}
21306
21307// ============================================================
21308
21309// ============================================================
21310// Missing math functions
21311// ============================================================
21312
21313#[no_mangle]
21314pub unsafe extern "C" fn drem(x: f64, y: f64) -> f64 {
21315    remainder(x, y)
21316}
21317
21318#[no_mangle]
21319pub unsafe extern "C" fn dremf(x: f32, y: f32) -> f32 {
21320    remainderf(x, y)
21321}
21322
21323#[no_mangle]
21324pub unsafe extern "C" fn pow10(x: f64) -> f64 {
21325    libm::pow(10.0, x)
21326}
21327
21328#[no_mangle]
21329pub unsafe extern "C" fn pow10f(x: f32) -> f32 {
21330    libm::powf(10.0, x)
21331}
21332
21333#[no_mangle]
21334pub unsafe extern "C" fn pow10l(x: f64) -> f64 {
21335    libm::pow(10.0, x)
21336}
21337
21338#[no_mangle]
21339pub unsafe extern "C" fn isless(x: f64, y: f64) -> i32 {
21340    if x.is_nan() || y.is_nan() { 0 } else { (x < y) as i32 }
21341}
21342
21343#[no_mangle]
21344pub unsafe extern "C" fn islessf(x: f32, y: f32) -> i32 {
21345    if x.is_nan() || y.is_nan() { 0 } else { (x < y) as i32 }
21346}
21347
21348#[no_mangle]
21349pub unsafe extern "C" fn lgamma_r(x: f64, signgamp: *mut i32) -> f64 {
21350    lgamma_r_impl(x, signgamp)
21351}
21352
21353#[no_mangle]
21354pub unsafe extern "C" fn lgammaf_r(x: f32, signgamp: *mut i32) -> f32 {
21355    if x.is_nan() {
21356        if !signgamp.is_null() { *signgamp = 1; }
21357        return x;
21358    }
21359    if x == 0.0 {
21360        if !signgamp.is_null() { *signgamp = if x.is_sign_negative() { -1 } else { 1 }; }
21361        feraiseexcept(FE_DIVBYZERO);
21362        return f32::INFINITY;
21363    }
21364    let (r, sign) = libm::lgammaf_r(x);
21365    if !signgamp.is_null() { *signgamp = sign; }
21366    r
21367}
21368
21369#[no_mangle]
21370pub unsafe extern "C" fn lgammal_r(x: f64, signgamp: *mut i32) -> f64 {
21371    lgamma_r(x, signgamp)
21372}
21373
21374// ============================================================
21375// Comparison macros
21376// ============================================================
21377
21378#[no_mangle]
21379pub unsafe extern "C" fn islessequal(x: f64, y: f64) -> i32 {
21380    if x.is_nan() || y.is_nan() { 0 } else { (x <= y) as i32 }
21381}
21382
21383#[no_mangle]
21384pub unsafe extern "C" fn islessequalf(x: f32, y: f32) -> i32 {
21385    if x.is_nan() || y.is_nan() { 0 } else { (x <= y) as i32 }
21386}
21387
21388#[no_mangle]
21389pub unsafe extern "C" fn islessgreater(x: f64, y: f64) -> i32 {
21390    if x.is_nan() || y.is_nan() { 0 } else { (x < y || x > y) as i32 }
21391}
21392
21393#[no_mangle]
21394pub unsafe extern "C" fn islessgreaterf(x: f32, y: f32) -> i32 {
21395    if x.is_nan() || y.is_nan() { 0 } else { (x < y || x > y) as i32 }
21396}
21397
21398#[no_mangle]
21399pub unsafe extern "C" fn isgreater(x: f64, y: f64) -> i32 {
21400    if x.is_nan() || y.is_nan() { 0 } else { (x > y) as i32 }
21401}
21402
21403#[no_mangle]
21404pub unsafe extern "C" fn isgreaterf(x: f32, y: f32) -> i32 {
21405    if x.is_nan() || y.is_nan() { 0 } else { (x > y) as i32 }
21406}
21407
21408#[no_mangle]
21409pub unsafe extern "C" fn isgreaterequal(x: f64, y: f64) -> i32 {
21410    if x.is_nan() || y.is_nan() { 0 } else { (x >= y) as i32 }
21411}
21412
21413#[no_mangle]
21414pub unsafe extern "C" fn isgreaterequalf(x: f32, y: f32) -> i32 {
21415    if x.is_nan() || y.is_nan() { 0 } else { (x >= y) as i32 }
21416}
21417
21418// ============================================================
21419// musl ABI compatibility helpers
21420// ============================================================
21421
21422#[no_mangle]
21423pub unsafe extern "C" fn stpcpy(dest: *mut c_char, src: *const c_char) -> *mut c_char {
21424    let mut d = dest;
21425    let mut s = src;
21426    while *s != 0 {
21427        *d = *s;
21428        d = d.add(1);
21429        s = s.add(1);
21430    }
21431    *d = 0;
21432    d
21433}
21434
21435#[no_mangle]
21436pub unsafe extern "C" fn stpncpy(dest: *mut c_char, src: *const c_char, n: usize) -> *mut c_char {
21437    let mut i = 0;
21438    while i < n && *src.add(i) != 0 {
21439        *dest.add(i) = *src.add(i);
21440        i += 1;
21441    }
21442    let end = dest.add(i);
21443    while i < n {
21444        *dest.add(i) = 0;
21445        i += 1;
21446    }
21447    end
21448}
21449
21450#[no_mangle]
21451pub unsafe extern "C" fn strchrnul(s: *const c_char, c: c_int) -> *mut c_char {
21452    let mut p = s;
21453    while *p != 0 && *p as c_int != c {
21454        p = p.add(1);
21455    }
21456    p as *mut c_char
21457}
21458
21459#[no_mangle]
21460pub unsafe extern "C" fn fstatat(dirfd: c_int, path: *const c_char, buf: *mut Stat, flags: c_int) -> c_int {
21461    let r = sys_newfstatat(dirfd, path, buf as *mut u8, flags);
21462    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21463}
21464
21465#[no_mangle]
21466pub unsafe extern "C" fn execvpe(
21467    file: *const c_char,
21468    argv: *const *const c_char,
21469    envp: *const *const c_char,
21470) -> c_int {
21471    ERRNO!() = ENOENT_VAL;
21472    if file.is_null() || *file == 0 {
21473        return -1;
21474    }
21475    let mut p = file;
21476    while *p != 0 {
21477        if *p == b'/' as c_char {
21478            return execve(file, argv, envp);
21479        }
21480        p = p.add(1);
21481    }
21482    let file_len = crate::strlen(file);
21483    let path = crate::getenv(b"PATH\0".as_ptr() as *const c_char);
21484    let default_path = b"/usr/local/bin:/bin:/usr/bin\0";
21485    let path = if path.is_null() { default_path.as_ptr() as *const c_char } else { path };
21486
21487    let mut seen_eacces = false;
21488    let mut buf = [0 as c_char; 4096];
21489    let mut dir = path;
21490    loop {
21491        let mut end = dir;
21492        while *end != 0 && *end != b':' as c_char { end = end.add(1); }
21493        let dlen = end.offset_from(dir) as usize;
21494        // An empty PATH component means the current directory (no slash).
21495        let need_slash = dlen > 0;
21496        let total = dlen + need_slash as usize + file_len;
21497        if total < buf.len() {
21498            let mut i = 0;
21499            while i < dlen { buf[i] = *dir.add(i); i += 1; }
21500            if need_slash { buf[i] = b'/' as c_char; i += 1; }
21501            let mut j = 0;
21502            while j < file_len { buf[i + j] = *file.add(j); j += 1; }
21503            buf[i + j] = 0;
21504            execve(buf.as_ptr(), argv, envp);
21505            match ERRNO!() {
21506                13 => seen_eacces = true, // EACCES
21507                2 | 20 => {}              // ENOENT, ENOTDIR: try next
21508                _ => return -1,
21509            }
21510        }
21511        if *end == 0 { break; }
21512        dir = end.add(1);
21513    }
21514    ERRNO!() = if seen_eacces { 13 } else { 2 };
21515    -1
21516}
21517
21518// Locale-aware entry points. keel currently has a single global locale,
21519// so these are source/ABI-compatible wrappers around the normal functions.
21520#[no_mangle]
21521pub unsafe extern "C" fn strcoll_l(s1: *const c_char, s2: *const c_char, _loc: locale_t) -> c_int {
21522    strcoll(s1, s2)
21523}
21524
21525#[no_mangle]
21526pub unsafe extern "C" fn strxfrm_l(dest: *mut c_char, src: *const c_char, n: usize, _loc: locale_t) -> usize {
21527    strxfrm(dest, src, n)
21528}
21529
21530#[no_mangle]
21531pub unsafe extern "C" fn strerror_l(errnum: c_int, _loc: locale_t) -> *mut c_char {
21532    strerror(errnum)
21533}
21534
21535#[no_mangle]
21536pub unsafe extern "C" fn strcasecmp_l(s1: *const c_char, s2: *const c_char, _loc: locale_t) -> c_int {
21537    strcasecmp(s1, s2)
21538}
21539
21540#[no_mangle]
21541pub unsafe extern "C" fn strncasecmp_l(s1: *const c_char, s2: *const c_char, n: usize, _loc: locale_t) -> c_int {
21542    strncasecmp(s1, s2, n)
21543}
21544
21545#[no_mangle]
21546pub unsafe extern "C" fn strftime_l(s: *mut c_char, max: usize, fmt: *const c_char, tm: *const tm, _loc: locale_t) -> usize {
21547    strftime(s, max, fmt, tm)
21548}
21549
21550#[no_mangle]
21551pub unsafe extern "C" fn nl_langinfo_l(item: c_int, _loc: locale_t) -> *mut c_char {
21552    nl_langinfo(item)
21553}
21554
21555#[no_mangle]
21556pub unsafe extern "C" fn wcscoll_l(s1: *const u32, s2: *const u32, _loc: locale_t) -> c_int {
21557    wcscoll(s1, s2)
21558}
21559
21560#[no_mangle]
21561pub unsafe extern "C" fn wcsxfrm_l(dst: *mut wchar_t, src: *const wchar_t, n: usize, _loc: locale_t) -> usize {
21562    wcsxfrm(dst, src, n)
21563}
21564
21565#[no_mangle]
21566pub unsafe extern "C" fn wcsftime_l(s: *mut u32, max: usize, fmt: *const u32, tm: *const c_void, _loc: locale_t) -> usize {
21567    wcsftime(s, max, fmt, tm)
21568}
21569
21570#[no_mangle]
21571pub unsafe extern "C" fn wctype_l(name: *const c_char, _loc: locale_t) -> wctype_t {
21572    wctype(name)
21573}
21574
21575#[no_mangle]
21576pub unsafe extern "C" fn wctrans_l(name: *const c_char, _loc: locale_t) -> wctrans_t {
21577    wctrans(name)
21578}
21579
21580#[no_mangle]
21581pub unsafe extern "C" fn towlower_l(c: wint_t, _loc: locale_t) -> wint_t {
21582    towlower(c)
21583}
21584
21585#[no_mangle]
21586pub unsafe extern "C" fn towupper_l(c: wint_t, _loc: locale_t) -> wint_t {
21587    towupper(c)
21588}
21589
21590#[no_mangle]
21591pub unsafe extern "C" fn towctrans_l(c: wint_t, desc: wctrans_t, _loc: locale_t) -> wint_t {
21592    towctrans(c, desc)
21593}
21594
21595#[no_mangle] pub unsafe extern "C" fn iswalnum_l(c: wint_t, _l: locale_t) -> c_int { iswalnum(c) }
21596#[no_mangle] pub unsafe extern "C" fn iswalpha_l(c: wint_t, _l: locale_t) -> c_int { iswalpha(c) }
21597#[no_mangle] pub unsafe extern "C" fn iswblank_l(c: wint_t, _l: locale_t) -> c_int { iswblank(c) }
21598#[no_mangle] pub unsafe extern "C" fn iswcntrl_l(c: wint_t, _l: locale_t) -> c_int { iswcntrl(c) }
21599#[no_mangle] pub unsafe extern "C" fn iswdigit_l(c: wint_t, _l: locale_t) -> c_int { iswdigit(c) }
21600#[no_mangle] pub unsafe extern "C" fn iswgraph_l(c: wint_t, _l: locale_t) -> c_int { iswgraph(c) }
21601#[no_mangle] pub unsafe extern "C" fn iswlower_l(c: wint_t, _l: locale_t) -> c_int { iswlower(c) }
21602#[no_mangle] pub unsafe extern "C" fn iswprint_l(c: wint_t, _l: locale_t) -> c_int { iswprint(c) }
21603#[no_mangle] pub unsafe extern "C" fn iswpunct_l(c: wint_t, _l: locale_t) -> c_int { iswpunct(c) }
21604#[no_mangle] pub unsafe extern "C" fn iswspace_l(c: wint_t, _l: locale_t) -> c_int { iswspace(c) }
21605#[no_mangle] pub unsafe extern "C" fn iswupper_l(c: wint_t, _l: locale_t) -> c_int { iswupper(c) }
21606#[no_mangle] pub unsafe extern "C" fn iswxdigit_l(c: wint_t, _l: locale_t) -> c_int { iswxdigit(c) }
21607#[no_mangle] pub unsafe extern "C" fn iswctype_l(c: wint_t, desc: wctype_t, _l: locale_t) -> c_int { iswctype(c, desc) }
21608
21609// ISO C99 scanf ABI aliases expected by musl binaries.
21610#[no_mangle] pub unsafe extern "C" fn __isoc99_scanf(fmt: *const c_char, args: ...) -> c_int { vfscanf(stdin, fmt, args) }
21611#[no_mangle] pub unsafe extern "C" fn __isoc99_fscanf(f: *mut FILE, fmt: *const c_char, args: ...) -> c_int { vfscanf(f, fmt, args) }
21612#[no_mangle] pub unsafe extern "C" fn __isoc99_sscanf(s: *const c_char, fmt: *const c_char, args: ...) -> c_int { vsscanf(s, fmt, args) }
21613#[no_mangle] pub unsafe extern "C" fn __isoc99_vscanf(fmt: *const c_char, args: VaList) -> c_int { vfscanf(stdin, fmt, args) }
21614#[no_mangle] pub unsafe extern "C" fn __isoc99_vfscanf(f: *mut FILE, fmt: *const c_char, args: VaList) -> c_int { vfscanf(f, fmt, args) }
21615#[no_mangle] pub unsafe extern "C" fn __isoc99_vsscanf(s: *const c_char, fmt: *const c_char, args: VaList) -> c_int { vsscanf(s, fmt, args) }
21616#[no_mangle] pub unsafe extern "C" fn __isoc99_wscanf(fmt: *const wchar_t, args: ...) -> c_int { vfwscanf(stdin, fmt, args) }
21617#[no_mangle] pub unsafe extern "C" fn __isoc99_fwscanf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int { vfwscanf(f, fmt, args) }
21618#[no_mangle] pub unsafe extern "C" fn __isoc99_swscanf(s: *const wchar_t, fmt: *const wchar_t, args: ...) -> c_int { vswscanf(s, fmt, args) }
21619#[no_mangle] pub unsafe extern "C" fn __isoc99_vwscanf(fmt: *const wchar_t, args: VaList) -> c_int { vfwscanf(stdin, fmt, args) }
21620#[no_mangle] pub unsafe extern "C" fn __isoc99_vfwscanf(f: *mut FILE, fmt: *const wchar_t, args: VaList) -> c_int { vfwscanf(f, fmt, args) }
21621#[no_mangle] pub unsafe extern "C" fn __isoc99_vswscanf(s: *const wchar_t, fmt: *const wchar_t, args: VaList) -> c_int { vswscanf(s, fmt, args) }
21622
21623// Unlocked stdio entry points. The current stdio implementation is not
21624// thread-safe anyway, so these are aliases for the normal entry points.
21625#[no_mangle] pub unsafe extern "C" fn clearerr_unlocked(f: *mut FILE) { clearerr(f) }
21626#[no_mangle] pub unsafe extern "C" fn feof_unlocked(f: *mut FILE) -> c_int { feof(f) }
21627#[no_mangle] pub unsafe extern "C" fn ferror_unlocked(f: *mut FILE) -> c_int { ferror(f) }
21628#[no_mangle] pub unsafe extern "C" fn fileno_unlocked(f: *mut FILE) -> c_int { fileno(f) }
21629#[no_mangle] pub unsafe extern "C" fn fflush_unlocked(f: *mut FILE) -> c_int { fflush(f) }
21630#[no_mangle] pub unsafe extern "C" fn fgetc_unlocked(f: *mut FILE) -> c_int { fgetc(f) }
21631#[no_mangle] pub unsafe extern "C" fn fgets_unlocked(s: *mut c_char, n: c_int, f: *mut FILE) -> *mut c_char { fgets(s, n, f) }
21632#[no_mangle] pub unsafe extern "C" fn fputc_unlocked(c: c_int, f: *mut FILE) -> c_int { fputc(c, f) }
21633#[no_mangle] pub unsafe extern "C" fn fputs_unlocked(s: *const c_char, f: *mut FILE) -> c_int { fputs(s, f) }
21634#[no_mangle] pub unsafe extern "C" fn fread_unlocked(p: *mut c_void, size: usize, n: usize, f: *mut FILE) -> usize { fread(p, size, n, f) }
21635#[no_mangle] pub unsafe extern "C" fn fwrite_unlocked(p: *const c_void, size: usize, n: usize, f: *mut FILE) -> usize { fwrite(p, size, n, f) }
21636#[no_mangle] pub unsafe extern "C" fn fgetwc_unlocked(f: *mut FILE) -> wint_t { fgetwc(f) }
21637#[no_mangle] pub unsafe extern "C" fn fgetws_unlocked(s: *mut u32, n: c_int, f: *mut c_void) -> *mut u32 { fgetws(s, n, f) }
21638#[no_mangle] pub unsafe extern "C" fn fputwc_unlocked(c: wchar_t, f: *mut FILE) -> wint_t { fputwc(c, f) }
21639#[no_mangle] pub unsafe extern "C" fn fputws_unlocked(s: *const wchar_t, f: *mut FILE) -> c_int { fputws(s, f) }
21640#[no_mangle] pub unsafe extern "C" fn getwc_unlocked(f: *mut c_void) -> wint_t { getwc(f) }
21641#[no_mangle] pub unsafe extern "C" fn putwc_unlocked(c: u32, f: *mut c_void) -> wint_t { putwc(c, f) }
21642#[no_mangle] pub unsafe extern "C" fn getwchar_unlocked() -> wint_t { getwchar() }
21643#[no_mangle] pub unsafe extern "C" fn putwchar_unlocked(c: wchar_t) -> wint_t { putwchar(c) }
21644#[no_mangle] pub unsafe extern "C" fn fpurge(f: *mut FILE) { clearerr(f) }
21645#[no_mangle] pub unsafe extern "C" fn _IO_getc(f: *mut FILE) -> c_int { getc(f) }
21646#[no_mangle] pub unsafe extern "C" fn _IO_putc(c: c_int, f: *mut FILE) -> c_int { putc(c, f) }
21647#[no_mangle] pub unsafe extern "C" fn _IO_getc_unlocked(f: *mut FILE) -> c_int { getc(f) }
21648#[no_mangle] pub unsafe extern "C" fn _IO_putc_unlocked(c: c_int, f: *mut FILE) -> c_int { putc(c, f) }
21649#[no_mangle] pub unsafe extern "C" fn _IO_feof_unlocked(f: *mut FILE) -> c_int { feof(f) }
21650#[no_mangle] pub unsafe extern "C" fn _IO_ferror_unlocked(f: *mut FILE) -> c_int { ferror(f) }
21651
21652// ABI aliases used by musl and older C libraries.
21653#[no_mangle] pub unsafe extern "C" fn __getauxval(t: c_ulong) -> c_ulong { getauxval(t) }
21654#[no_mangle] pub unsafe extern "C" fn __longjmp(env: *const c_ulong, val: c_int) -> ! { longjmp(env, val) }
21655#[no_mangle] pub unsafe extern "C" fn bsd_signal(sig: c_int, handler: usize) -> usize { signal(sig, handler) }
21656#[no_mangle] pub unsafe extern "C" fn __sysv_signal(sig: c_int, handler: usize) -> usize { signal(sig, handler) }
21657#[no_mangle] pub unsafe extern "C" fn eaccess(path: *const c_char, mode: c_int) -> c_int { access(path, mode) }
21658#[no_mangle] pub unsafe extern "C" fn __xpg_basename(path: *mut c_char) -> *mut c_char { basename(path) }
21659#[no_mangle] pub unsafe extern "C" fn __xpg_strerror_r(errnum: c_int, buf: *mut c_char, len: usize) -> c_int { strerror_r(errnum, buf, len) }
21660#[no_mangle] pub unsafe extern "C" fn __posix_getopt(argc: c_int, argv: *const *const c_char, optstring: *const c_char) -> c_int { getopt(argc, argv, optstring) }
21661
21662// ============================================================
21663// Remaining musl ABI entry points
21664// ============================================================
21665
21666#[no_mangle]
21667pub unsafe extern "C" fn cfsetspeed(termios_p: *mut c_void, speed: u32) -> c_int {
21668    let r = cfsetispeed(termios_p, speed);
21669    if r != 0 { return r; }
21670    cfsetospeed(termios_p, speed)
21671}
21672
21673#[no_mangle]
21674pub unsafe extern "C" fn futimesat(dirfd: c_int, path: *const c_char, times: *const timeval) -> c_int {
21675    if times.is_null() {
21676        return utimensat(dirfd, path, core::ptr::null(), 0);
21677    }
21678    let tv = times as *const [timeval; 2];
21679    let mut ts: [timespec; 2] = [
21680        timespec { tv_sec: (*tv)[0].tv_sec, tv_nsec: (*tv)[0].tv_usec * 1000 },
21681        timespec { tv_sec: (*tv)[1].tv_sec, tv_nsec: (*tv)[1].tv_usec * 1000 },
21682    ];
21683    for t in &mut ts {
21684        if t.tv_nsec < 0 || t.tv_nsec >= 1_000_000_000 {
21685            ERRNO!() = EINVAL;
21686            return -1;
21687        }
21688    }
21689    utimensat(dirfd, path, ts.as_ptr(), 0)
21690}
21691
21692#[no_mangle]
21693pub unsafe extern "C" fn membarrier(cmd: c_int, flags: c_int, cpu_id: c_int) -> c_int {
21694    <Arch as Syscalls>::syscall3(SYS_MEMBARRIER, cmd as i64, flags as i64, cpu_id as i64) as c_int
21695}
21696
21697#[no_mangle]
21698pub unsafe extern "C" fn mremap(
21699    old_address: *mut c_void,
21700    old_size: usize,
21701    new_size: usize,
21702    flags: c_int,
21703    mut args: ...
21704) -> *mut c_void {
21705    let new_address = if flags & 2 != 0 { args.next_arg::<*mut c_void>() } else { core::ptr::null_mut() };
21706    let r = <Arch as Syscalls>::syscall5(
21707        SYS_MREMAP,
21708        old_address as i64,
21709        old_size as i64,
21710        new_size as i64,
21711        flags as i64,
21712        new_address as i64,
21713    );
21714    if r < 0 {
21715        ERRNO!() = (-r) as c_int;
21716        return (-1isize) as *mut c_void;
21717    }
21718    r as *mut c_void
21719}
21720
21721#[no_mangle]
21722pub unsafe extern "C" fn ptsname_r(fd: c_int, buf: *mut c_char, buflen: usize) -> c_int {
21723    let name = ptsname(fd);
21724    if name.is_null() { return -1; }
21725    let n = crate::strlen(name);
21726    if n + 1 > buflen {
21727        ERRNO!() = ERANGE_VAL;
21728        return ERANGE_VAL;
21729    }
21730    core::ptr::copy_nonoverlapping(name, buf, n + 1);
21731    0
21732}
21733
21734#[no_mangle]
21735pub unsafe extern "C" fn posix_getdents(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize {
21736    if flags != 0 {
21737        ERRNO!() = EINVAL;
21738        return -1;
21739    }
21740    let r = <Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, buf as i64, len as i64);
21741    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
21742}
21743
21744#[no_mangle]
21745pub unsafe extern "C" fn riscv_flush_icache(start: *mut c_void, end: *mut c_void, flags: c_ulong) -> c_int {
21746    #[cfg(target_arch = "riscv64")]
21747    {
21748        let r = <Arch as Syscalls>::syscall3(259, start as i64, end as i64, flags as i64);
21749        if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21750    }
21751    #[cfg(not(target_arch = "riscv64"))]
21752    {
21753        let _ = (start, end, flags);
21754        0
21755    }
21756}
21757
21758#[no_mangle]
21759pub unsafe extern "C" fn __riscv_flush_icache(start: *mut c_void, end: *mut c_void, flags: c_ulong) -> c_int {
21760    riscv_flush_icache(start, end, flags)
21761}
21762
21763#[no_mangle]
21764pub unsafe extern "C" fn mkostemps(template: *mut c_char, suffixlen: c_int, flags: c_int) -> c_int {
21765    let fd = mkstemps(template, suffixlen);
21766    if fd >= 0 && flags & O_CLOEXEC != 0 {
21767        sys_fcntl(fd, F_SETFD, FD_CLOEXEC as i64);
21768    }
21769    fd
21770}
21771
21772#[no_mangle]
21773pub unsafe extern "C" fn statfs(path: *const c_char, buf: *mut c_void) -> c_int {
21774    let r = <Arch as Syscalls>::syscall2(SYS_STATFS, path as i64, buf as i64);
21775    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21776}
21777
21778#[no_mangle]
21779pub unsafe extern "C" fn fstatfs(fd: c_int, buf: *mut c_void) -> c_int {
21780    let r = <Arch as Syscalls>::syscall2(SYS_FSTATFS, fd as i64, buf as i64);
21781    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21782}
21783
21784#[no_mangle]
21785pub unsafe extern "C" fn sysinfo(info: *mut c_void) -> c_int {
21786    let r = <Arch as Syscalls>::syscall1(SYS_SYSINFO, info as i64);
21787    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21788}
21789
21790#[no_mangle]
21791pub unsafe extern "C" fn pthread_tryjoin_np(thread: PthreadT, retval: *mut *mut c_void) -> c_int {
21792    let slot = thread as *mut Thread;
21793    if slot.is_null() { return EINVAL; }
21794    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
21795    let tid = core::ptr::read_volatile(&raw const (*slot).tid);
21796    if tid > 0 { return EBUSY; }
21797    if tid < 0 { return EINVAL; }
21798    pthread_join(thread, retval)
21799}
21800
21801#[no_mangle]
21802pub unsafe extern "C" fn pthread_timedjoin_np(thread: PthreadT, retval: *mut *mut c_void, abstime: *const timespec) -> c_int {
21803    let slot = thread as *mut Thread;
21804    if slot.is_null() { return EINVAL; }
21805    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
21806    loop {
21807        let r = pthread_tryjoin_np(thread, retval);
21808        if r != EBUSY { return r; }
21809        let tid = core::ptr::read_volatile(&raw const (*slot).tid);
21810        if tid <= 0 { continue; }
21811        let e = futex_timedwait(&raw mut (*slot).tid, tid, abstime);
21812        if e == ETIMEDOUT { return ETIMEDOUT; }
21813    }
21814}
21815
21816
21817// utmp/utmpx are backed by the classic /var/run/utmp file.  musl itself
21818// leaves these as no-ops; keel provides the real file-backed API.
21819#[repr(C)]
21820pub struct UtmpExit {
21821    pub e_termination: i16,
21822    pub e_exit: i16,
21823}
21824
21825#[repr(C)]
21826pub struct Utmpx {
21827    pub ut_type: i16,
21828    pub __ut_pad1: i16,
21829    pub ut_pid: i32,
21830    pub ut_line: [c_char; 32],
21831    pub ut_id: [c_char; 4],
21832    pub ut_user: [c_char; 32],
21833    pub ut_host: [c_char; 256],
21834    pub ut_exit: UtmpExit,
21835    pub ut_session: i32,
21836    pub __ut_pad2: i32,
21837    pub ut_tv: timeval,
21838    pub ut_addr_v6: [u32; 4],
21839    pub __unused: [u8; 20],
21840}
21841
21842const UTMP_SIZE: usize = 400;
21843const _: [(); UTMP_SIZE] = [(); core::mem::size_of::<Utmpx>()];
21844
21845static mut UTMP_FD: c_int = -1;
21846static mut UTMP_PATH: [u8; 256] = [0; 256];
21847static mut UTMP_PATH_SET: bool = false;
21848#[repr(align(8))]
21849struct UtmpBuf([u8; UTMP_SIZE]);
21850static mut UTMP_BUF: UtmpBuf = UtmpBuf([0; UTMP_SIZE]);
21851
21852unsafe fn utmp_path_ptr() -> *const c_char {
21853    if !UTMP_PATH_SET {
21854        let default = b"/var/run/utmp\0";
21855        let mut i = 0;
21856        while i < default.len() && i < UTMP_PATH.len() {
21857            UTMP_PATH[i] = default[i];
21858            i += 1;
21859        }
21860        UTMP_PATH_SET = true;
21861    }
21862    UTMP_PATH.as_ptr() as *const c_char
21863}
21864
21865unsafe fn utmp_open_read() -> c_int {
21866    if UTMP_FD >= 0 {
21867        crate::close(UTMP_FD);
21868    }
21869    UTMP_FD = crate::open(utmp_path_ptr(), 0, 0);
21870    UTMP_FD
21871}
21872
21873unsafe fn utmp_open_append() -> c_int {
21874    crate::open(utmp_path_ptr(), 1 | 64 | 1024, 0o644)
21875}
21876
21877#[no_mangle]
21878pub unsafe extern "C" fn setutent() {
21879    let _ = utmp_open_read();
21880}
21881
21882#[no_mangle]
21883pub unsafe extern "C" fn endutent() {
21884    if UTMP_FD >= 0 {
21885        crate::close(UTMP_FD);
21886        UTMP_FD = -1;
21887    }
21888}
21889
21890#[no_mangle]
21891pub unsafe extern "C" fn getutent() -> *mut c_void {
21892    if UTMP_FD < 0 && utmp_open_read() < 0 {
21893        return core::ptr::null_mut();
21894    }
21895    let n = crate::read(UTMP_FD, UTMP_BUF.0.as_mut_ptr() as *mut c_void, UTMP_SIZE);
21896    if n == UTMP_SIZE as isize {
21897        UTMP_BUF.0.as_mut_ptr() as *mut c_void
21898    } else {
21899        core::ptr::null_mut()
21900    }
21901}
21902
21903unsafe fn utmp_id_eq(a: &[c_char; 4], b: &[c_char; 4]) -> bool {
21904    a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3]
21905}
21906
21907unsafe fn utmp_line_eq(a: &[c_char; 32], b: &[c_char; 32]) -> bool {
21908    let mut i = 0;
21909    while i < 32 {
21910        if a[i] != b[i] { return false; }
21911        if a[i] == 0 { return true; }
21912        i += 1;
21913    }
21914    true
21915}
21916
21917#[no_mangle]
21918pub unsafe extern "C" fn getutid(ut: *const c_void) -> *mut c_void {
21919    if ut.is_null() { return core::ptr::null_mut(); }
21920    let want = &*(ut as *const Utmpx);
21921    loop {
21922        let p = getutent();
21923        if p.is_null() { return p; }
21924        let cur = &*(p as *const Utmpx);
21925        let matched = match want.ut_type {
21926            1 | 2 | 3 | 4 => cur.ut_type == want.ut_type,
21927            _ => utmp_id_eq(&cur.ut_id, &want.ut_id)
21928                && (want.ut_type == 0 || cur.ut_type == want.ut_type),
21929        };
21930        if matched { return p; }
21931    }
21932}
21933
21934#[no_mangle]
21935pub unsafe extern "C" fn getutline(ut: *const c_void) -> *mut c_void {
21936    if ut.is_null() { return core::ptr::null_mut(); }
21937    let want = &*(ut as *const Utmpx);
21938    loop {
21939        let p = getutent();
21940        if p.is_null() { return p; }
21941        if utmp_line_eq(&(*(p as *const Utmpx)).ut_line, &want.ut_line) {
21942            return p;
21943        }
21944    }
21945}
21946
21947#[no_mangle]
21948pub unsafe extern "C" fn pututline(ut: *const c_void) -> *mut c_void {
21949    if ut.is_null() { return core::ptr::null_mut(); }
21950    let fd = utmp_open_append();
21951    if fd < 0 { return core::ptr::null_mut(); }
21952    let n = crate::write(fd, ut, UTMP_SIZE);
21953    crate::close(fd);
21954    if n == UTMP_SIZE as isize { ut as *mut c_void } else { core::ptr::null_mut() }
21955}
21956
21957#[no_mangle]
21958pub unsafe extern "C" fn updwtmp(file: *const c_char, ut: *const c_void) {
21959    if file.is_null() || ut.is_null() { return; }
21960    let fd = crate::open(file, 1 | 64 | 1024, 0o644);
21961    if fd >= 0 {
21962        let _ = crate::write(fd, ut, UTMP_SIZE);
21963        crate::close(fd);
21964    }
21965}
21966
21967unsafe fn utmp_set_name(file: *const c_char) -> c_int {
21968    if file.is_null() { return -1; }
21969    let len = crate::strlen(file);
21970    if len + 1 > UTMP_PATH.len() { return -1; }
21971    if UTMP_FD >= 0 {
21972        crate::close(UTMP_FD);
21973        UTMP_FD = -1;
21974    }
21975    core::ptr::copy_nonoverlapping(file, UTMP_PATH.as_mut_ptr() as *mut c_char, len + 1);
21976    UTMP_PATH_SET = true;
21977    0
21978}
21979
21980#[no_mangle]
21981pub unsafe extern "C" fn utmpname(file: *const c_char) -> c_int { utmp_set_name(file) }
21982
21983#[no_mangle]
21984pub unsafe extern "C" fn utmpxname(file: *const c_char) -> c_int { utmp_set_name(file) }
21985
21986
21987// Data symbols and internal aliases still referenced by some musl binaries.
21988#[no_mangle] pub static mut ___environ: *mut *mut c_char = core::ptr::null_mut();
21989#[no_mangle] pub static mut _environ: *mut *mut c_char = core::ptr::null_mut();
21990#[no_mangle] pub unsafe extern "C" fn __freelocale(loc: locale_t) { freelocale(loc) }
21991#[no_mangle] pub unsafe extern "C" fn __getdelim(lineptr: *mut *mut c_char, n: *mut usize, delim: c_int, stream: *mut FILE) -> isize { getdelim(lineptr, n, delim, stream) }
21992#[no_mangle] pub unsafe extern "C" fn __strtod_l(s: *const c_char, end: *mut *mut c_char, loc: locale_t) -> f64 { strtod_l(s, end, loc) }
21993#[no_mangle] pub unsafe extern "C" fn __strtof_l(s: *const c_char, end: *mut *mut c_char, loc: locale_t) -> f32 { strtof_l(s, end, loc) }
21994#[no_mangle] pub unsafe extern "C" fn __strtold_l(s: *const c_char, end: *mut *mut c_char, loc: locale_t) -> f64 { strtold_l(s, end, loc) }
21995
21996#[no_mangle] pub unsafe extern "C" fn __strtol_internal(s: *const c_char, end: *mut *mut c_char, base: c_int) -> c_long { strtol(s, end, base) }
21997#[no_mangle] pub unsafe extern "C" fn __strtoul_internal(s: *const c_char, end: *mut *mut c_char, base: c_int) -> c_ulong { strtoul(s, end, base) }
21998#[no_mangle] pub unsafe extern "C" fn __strtoll_internal(s: *const c_char, end: *mut *mut c_char, base: c_int) -> c_longlong { strtoll(s, end, base) }
21999#[no_mangle] pub unsafe extern "C" fn __strtoull_internal(s: *const c_char, end: *mut *mut c_char, base: c_int) -> c_ulonglong { strtoull(s, end, base) }
22000#[no_mangle] pub unsafe extern "C" fn __strtoimax_internal(s: *const c_char, end: *mut *mut c_char, base: c_int) -> i64 { strtoimax(s, end, base) }
22001#[no_mangle] pub unsafe extern "C" fn __strtoumax_internal(s: *const c_char, end: *mut *mut c_char, base: c_int) -> u64 { strtoumax(s, end, base) }
22002
22003// ============================================================
22004// Resolver (UDP DNS)
22005// ============================================================
22006
22007const MAX_NS: usize = 3;
22008const MAX_SEARCH: usize = 6;
22009const HOST_NOT_FOUND: c_int = 1;
22010const TRY_AGAIN: c_int = 2;
22011const NO_RECOVERY: c_int = 3;
22012const NO_DATA: c_int = 4;
22013
22014static mut NS_COUNT: usize = 0;
22015static mut NS_ADDRS: [u32; MAX_NS] = [0; MAX_NS];
22016static mut SEARCH_COUNT: usize = 0;
22017static mut SEARCH_DOMAINS: [[u8; 256]; MAX_SEARCH] = [[0; 256]; MAX_SEARCH];
22018static mut RESOLV_INITIALIZED: bool = false;
22019
22020#[repr(C)]
22021struct SockAddrIn {
22022    sin_family: u16,
22023    sin_port: u16,
22024    sin_addr: u32,
22025    sin_zero: [u8; 8],
22026}
22027
22028#[repr(C)]
22029struct PollFd {
22030    fd: c_int,
22031    events: i16,
22032    revents: i16,
22033}
22034
22035unsafe fn resolv_skip_ws(line: &[u8], mut i: usize) -> usize {
22036    while i < line.len() && (line[i] == b' ' || line[i] == b'\t') { i += 1; }
22037    i
22038}
22039
22040unsafe fn resolv_token<'a>(line: &'a [u8], mut i: usize) -> (&'a [u8], usize) {
22041    let start = i;
22042    while i < line.len() && line[i] != b' ' && line[i] != b'\t' && line[i] != b'#' { i += 1; }
22043    (&line[start..i], i)
22044}
22045
22046unsafe fn resolv_parse_config() -> c_int {
22047    RESOLV_INITIALIZED = true;
22048    NS_COUNT = 0;
22049    SEARCH_COUNT = 0;
22050    let path = b"/etc/resolv.conf\0";
22051    let fd = crate::open(path.as_ptr() as *const c_char, 0, 0);
22052    if fd < 0 { return -1; }
22053    let mut buf = [0u8; 4096];
22054    let n = crate::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len());
22055    crate::close(fd);
22056    if n <= 0 { return -1; }
22057    let len = n as usize;
22058    let mut i = 0;
22059    while i < len {
22060        let start = i;
22061        while i < len && buf[i] != b'\n' { i += 1; }
22062        let line = &buf[start..i];
22063        i += 1;
22064        let mut j = resolv_skip_ws(line, 0);
22065        if j >= line.len() || line[j] == b'#' { continue; }
22066        let (key, next) = resolv_token(line, j);
22067        j = next;
22068        if key == b"nameserver" {
22069            j = resolv_skip_ws(line, j);
22070            let (tok, _) = resolv_token(line, j);
22071            if !tok.is_empty() && NS_COUNT < MAX_NS {
22072                let mut name = [0u8; 64];
22073                let l = core::cmp::min(tok.len(), 63);
22074                name[..l].copy_from_slice(&tok[..l]);
22075                let addr = crate::inet_addr(name.as_ptr() as *const c_char);
22076                if addr != u32::MAX {
22077                    NS_ADDRS[NS_COUNT] = addr;
22078                    NS_COUNT += 1;
22079                }
22080            }
22081        } else if key == b"search" || key == b"domain" {
22082            loop {
22083                j = resolv_skip_ws(line, j);
22084                if j >= line.len() || line[j] == b'#' { break; }
22085                let (tok, next) = resolv_token(line, j);
22086                j = next;
22087                if tok.is_empty() { break; }
22088                if SEARCH_COUNT < MAX_SEARCH {
22089                    let l = core::cmp::min(tok.len(), 255);
22090                    SEARCH_DOMAINS[SEARCH_COUNT][..l].copy_from_slice(&tok[..l]);
22091                    SEARCH_DOMAINS[SEARCH_COUNT][l] = 0;
22092                    SEARCH_COUNT += 1;
22093                }
22094                if key == b"domain" { break; }
22095            }
22096        }
22097    }
22098    0
22099}
22100
22101#[no_mangle]
22102pub unsafe extern "C" fn res_init() -> c_int {
22103    let _ = resolv_parse_config();
22104    0
22105}
22106
22107#[no_mangle]
22108pub unsafe extern "C" fn res_mkquery(
22109    op: c_int,
22110    dname: *const c_char,
22111    class: c_int,
22112    type_: c_int,
22113    _data: *const u8,
22114    _datalen: c_int,
22115    _newrr: *const u8,
22116    buf: *mut u8,
22117    buflen: c_int,
22118) -> c_int {
22119    if dname.is_null() || buf.is_null() { return -1; }
22120    let mut l = crate::strnlen(dname as *const u8, 255);
22121    if l > 0 && *dname.add(l - 1) == b'.' as c_char { l -= 1; }
22122    if l > 0 && *dname.add(l - 1) == b'.' as c_char { return -1; }
22123    let n = 17 + l + if l != 0 { 1 } else { 0 };
22124    if l > 253 || buflen < n as c_int || op < 0 || op > 15 || class < 0 || class > 255 || type_ < 0 || type_ > 255 {
22125        return -1;
22126    }
22127    let mut q = [0u8; 280];
22128    crate::memset(q.as_mut_ptr() as *mut c_void, 0, n);
22129    q[2] = (op * 8 + 1) as u8;
22130    q[3] = 32;
22131    q[5] = 1;
22132    core::ptr::copy_nonoverlapping(dname as *const u8, q.as_mut_ptr().add(13), l);
22133    let mut i = 13;
22134    while q[i] != 0 {
22135        let mut j = i;
22136        while q[j] != 0 && q[j] != b'.' { j += 1; }
22137        if j - i - 1 > 62 { return -1; }
22138        q[i - 1] = (j - i) as u8;
22139        i = j + 1;
22140    }
22141    q[i + 1] = type_ as u8;
22142    q[i + 3] = class as u8;
22143    let mut ts = timespec { tv_sec: 0, tv_nsec: 0 };
22144    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
22145    let id = (((ts.tv_nsec as u64) + (ts.tv_nsec as u64) / 65536) & 0xffff) as u16;
22146    q[0] = (id >> 8) as u8;
22147    q[1] = id as u8;
22148    core::ptr::copy_nonoverlapping(q.as_ptr(), buf, n);
22149    n as c_int
22150}
22151
22152unsafe fn res_send_inner(msg: *const u8, msglen: c_int, answer: *mut u8, anslen: c_int) -> c_int {
22153    if msg.is_null() || answer.is_null() || msglen < 12 || anslen < 12 { return -1; }
22154    if !RESOLV_INITIALIZED { let _ = resolv_parse_config(); }
22155    if NS_COUNT == 0 {
22156        h_errno = TRY_AGAIN;
22157        return -1;
22158    }
22159    for n in 0..NS_COUNT {
22160        let fd = crate::socket(AF_INET, SOCK_DGRAM, 0);
22161        if fd < 0 { continue; }
22162        let sa = SockAddrIn {
22163            sin_family: AF_INET as u16,
22164            sin_port: 53u16.to_be(),
22165            sin_addr: NS_ADDRS[n],
22166            sin_zero: [0; 8],
22167        };
22168        let sent = crate::sendto(fd, msg as *const c_void, msglen as usize, 0, &sa as *const SockAddrIn as *const crate::sockaddr, 16);
22169        if sent != msglen as isize {
22170            crate::close(fd);
22171            continue;
22172        }
22173        let mut pfd = PollFd { fd, events: 1, revents: 0 };
22174        let pr = crate::poll(&mut pfd as *mut PollFd as *mut c_void, 1, 5000);
22175        if pr <= 0 {
22176            crate::close(fd);
22177            continue;
22178        }
22179        let r = crate::recvfrom(fd, answer as *mut c_void, anslen as usize, 0, core::ptr::null_mut(), core::ptr::null_mut());
22180        crate::close(fd);
22181        if r >= 12 {
22182            let id_ok = *answer == *msg && *answer.add(1) == *msg.add(1);
22183            let qr = (*answer.add(2) & 0x80) != 0;
22184            if id_ok && qr {
22185                return r as c_int;
22186            }
22187        }
22188    }
22189    h_errno = TRY_AGAIN;
22190    -1
22191}
22192
22193#[no_mangle]
22194pub unsafe extern "C" fn res_send(msg: *const u8, msglen: c_int, answer: *mut u8, anslen: c_int) -> c_int {
22195    if anslen < 512 {
22196        let mut buf = [0u8; 512];
22197        let r = res_send_inner(msg, msglen, buf.as_mut_ptr(), 512);
22198        if r >= 0 {
22199            let copy = core::cmp::min(r, anslen) as usize;
22200            if copy > 0 { core::ptr::copy_nonoverlapping(buf.as_ptr(), answer, copy); }
22201        }
22202        return r;
22203    }
22204    res_send_inner(msg, msglen, answer, anslen)
22205}
22206
22207#[no_mangle]
22208pub unsafe extern "C" fn res_query(
22209    dname: *const c_char,
22210    class: c_int,
22211    type_: c_int,
22212    answer: *mut u8,
22213    anslen: c_int,
22214) -> c_int {
22215    let mut q = [0u8; 280];
22216    let ql = res_mkquery(0, dname, class, type_, core::ptr::null(), 0, core::ptr::null(), q.as_mut_ptr(), q.len() as c_int);
22217    if ql < 0 { return ql; }
22218    let r = res_send(q.as_ptr(), ql, answer, anslen);
22219    if r < 12 {
22220        h_errno = TRY_AGAIN;
22221        return -1;
22222    }
22223    let rcode = answer.add(3).read() & 0x0f;
22224    if rcode == 3 {
22225        h_errno = HOST_NOT_FOUND;
22226        return -1;
22227    }
22228    if rcode == 0 && *answer.add(6) == 0 && *answer.add(7) == 0 {
22229        h_errno = NO_DATA;
22230        return -1;
22231    }
22232    if rcode != 0 {
22233        h_errno = NO_RECOVERY;
22234        return -1;
22235    }
22236    r
22237}
22238
22239#[no_mangle]
22240pub unsafe extern "C" fn res_querydomain(
22241    name: *const c_char,
22242    domain: *const c_char,
22243    class: c_int,
22244    type_: c_int,
22245    answer: *mut u8,
22246    anslen: c_int,
22247) -> c_int {
22248    if domain.is_null() || *domain == 0 { return res_query(name, class, type_, answer, anslen); }
22249    let mut buf = [0u8; 512];
22250    let nl = crate::strlen(name);
22251    let dl = crate::strlen(domain);
22252    if nl + 1 + dl >= buf.len() { return -1; }
22253    core::ptr::copy_nonoverlapping(name, buf.as_mut_ptr() as *mut c_char, nl);
22254    buf[nl] = b'.';
22255    core::ptr::copy_nonoverlapping(domain, buf.as_mut_ptr().add(nl + 1) as *mut c_char, dl);
22256    buf[nl + 1 + dl] = 0;
22257    res_query(buf.as_ptr() as *const c_char, class, type_, answer, anslen)
22258}
22259
22260#[no_mangle]
22261pub unsafe extern "C" fn res_search(
22262    name: *const c_char,
22263    class: c_int,
22264    type_: c_int,
22265    answer: *mut u8,
22266    anslen: c_int,
22267) -> c_int {
22268    if name.is_null() { return -1; }
22269    if !RESOLV_INITIALIZED { let _ = resolv_parse_config(); }
22270    let len = crate::strlen(name);
22271    let mut dots = 0;
22272    for i in 0..len {
22273        if *name.add(i) == b'.' as c_char { dots += 1; }
22274    }
22275    let trailing_dot = len > 0 && *name.add(len - 1) == b'.' as c_char;
22276    if trailing_dot || dots >= 1 {
22277        let r = res_query(name, class, type_, answer, anslen);
22278        if r >= 0 { return r; }
22279        if trailing_dot { return -1; }
22280    }
22281    for i in 0..SEARCH_COUNT {
22282        let dom = SEARCH_DOMAINS[i].as_ptr() as *const c_char;
22283        let r = res_querydomain(name, dom, class, type_, answer, anslen);
22284        if r >= 0 { return r; }
22285        if h_errno != HOST_NOT_FOUND && h_errno != NO_DATA { return -1; }
22286    }
22287    if dots == 0 {
22288        return res_query(name, class, type_, answer, anslen);
22289    }
22290    -1
22291}
22292
22293// ============================================================
22294// Host and address resolution
22295// ============================================================
22296
22297#[repr(C)]
22298pub struct HostEnt {
22299    pub h_name: *mut c_char,
22300    pub h_aliases: *mut *mut c_char,
22301    pub h_addrtype: c_int,
22302    pub h_length: c_int,
22303    pub h_addr_list: *mut *mut c_char,
22304}
22305
22306#[repr(C)]
22307pub struct AddrInfo {
22308    pub ai_flags: c_int,
22309    pub ai_family: c_int,
22310    pub ai_socktype: c_int,
22311    pub ai_protocol: c_int,
22312    pub ai_addrlen: u32,
22313    pub ai_addr: *mut c_void,
22314    pub ai_canonname: *mut c_char,
22315    pub ai_next: *mut AddrInfo,
22316}
22317
22318static mut HOST_ENT: HostEnt = HostEnt {
22319    h_name: core::ptr::null_mut(),
22320    h_aliases: core::ptr::null_mut(),
22321    h_addrtype: 0,
22322    h_length: 0,
22323    h_addr_list: core::ptr::null_mut(),
22324};
22325static mut HOST_NAME: [c_char; 256] = [0; 256];
22326static mut HOST_ALIASES: [*mut c_char; 8] = [core::ptr::null_mut(); 8];
22327static mut HOST_ADDR: [u8; 16] = [0; 16];
22328static mut HOST_ADDR_PTRS: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
22329
22330unsafe fn dns_skip_name(p: *const u8, end: *const u8) -> *const u8 {
22331    let mut q = p;
22332    while q < end {
22333        let c = *q;
22334        if c == 0 { return q.add(1); }
22335        if c & 0xc0 == 0xc0 { return q.add(2); }
22336        q = q.add(1 + c as usize);
22337    }
22338    end
22339}
22340
22341unsafe fn dns_read_u16(p: *const u8) -> u16 {
22342    ((*p as u16) << 8) | *p.add(1) as u16
22343}
22344
22345unsafe fn dns_expand_name(p: *const u8, msg: *const u8, out: *mut c_char, outlen: usize) -> bool {
22346    let mut q = p;
22347    let mut o = 0usize;
22348    let mut jumps = 0;
22349    loop {
22350        let c = *q;
22351        if c == 0 {
22352            if o < outlen { *out.add(o) = 0; }
22353            return true;
22354        }
22355        if c & 0xc0 == 0xc0 {
22356            let off = (((c & 0x3f) as usize) << 8) | *q.add(1) as usize;
22357            q = msg.add(off);
22358            jumps += 1;
22359            if jumps > 16 { return false; }
22360            continue;
22361        }
22362        let l = c as usize;
22363        if l > 63 { return false; }
22364        if o + l + 1 >= outlen { return false; }
22365        core::ptr::copy_nonoverlapping(q.add(1), out.add(o) as *mut u8, l);
22366        o += l;
22367        *out.add(o) = b'.' as c_char;
22368        o += 1;
22369        q = q.add(1 + l);
22370    }
22371}
22372
22373unsafe fn host_from_answer(answer: *const u8, len: c_int, af: c_int) -> *mut HostEnt {
22374    if len < 12 { return core::ptr::null_mut(); }
22375    let end = answer.add(len as usize);
22376    let qd = dns_read_u16(answer.add(4)) as usize;
22377    let an = dns_read_u16(answer.add(6)) as usize;
22378    let mut p = answer.add(12);
22379    for _ in 0..qd {
22380        p = dns_skip_name(p, end);
22381        p = p.add(4);
22382    }
22383    let want_type: u16 = if af == AF_INET6 { 28 } else { 1 };
22384    let want_len = if af == AF_INET6 { 16 } else { 4 };
22385    for _ in 0..an {
22386        p = dns_skip_name(p, end);
22387        if p.add(10) > end { break; }
22388        let typ = dns_read_u16(p);
22389        let class = dns_read_u16(p.add(2));
22390        let rdlen = dns_read_u16(p.add(8)) as usize;
22391        let rdata = p.add(10);
22392        if rdata.add(rdlen) > end { break; }
22393        if typ == want_type && class == 1 && rdlen == want_len {
22394            core::ptr::copy_nonoverlapping(rdata, HOST_ADDR.as_mut_ptr(), want_len);
22395            HOST_ENT.h_addrtype = af;
22396            HOST_ENT.h_length = want_len as c_int;
22397            HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
22398            HOST_ADDR_PTRS[1] = core::ptr::null_mut();
22399            HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
22400            HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
22401            HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
22402            h_errno = 0;
22403            return &raw mut HOST_ENT;
22404        }
22405        p = rdata.add(rdlen);
22406    }
22407    core::ptr::null_mut()
22408}
22409
22410#[no_mangle]
22411pub unsafe extern "C" fn gethostbyname(name: *const c_char) -> *mut HostEnt {
22412    gethostbyname2(name, AF_INET)
22413}
22414
22415#[no_mangle]
22416pub unsafe extern "C" fn gethostbyname2(name: *const c_char, af: c_int) -> *mut HostEnt {
22417    if name.is_null() { h_errno = HOST_NOT_FOUND; return core::ptr::null_mut(); }
22418    let mut addr = [0u8; 16];
22419    let addrlen = if af == AF_INET6 { 16 } else { 4 };
22420    if inet_pton(af, name, addr.as_mut_ptr() as *mut c_void) == 1 {
22421        core::ptr::copy_nonoverlapping(addr.as_ptr(), HOST_ADDR.as_mut_ptr(), addrlen);
22422        let n = crate::strlen(name);
22423        let l = core::cmp::min(n, 255);
22424        core::ptr::copy_nonoverlapping(name, HOST_NAME.as_mut_ptr(), l);
22425        HOST_NAME[l] = 0;
22426        HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
22427        HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
22428        HOST_ENT.h_addrtype = af;
22429        HOST_ENT.h_length = addrlen as c_int;
22430        HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
22431        HOST_ADDR_PTRS[1] = core::ptr::null_mut();
22432        HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
22433        h_errno = 0;
22434        return &raw mut HOST_ENT;
22435    }
22436    let mut answer = [0u8; 512];
22437    let qtype = if af == AF_INET6 { 28 } else { 1 };
22438    let r = res_query(name, 1, qtype, answer.as_mut_ptr(), answer.len() as c_int);
22439    if r < 0 {
22440        if h_errno == 0 { h_errno = TRY_AGAIN; }
22441        return core::ptr::null_mut();
22442    }
22443    let ent = host_from_answer(answer.as_ptr(), r, af);
22444    if !ent.is_null() {
22445        let n = crate::strlen(name);
22446        let l = core::cmp::min(n, 255);
22447        core::ptr::copy_nonoverlapping(name, HOST_NAME.as_mut_ptr(), l);
22448        HOST_NAME[l] = 0;
22449    } else {
22450        h_errno = HOST_NOT_FOUND;
22451    }
22452    ent
22453}
22454
22455#[no_mangle]
22456pub unsafe extern "C" fn gethostbyaddr(addr: *const c_void, len: u32, type_: c_int) -> *mut HostEnt {
22457    // musl implements gethostbyaddr() on top of getnameinfo(), so /etc/hosts
22458    // and the DNS reverse path behave identically for both APIs.
22459    let (addr_len, salen) = match type_ {
22460        AF_INET => (4usize, 16u32),
22461        AF_INET6 => (16usize, 28u32),
22462        _ => {
22463            h_errno = HOST_NOT_FOUND;
22464            return core::ptr::null_mut();
22465        }
22466    };
22467    if addr.is_null() || len as usize != addr_len {
22468        h_errno = HOST_NOT_FOUND;
22469        return core::ptr::null_mut();
22470    }
22471    let mut sa = [0u8; 28];
22472    *(sa.as_mut_ptr() as *mut u16) = type_ as u16;
22473    if type_ == AF_INET {
22474        core::ptr::copy_nonoverlapping(addr as *const u8, sa.as_mut_ptr().add(4), 4);
22475    } else {
22476        core::ptr::copy_nonoverlapping(addr as *const u8, sa.as_mut_ptr().add(8), 16);
22477    }
22478    let mut name = [0 as c_char; 256];
22479    let rc = getnameinfo(
22480        sa.as_ptr() as *const c_void,
22481        salen,
22482        name.as_mut_ptr(),
22483        name.len() as u32,
22484        core::ptr::null_mut(),
22485        0,
22486        0,
22487    );
22488    if rc != 0 {
22489        h_errno = match rc {
22490            EAI_AGAIN_V => TRY_AGAIN,
22491            EAI_NONAME_V => HOST_NOT_FOUND,
22492            _ => NO_RECOVERY,
22493        };
22494        return core::ptr::null_mut();
22495    }
22496    let l = crate::strlen(name.as_ptr());
22497    if l >= HOST_NAME.len() {
22498        h_errno = NO_RECOVERY;
22499        return core::ptr::null_mut();
22500    }
22501    core::ptr::copy_nonoverlapping(name.as_ptr(), HOST_NAME.as_mut_ptr(), l + 1);
22502    core::ptr::copy_nonoverlapping(addr as *const u8, HOST_ADDR.as_mut_ptr(), addr_len);
22503    HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
22504    HOST_ALIASES[0] = HOST_NAME.as_mut_ptr();
22505    HOST_ALIASES[1] = core::ptr::null_mut();
22506    HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
22507    HOST_ENT.h_addrtype = type_;
22508    HOST_ENT.h_length = addr_len as c_int;
22509    HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
22510    HOST_ADDR_PTRS[1] = core::ptr::null_mut();
22511    HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
22512    h_errno = 0;
22513    &raw mut HOST_ENT
22514}
22515
22516// ============================================================
22517// Legacy syscall/stdio/signal compatibility
22518// ============================================================
22519
22520#[inline]
22521fn sysno(x86_64: i64, generic: i64) -> i64 {
22522    if cfg!(target_arch = "x86_64") { x86_64 } else { generic }
22523}
22524
22525#[no_mangle]
22526pub unsafe extern "C" fn settimeofday(tv: *const c_void, tz: *const c_void) -> c_int {
22527    let r = <Arch as Syscalls>::syscall2(sysno(164, 170), tv as i64, tz as i64);
22528    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22529}
22530
22531#[no_mangle]
22532pub unsafe extern "C" fn stime(t: *const i64) -> c_int {
22533    if t.is_null() { ERRNO!() = EINVAL; return -1; }
22534    let tv = timeval { tv_sec: *t, tv_usec: 0 };
22535    settimeofday(&tv as *const timeval as *const c_void, core::ptr::null())
22536}
22537
22538#[no_mangle]
22539pub unsafe extern "C" fn times(buf: *mut c_void) -> c_long {
22540    let r = <Arch as Syscalls>::syscall1(sysno(100, 153), buf as i64);
22541    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_long }
22542}
22543
22544#[no_mangle]
22545pub unsafe extern "C" fn splice(fd_in: c_int, off_in: *mut i64, fd_out: c_int, off_out: *mut i64, len: usize, flags: u32) -> isize {
22546    let r = <Arch as Syscalls>::syscall6(sysno(275, 76), fd_in as i64, off_in as i64, fd_out as i64, off_out as i64, len as i64, flags as i64);
22547    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22548}
22549
22550#[no_mangle]
22551pub unsafe extern "C" fn tee(fd_in: c_int, fd_out: c_int, len: usize, flags: u32) -> isize {
22552    let r = <Arch as Syscalls>::syscall4(sysno(276, 77), fd_in as i64, fd_out as i64, len as i64, flags as i64);
22553    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22554}
22555
22556#[no_mangle]
22557pub unsafe extern "C" fn statx(dirfd: c_int, path: *const c_char, flags: c_int, mask: u32, buf: *mut c_void) -> c_int {
22558    let r = <Arch as Syscalls>::syscall5(sysno(332, 291), dirfd as i64, path as i64, flags as i64, mask as i64, buf as i64);
22559    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22560}
22561
22562#[no_mangle]
22563pub unsafe extern "C" fn setns(fd: c_int, nstype: c_int) -> c_int {
22564    let r = <Arch as Syscalls>::syscall2(SYS_SETNS, fd as i64, nstype as i64);
22565    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22566}
22567
22568#[no_mangle]
22569pub unsafe extern "C" fn setfsuid(uid: u32) -> c_int {
22570    <Arch as Syscalls>::syscall1(sysno(122, 151), uid as i64) as c_int
22571}
22572
22573#[no_mangle]
22574pub unsafe extern "C" fn setfsgid(gid: u32) -> c_int {
22575    <Arch as Syscalls>::syscall1(sysno(123, 152), gid as i64) as c_int
22576}
22577
22578#[no_mangle]
22579pub unsafe extern "C" fn setregid(rgid: u32, egid: u32) -> c_int {
22580    let r = <Arch as Syscalls>::syscall2(sysno(114, 143), rgid as i64, egid as i64);
22581    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22582}
22583
22584#[no_mangle]
22585pub unsafe extern "C" fn process_vm_readv(pid: c_int, local: *const c_void, liovcnt: usize, remote: *const c_void, riovcnt: usize, flags: u64) -> isize {
22586    let r = <Arch as Syscalls>::syscall6(sysno(310, 270), pid as i64, local as i64, liovcnt as i64, remote as i64, riovcnt as i64, flags as i64);
22587    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22588}
22589
22590#[no_mangle]
22591pub unsafe extern "C" fn process_vm_writev(pid: c_int, local: *const c_void, liovcnt: usize, remote: *const c_void, riovcnt: usize, flags: u64) -> isize {
22592    let r = <Arch as Syscalls>::syscall6(sysno(311, 271), pid as i64, local as i64, liovcnt as i64, remote as i64, riovcnt as i64, flags as i64);
22593    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22594}
22595
22596#[no_mangle]
22597pub unsafe extern "C" fn tcgetwinsize(fd: c_int, ws: *mut c_void) -> c_int {
22598    if fd < 0 || ws.is_null() { ERRNO!() = EINVAL; return -1; }
22599    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5413, ws as i64);
22600    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22601}
22602
22603#[no_mangle]
22604pub unsafe extern "C" fn tcsetwinsize(fd: c_int, ws: *const c_void) -> c_int {
22605    if fd < 0 || ws.is_null() { ERRNO!() = EINVAL; return -1; }
22606    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5414, ws as i64);
22607    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22608}
22609
22610#[no_mangle]
22611pub unsafe extern "C" fn sockatmark(fd: c_int) -> c_int {
22612    let mut at: c_int = 0;
22613    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x8905, &mut at as *mut c_int as i64);
22614    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { at }
22615}
22616
22617#[no_mangle]
22618pub unsafe extern "C" fn isastream(fd: c_int) -> c_int {
22619    let mut buf = [0u8; 64];
22620    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5401, buf.as_mut_ptr() as i64);
22621    if r < 0 { ERRNO!() = (-r) as c_int; 0 } else { 1 }
22622}
22623
22624#[no_mangle]
22625pub unsafe extern "C" fn posix_madvise(addr: *mut c_void, len: usize, advice: c_int) -> c_int {
22626    madvise(addr as *mut u8, len, advice)
22627}
22628
22629#[no_mangle]
22630pub unsafe extern "C" fn secure_getenv(name: *const c_char) -> *mut c_char {
22631    if getauxval(23) != 0 { return core::ptr::null_mut(); }
22632    getenv(name)
22633}
22634
22635#[no_mangle]
22636pub unsafe extern "C" fn sigandset(dest: *mut c_ulong, left: *const c_ulong, right: *const c_ulong) -> c_int {
22637    if dest.is_null() || left.is_null() || right.is_null() { return -1; }
22638    *dest = *left & *right;
22639    0
22640}
22641
22642#[no_mangle]
22643pub unsafe extern "C" fn sigorset(dest: *mut c_ulong, left: *const c_ulong, right: *const c_ulong) -> c_int {
22644    if dest.is_null() || left.is_null() || right.is_null() { return -1; }
22645    *dest = *left | *right;
22646    0
22647}
22648
22649#[no_mangle]
22650pub unsafe extern "C" fn sigisemptyset(set: *const c_ulong) -> c_int {
22651    if set.is_null() { return 1; }
22652    (*set == 0) as c_int
22653}
22654
22655#[no_mangle]
22656pub unsafe extern "C" fn sighold(sig: c_int) -> c_int {
22657    let set: c_ulong = 1u64 << (sig - 1) as u32;
22658    sigprocmask(0, &set, core::ptr::null_mut());
22659    0
22660}
22661
22662#[no_mangle]
22663pub unsafe extern "C" fn sigignore(sig: c_int) -> c_int {
22664    let _ = signal(sig, 1);
22665    0
22666}
22667
22668#[no_mangle]
22669pub unsafe extern "C" fn sigrelse(sig: c_int) -> c_int {
22670    let set: c_ulong = 1u64 << (sig - 1) as u32;
22671    sigprocmask(1, &set, core::ptr::null_mut());
22672    0
22673}
22674
22675#[no_mangle]
22676pub unsafe extern "C" fn siginterrupt(sig: c_int, flag: c_int) -> c_int {
22677    let mut sa: sigaction = core::mem::zeroed();
22678    if sigaction(sig, core::ptr::null(), &mut sa) != 0 { return -1; }
22679    if flag != 0 { sa.sa_flags &= !(SA_RESTART as c_int); } else { sa.sa_flags |= SA_RESTART as c_int; }
22680    sigaction(sig, &sa, core::ptr::null_mut())
22681}
22682
22683#[no_mangle]
22684pub unsafe extern "C" fn sigpause(sig: c_int) -> c_int {
22685    let set: c_ulong = 1u64 << (sig - 1) as u32;
22686    sigsuspend(&set)
22687}
22688
22689#[no_mangle]
22690pub unsafe extern "C" fn semtimedop(semid: c_int, sops: *mut c_void, nsops: usize, timeout: *const timespec) -> c_int {
22691    let r = <Arch as Syscalls>::syscall4(sysno(220, 192), semid as i64, sops as i64, nsops as i64, timeout as i64);
22692    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
22693}
22694
22695#[no_mangle]
22696pub unsafe extern "C" fn wait3(status: *mut c_int, options: c_int, rusage: *mut c_void) -> i32 {
22697    wait4(-1, status, options, rusage) as i32
22698}
22699
22700#[no_mangle]
22701pub unsafe extern "C" fn tempnam(dir: *const c_char, pfx: *const c_char) -> *mut c_char {
22702    let mut path = [0 as c_char; 256];
22703    let mut i = 0;
22704    if !dir.is_null() {
22705        while *dir.add(i) != 0 && i < 200 { path[i] = *dir.add(i); i += 1; }
22706        if i > 0 && path[i-1] != b'/' as c_char { path[i] = b'/' as c_char; i += 1; }
22707    } else {
22708        for &c in b"/tmp/" { path[i] = c as c_char; i += 1; }
22709    }
22710    if !pfx.is_null() {
22711        let mut j = 0;
22712        while *pfx.add(j) != 0 && i < 220 { path[i] = *pfx.add(j); i += 1; j += 1; }
22713    }
22714    for &c in b"XXXXXX" { path[i] = c as c_char; i += 1; }
22715    path[i] = 0;
22716    let fd = mkstemp(path.as_mut_ptr());
22717    if fd < 0 { return core::ptr::null_mut(); }
22718    close(fd);
22719    unlink(path.as_ptr());
22720    let n = strlen(path.as_ptr());
22721    let out = malloc(n + 1) as *mut c_char;
22722    if out.is_null() { return core::ptr::null_mut(); }
22723    core::ptr::copy_nonoverlapping(path.as_ptr(), out, n + 1);
22724    out
22725}
22726
22727#[no_mangle]
22728pub unsafe extern "C" fn putwc(c: u32, f: *mut c_void) -> u32 {
22729    fputwc(c as c_int, f as *mut FILE) as u32
22730}
22731
22732#[no_mangle]
22733pub unsafe extern "C" fn __uflow(f: *mut c_void) -> c_int {
22734    fgetc(f as *mut FILE)
22735}
22736
22737#[no_mangle]
22738pub unsafe extern "C" fn __xmknod(_ver: c_int, path: *const c_char, mode: c_uint, dev: u64) -> c_int {
22739    mknod(path, mode, dev)
22740}
22741
22742#[no_mangle]
22743pub unsafe extern "C" fn __xmknodat(_ver: c_int, dirfd: c_int, path: *const c_char, mode: c_uint, dev: u64) -> c_int {
22744    mknodat(dirfd, path, mode, dev)
22745}
22746
22747#[no_mangle]
22748pub unsafe extern "C" fn name_to_handle_at(dirfd: c_int, path: *const c_char, handle: *mut c_void, mount_id: *mut c_int, flags: c_int) -> c_int {
22749    let r = <Arch as Syscalls>::syscall5(sysno(303, 264), dirfd as i64, path as i64, handle as i64, mount_id as i64, flags as i64);
22750    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22751}
22752
22753#[no_mangle]
22754pub unsafe extern "C" fn open_by_handle_at(mount_fd: c_int, handle: *mut c_void, flags: c_int) -> c_int {
22755    let r = <Arch as Syscalls>::syscall3(sysno(304, 265), mount_fd as i64, handle as i64, flags as i64);
22756    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
22757}
22758
22759#[no_mangle]
22760pub unsafe extern "C" fn dn_skipname(comp: *const u8, eom: *const u8) -> c_int {
22761    let p = dns_skip_name(comp, eom);
22762    if p <= eom { (p as isize - comp as isize) as c_int } else { -1 }
22763}
22764
22765#[no_mangle]
22766pub unsafe extern "C" fn dn_comp(exp: *const c_char, dst: *mut u8, dstsiz: c_int, _dnptrs: *mut *mut u8, _lastdnptr: *mut *mut u8) -> c_int {
22767    if exp.is_null() || dst.is_null() || dstsiz <= 0 { return -1; }
22768    let mut o = 0usize;
22769    let mut p = exp;
22770    loop {
22771        let start = p;
22772        while *p != 0 && *p != b'.' as c_char { p = p.add(1); }
22773        let l = p as usize - start as usize;
22774        if l > 63 || o + l + 2 > dstsiz as usize { return -1; }
22775        *dst.add(o) = l as u8; o += 1;
22776        core::ptr::copy_nonoverlapping(start as *const u8, dst.add(o), l);
22777        o += l;
22778        if *p == 0 { break; }
22779        p = p.add(1);
22780    }
22781    if o + 1 > dstsiz as usize { return -1; }
22782    *dst.add(o) = 0;
22783    (o + 1) as c_int
22784}
22785
22786// ============================================================
22787// Shadow database
22788// ============================================================
22789
22790#[repr(C)]
22791#[derive(Copy, Clone)]
22792pub struct Spwd {
22793    pub sp_namp: *mut c_char,
22794    pub sp_pwdp: *mut c_char,
22795    pub sp_lstchg: c_long,
22796    pub sp_min: c_long,
22797    pub sp_max: c_long,
22798    pub sp_warn: c_long,
22799    pub sp_inact: c_long,
22800    pub sp_expire: c_long,
22801    pub sp_flag: c_ulong,
22802}
22803
22804static mut SPWD_ENT: Spwd = Spwd {
22805    sp_namp: core::ptr::null_mut(), sp_pwdp: core::ptr::null_mut(),
22806    sp_lstchg: 0, sp_min: 0, sp_max: 0, sp_warn: 0, sp_inact: 0,
22807    sp_expire: 0, sp_flag: 0,
22808};
22809static mut SPWD_BUF: [c_char; 1024] = [0; 1024];
22810static mut SPWD_FILE: *mut FILE = core::ptr::null_mut();
22811
22812unsafe fn parse_spwd(line: *const c_char, ent: *mut Spwd, buf: *mut c_char, buflen: usize) -> bool {
22813    let mut src = line;
22814    let mut o = 0usize;
22815    let mut fields: [*mut c_char; 9] = [core::ptr::null_mut(); 9];
22816    let mut n = 0usize;
22817    while n < 9 {
22818        let start = o;
22819        while *src != 0 && *src != b':' as c_char {
22820            if o + 1 >= buflen { return false; }
22821            *buf.add(o) = *src;
22822            o += 1;
22823            src = src.add(1);
22824        }
22825        *buf.add(o) = 0;
22826        o += 1;
22827        fields[n] = buf.add(start);
22828        n += 1;
22829        if *src == 0 { break; }
22830        src = src.add(1);
22831    }
22832    if n < 9 { return false; }
22833    (*ent).sp_namp = fields[0];
22834    (*ent).sp_pwdp = fields[1];
22835    (*ent).sp_lstchg = crate::strtol(fields[2], core::ptr::null_mut(), 10) as c_long;
22836    (*ent).sp_min = crate::strtol(fields[3], core::ptr::null_mut(), 10) as c_long;
22837    (*ent).sp_max = crate::strtol(fields[4], core::ptr::null_mut(), 10) as c_long;
22838    (*ent).sp_warn = crate::strtol(fields[5], core::ptr::null_mut(), 10) as c_long;
22839    (*ent).sp_inact = crate::strtol(fields[6], core::ptr::null_mut(), 10) as c_long;
22840    (*ent).sp_expire = crate::strtol(fields[7], core::ptr::null_mut(), 10) as c_long;
22841    (*ent).sp_flag = crate::strtoul(fields[8], core::ptr::null_mut(), 10) as c_ulong;
22842    true
22843}
22844
22845#[no_mangle]
22846pub unsafe extern "C" fn setspent() {
22847    endspent();
22848    SPWD_FILE = crate::fopen(b"/etc/shadow\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
22849}
22850
22851#[no_mangle]
22852pub unsafe extern "C" fn endspent() {
22853    if !SPWD_FILE.is_null() { crate::fclose(SPWD_FILE); SPWD_FILE = core::ptr::null_mut(); }
22854}
22855
22856#[no_mangle]
22857pub unsafe extern "C" fn getspent() -> *mut Spwd {
22858    if SPWD_FILE.is_null() { setspent(); if SPWD_FILE.is_null() { return core::ptr::null_mut(); } }
22859    let mut line = [0 as c_char; 1024];
22860    loop {
22861        if crate::fgets(line.as_mut_ptr(), 1024, SPWD_FILE).is_null() { return core::ptr::null_mut(); }
22862        if parse_spwd(line.as_ptr(), &raw mut SPWD_ENT, SPWD_BUF.as_mut_ptr(), SPWD_BUF.len()) {
22863            return &raw mut SPWD_ENT;
22864        }
22865    }
22866}
22867
22868#[no_mangle]
22869pub unsafe extern "C" fn fgetspent(f: *mut FILE) -> *mut Spwd {
22870    if f.is_null() { return core::ptr::null_mut(); }
22871    let mut line = [0 as c_char; 1024];
22872    loop {
22873        if crate::fgets(line.as_mut_ptr(), 1024, f).is_null() { return core::ptr::null_mut(); }
22874        if parse_spwd(line.as_ptr(), &raw mut SPWD_ENT, SPWD_BUF.as_mut_ptr(), SPWD_BUF.len()) {
22875            return &raw mut SPWD_ENT;
22876        }
22877    }
22878}
22879
22880#[no_mangle]
22881pub unsafe extern "C" fn getspnam(name: *const c_char) -> *mut Spwd {
22882    if name.is_null() { return core::ptr::null_mut(); }
22883    setspent();
22884    loop {
22885        let sp = getspent();
22886        if sp.is_null() { break; }
22887        if crate::strcmp((*sp).sp_namp as *const u8, name as *const u8) == 0 { endspent(); return sp; }
22888    }
22889    endspent();
22890    core::ptr::null_mut()
22891}
22892
22893#[no_mangle]
22894pub unsafe extern "C" fn getspnam_r(name: *const c_char, sp: *mut Spwd, _buf: *mut c_char, _buflen: usize, result: *mut *mut Spwd) -> c_int {
22895    if result.is_null() { return EINVAL; }
22896    let p = getspnam(name);
22897    if p.is_null() { *result = core::ptr::null_mut(); 0 } else { *sp = *p; *result = sp; 0 }
22898}
22899
22900#[no_mangle]
22901pub unsafe extern "C" fn putspent(sp: *const Spwd, f: *mut FILE) -> c_int {
22902    if sp.is_null() || f.is_null() { return -1; }
22903    crate::fprintf(f, b"%s:%s:%ld:%ld:%ld:%ld:%ld:%ld:%lu\\n\0".as_ptr() as *const c_char,
22904        (*sp).sp_namp, (*sp).sp_pwdp, (*sp).sp_lstchg, (*sp).sp_min, (*sp).sp_max,
22905        (*sp).sp_warn, (*sp).sp_inact, (*sp).sp_expire, (*sp).sp_flag)
22906}
22907
22908#[no_mangle]
22909pub unsafe extern "C" fn getgrouplist(user: *const c_char, group: u32, groups: *mut u32, ngroups: *mut i32) -> c_int {
22910    if user.is_null() || groups.is_null() || ngroups.is_null() { return -1; }
22911    let max = *ngroups as usize;
22912    let mut n = 0usize;
22913    if n < max { *groups.add(n) = group; }
22914    n += 1;
22915    setgrent();
22916    loop {
22917        let g = getgrent();
22918        if g.is_null() { break; }
22919        if (*g).gr_gid == group { continue; }
22920        let mut found = false;
22921        let mut i = 0;
22922        while !(*(*g).gr_mem.add(i)).is_null() {
22923            if crate::strcmp(*(*g).gr_mem.add(i) as *const u8, user as *const u8) == 0 {
22924                found = true;
22925                break;
22926            }
22927            i += 1;
22928        }
22929        if found {
22930            if n < max { *groups.add(n) = (*g).gr_gid; }
22931            n += 1;
22932        }
22933    }
22934    endgrent();
22935    if n > max { *ngroups = n as i32; return -1; }
22936    *ngroups = n as i32;
22937    n as c_int
22938}