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// libc.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
2728static mut CREATE_THREAD_TLS_IMPL: usize = 0;
2729static mut INIT_THREAD_TLS_IMPL: usize = 0;
2730static mut TLS_BLOCK_SIZE_IMPL: usize = 0;
2731static mut TLS_BASE_OFFSET_IMPL: usize = 0;
2732
2733/// Called by the dynamic loader once it is self-relocated.  A static
2734/// executable does not call this and keeps the fallback behaviour.
2735#[no_mangle]
2736pub unsafe extern "C" fn __keel_set_thread_tls_hooks(
2737    create: usize,
2738    init: usize,
2739    block_size: usize,
2740    base_offset: usize,
2741) {
2742    CREATE_THREAD_TLS_IMPL = create;
2743    INIT_THREAD_TLS_IMPL = init;
2744    TLS_BLOCK_SIZE_IMPL = block_size;
2745    TLS_BASE_OFFSET_IMPL = base_offset;
2746}
2747
2748#[inline(never)]
2749#[linkage = "weak"]
2750#[no_mangle]
2751pub extern "C" fn __keel_create_thread_tls() -> *mut u8 {
2752    let f = unsafe { CREATE_THREAD_TLS_IMPL };
2753    if f == 0 {
2754        return core::ptr::null_mut();
2755    }
2756    let f: unsafe extern "C" fn() -> *mut u8 = unsafe { core::mem::transmute(f) };
2757    unsafe { f() }
2758}
2759
2760#[inline(never)]
2761#[linkage = "weak"]
2762#[no_mangle]
2763pub unsafe extern "C" fn __keel_init_thread_tls_at(block: *mut u8) -> *mut u8 {
2764    let f = INIT_THREAD_TLS_IMPL;
2765    if f == 0 {
2766        return core::ptr::null_mut();
2767    }
2768    let f: unsafe extern "C" fn(*mut u8) -> *mut u8 = core::mem::transmute(f);
2769    f(block)
2770}
2771
2772#[inline(never)]
2773#[linkage = "weak"]
2774#[no_mangle]
2775pub extern "C" fn __keel_tls_block_size() -> usize {
2776    let f = unsafe { TLS_BLOCK_SIZE_IMPL };
2777    if f == 0 {
2778        return 0;
2779    }
2780    let f: extern "C" fn() -> usize = unsafe { core::mem::transmute(f) };
2781    f()
2782}
2783
2784#[inline(never)]
2785#[linkage = "weak"]
2786#[no_mangle]
2787pub extern "C" fn __keel_tls_base_offset() -> usize {
2788    let f = unsafe { TLS_BASE_OFFSET_IMPL };
2789    if f == 0 {
2790        return 0;
2791    }
2792    let f: extern "C" fn() -> usize = unsafe { core::mem::transmute(f) };
2793    f()
2794}
2795
2796#[inline]
2797unsafe fn sys_gettid() -> i64 {
2798    <Arch as Syscalls>::syscall0(SYS_GETTID)
2799}
2800
2801#[inline]
2802unsafe fn sys_futex(uaddr: *mut c_int,
2803    futex_op: c_int,
2804    val: c_int,
2805    timeout: *mut c_void,
2806    uaddr2: *mut c_int,
2807    val3: c_int,) -> i64 {
2808    <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)
2809}
2810
2811const THREAD_CHUNK: usize = 1024;
2812const STACK_SIZE: usize = 1024 * 1024;
2813// Per-thread pointer to its Thread record.  The TCB has room after errno
2814// (0x30), the vDSO getrandom state (0x38), and this pointer (0x40).
2815const THREAD_TCB_OFFSET: usize = 0x40;
2816
2817#[repr(C)]
2818#[derive(Copy, Clone)]
2819struct Thread {
2820    tid: c_int,
2821    detach_state: c_int,
2822    result: *mut c_void,
2823    cancel: c_int,
2824    cancel_state: c_int,
2825    cancel_type: c_int,
2826    user_fn: usize,
2827    user_arg: *mut c_void,
2828    stack: *mut u8,
2829    stack_size: usize,
2830    stack_owned: bool,
2831    fs_base: *mut u8,
2832    // TLS block as allocated at creation. The global TLS size can grow when
2833    // a DSO is dlopen'ed, so it must not be used to free an older thread's
2834    // block: the address and length would be wrong and could unmap a
2835    // neighbouring thread stack.
2836    tls_base: *mut u8,
2837    tls_size: usize,
2838    tsd: [*mut c_void; PTHREAD_KEYS_MAX],
2839    cancelbuf: *mut __ptcb,
2840    robust_list: robust_list_head,
2841    free_next: *mut Thread,
2842}
2843
2844static mut THREADS: [Thread; THREAD_CHUNK] = [Thread {
2845    tid: -1,
2846    detach_state: DT_JOINABLE,
2847    result: core::ptr::null_mut(),
2848    cancel: 0,
2849    cancel_state: PTHREAD_CANCEL_ENABLE,
2850    cancel_type: PTHREAD_CANCEL_DEFERRED,
2851    user_fn: 0,
2852    user_arg: core::ptr::null_mut(),
2853    stack: core::ptr::null_mut(),
2854    stack_size: 0,
2855    stack_owned: false,
2856    fs_base: core::ptr::null_mut(),
2857    tls_base: core::ptr::null_mut(),
2858    tls_size: 0,
2859    tsd: [core::ptr::null_mut(); PTHREAD_KEYS_MAX],
2860    cancelbuf: core::ptr::null_mut(),
2861    robust_list: robust_list_head {
2862        list: robust_list { next: core::ptr::null_mut() },
2863        futex_offset: 0,
2864        pending: core::ptr::null_mut(),
2865    },
2866    free_next: core::ptr::null_mut(),
2867}; THREAD_CHUNK];
2868#[repr(C)]
2869struct ThreadChunk {
2870    next: *mut ThreadChunk,
2871    base: *mut Thread,
2872}
2873static THREAD_CHUNK_LIST: AtomicPtr<ThreadChunk> =
2874    AtomicPtr::new(core::ptr::null_mut());
2875static EXTRA_CHUNK_COUNT: AtomicUsize = AtomicUsize::new(0);
2876// Free list of thread slots, protected by THREAD_LOCK.  Slots are never
2877// moved, so pthread_t values stay valid for the life of a thread.
2878static mut FREE_THREADS: *mut Thread = core::ptr::null_mut();
2879static mut THREAD_TABLE_READY: bool = false;
2880static mut THREAD_LOCK: c_int = 0;
2881static mut THREAD_WAITERS: c_int = 0;
2882static ACTIVE_THREADS: AtomicUsize = AtomicUsize::new(0);
2883static mut KEY_DTORS: [Option<unsafe extern "C" fn(*mut c_void)>; PTHREAD_KEYS_MAX] = [None; PTHREAD_KEYS_MAX];
2884static NEXT_KEY: AtomicUsize = AtomicUsize::new(0);
2885
2886// ponytail: futex helpers
2887unsafe fn futex_wait(addr: *mut c_int, expected: c_int) -> c_int {
2888    let r = sys_futex(addr, FUTEX_WAIT, expected, null_mut(), null_mut(), 0);
2889    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
2890}
2891
2892unsafe fn futex_wake(addr: *mut c_int, count: c_int) {
2893    let c = if count < 0 { c_int::MAX } else { count };
2894    sys_futex(addr, FUTEX_WAKE, c, null_mut(), null_mut(), 0);
2895}
2896
2897unsafe fn futex_lock_pi(addr: *mut c_int, abs_timeout: *const timespec) -> c_int {
2898    let timeout_ptr = if abs_timeout.is_null() { null_mut() } else { abs_timeout as *mut c_void };
2899    let r = sys_futex(addr, FUTEX_LOCK_PI, 0, timeout_ptr, null_mut(), 0);
2900    if r < 0 { (-r) as c_int } else { 0 }
2901}
2902
2903unsafe fn futex_unlock_pi(addr: *mut c_int) -> c_int {
2904    let r = sys_futex(addr, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
2905    if r < 0 { (-r) as c_int } else { 0 }
2906}
2907
2908#[inline]
2909unsafe fn sys_set_robust_list(head: *mut robust_list_head, len: usize) -> i64 {
2910    <Arch as Syscalls>::syscall2(SYS_SET_ROBUST_LIST, head as i64, len as i64)
2911}
2912
2913unsafe fn futex_timedwait(addr: *mut c_int, expected: c_int, abs_timeout: *const timespec) -> c_int {
2914    if abs_timeout.is_null() { return futex_wait(addr, expected); }
2915    let mut now: timespec = core::mem::zeroed();
2916    if sys_clock_gettime(CLOCK_REALTIME, &mut now) < 0 { return EINVAL; }
2917    let mut rel: timespec = core::mem::zeroed();
2918    rel.tv_sec = (*abs_timeout).tv_sec - now.tv_sec;
2919    rel.tv_nsec = (*abs_timeout).tv_nsec - now.tv_nsec;
2920    if rel.tv_nsec < 0 { rel.tv_sec -= 1; rel.tv_nsec += 1_000_000_000; }
2921    if rel.tv_sec < 0 { return ETIMEDOUT; }
2922    let r = sys_futex(addr, FUTEX_WAIT, expected, &mut rel as *mut timespec as *mut c_void, null_mut(), 0);
2923    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
2924}
2925
2926// ponytail: atomic helpers wrapping AtomicI32
2927unsafe fn a_cas(addr: *mut c_int, expected: c_int, desired: c_int) -> c_int {
2928    let a = &*(addr as *const AtomicI32);
2929    match a.compare_exchange(expected, desired, Ordering::AcqRel, Ordering::Acquire) {
2930        Ok(v) | Err(v) => v,
2931    }
2932}
2933
2934unsafe fn a_store(addr: *mut c_int, val: c_int) {
2935    (*(addr as *const AtomicI32)).store(val, Ordering::Release);
2936}
2937
2938unsafe fn a_load(addr: *const c_int) -> c_int {
2939    (*(addr as *const AtomicI32)).load(Ordering::Acquire)
2940}
2941
2942unsafe fn a_swap(addr: *mut c_int, val: c_int) -> c_int {
2943    (*(addr as *const AtomicI32)).swap(val, Ordering::AcqRel)
2944}
2945
2946unsafe fn a_fetch_add(addr: *mut c_int, val: c_int) -> c_int {
2947    (*(addr as *const AtomicI32)).fetch_add(val, Ordering::AcqRel)
2948}
2949
2950unsafe fn a_fetch_sub(addr: *mut c_int, val: c_int) -> c_int {
2951    (*(addr as *const AtomicI32)).fetch_sub(val, Ordering::AcqRel)
2952}
2953
2954unsafe fn spinlock_lock(lock: *mut c_int, waiters: *mut c_int) {
2955    while a_swap(lock, 1) != 0 {
2956        let mut spins = 100;
2957        while spins > 0 && a_load(lock) != 0 { core::hint::spin_loop(); spins -= 1; }
2958        if a_load(lock) == 0 { continue; }
2959        a_fetch_add(waiters, 1);
2960        futex_wait(lock, 1);
2961        a_fetch_sub(waiters, 1);
2962    }
2963}
2964
2965unsafe fn spinlock_unlock(lock: *mut c_int, waiters: *mut c_int) {
2966    a_store(lock, 0);
2967    if a_load(waiters) > 0 { futex_wake(lock, 1); }
2968}
2969
2970unsafe fn thread_slot_count() -> usize {
2971    THREAD_CHUNK + EXTRA_CHUNK_COUNT.load(Ordering::Acquire) * THREAD_CHUNK
2972}
2973
2974unsafe fn thread_slot_at(index: usize) -> *mut Thread {
2975    if index < THREAD_CHUNK {
2976        core::ptr::addr_of_mut!(THREADS[index])
2977    } else {
2978        let extra = index - THREAD_CHUNK;
2979        let chunk_index = extra / THREAD_CHUNK;
2980        let offset = extra % THREAD_CHUNK;
2981        let mut chunk = THREAD_CHUNK_LIST.load(Ordering::Acquire);
2982        let mut i = 0usize;
2983        while i < chunk_index && !chunk.is_null() {
2984            chunk = (*chunk).next;
2985            i += 1;
2986        }
2987        if chunk.is_null() {
2988            return core::ptr::null_mut();
2989        }
2990        (*chunk).base.add(offset)
2991    }
2992}
2993
2994unsafe fn release_thread_slot(slot: *const Thread) {
2995    let slot = slot as *mut Thread;
2996    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
2997    (*slot).tid = -1;
2998    (*slot).free_next = FREE_THREADS;
2999    FREE_THREADS = slot;
3000    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3001}
3002
3003unsafe fn alloc_thread_slot() -> Option<&'static mut Thread> {
3004    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3005    if !THREAD_TABLE_READY {
3006        // Slot 0 is reserved for the process's initial thread.  Registering
3007        // it must not require touching the rest of the table.
3008        let mut i = THREAD_CHUNK;
3009        while i > 1 {
3010            i -= 1;
3011            let slot = &mut THREADS[i];
3012            slot.free_next = FREE_THREADS;
3013            FREE_THREADS = slot;
3014        }
3015        THREAD_TABLE_READY = true;
3016    }
3017    let mut slot = FREE_THREADS;
3018    if slot.is_null() {
3019        let bytes = core::mem::size_of::<ThreadChunk>()
3020            + THREAD_CHUNK * core::mem::size_of::<Thread>();
3021        let raw = sys_mmap(
3022            core::ptr::null_mut(),
3023            bytes,
3024            PROT_READ | PROT_WRITE,
3025            MAP_PRIVATE | MAP_ANONYMOUS,
3026            -1,
3027            0,
3028        ) as *mut u8;
3029        if raw.is_null() || raw == MMAP_FAILED {
3030            spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3031            return None;
3032        }
3033        let header = raw as *mut ThreadChunk;
3034        let base = raw.add(core::mem::size_of::<ThreadChunk>()) as *mut Thread;
3035        (*header).base = base;
3036        let mut i = THREAD_CHUNK;
3037        while i > 1 {
3038            i -= 1;
3039            let s = base.add(i);
3040            (*s).free_next = FREE_THREADS;
3041            FREE_THREADS = s;
3042        }
3043        (*header).next = THREAD_CHUNK_LIST.load(Ordering::Relaxed);
3044        THREAD_CHUNK_LIST.store(header, Ordering::Release);
3045        EXTRA_CHUNK_COUNT.fetch_add(1, Ordering::AcqRel);
3046        slot = base;
3047    } else {
3048        FREE_THREADS = (*slot).free_next;
3049        (*slot).free_next = core::ptr::null_mut();
3050    }
3051    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3052    Some(&mut *slot)
3053}
3054
3055/// The child of fork() keeps only the calling thread.  Rebuild the free list
3056/// so slots belonging to vanished threads are reusable, and update the
3057/// current thread's tid to the child's.
3058unsafe fn thread_allocator_after_fork() {
3059    a_store(&raw mut THREAD_LOCK, 0);
3060    a_store(&raw mut THREAD_WAITERS, 0);
3061    let tp = tcb_slot(THREAD_TCB_OFFSET);
3062    let current = if tp.is_null() {
3063        core::ptr::null_mut()
3064    } else {
3065        core::ptr::read_unaligned(tp) as *mut Thread
3066    };
3067    let child_tid = sys_gettid() as c_int;
3068    if !THREAD_TABLE_READY {
3069        // The initial thread is registered directly in slot 0, so the free
3070        // list may never have been built.  Only update that one slot; the
3071        // first pthread_create() will build the free list.
3072        if !current.is_null() {
3073            (*current).tid = child_tid;
3074            ACTIVE_THREADS.store(1, Ordering::Release);
3075        }
3076        return;
3077    }
3078    let count = thread_slot_count();
3079    let mut free = core::ptr::null_mut();
3080    let mut active = 0usize;
3081    let mut i = 0usize;
3082    while i < count {
3083        let slot = thread_slot_at(i);
3084        if slot == current {
3085            (*slot).tid = child_tid;
3086            (*slot).free_next = core::ptr::null_mut();
3087            active += 1;
3088        } else {
3089            (*slot).tid = -1;
3090            (*slot).free_next = free;
3091            free = slot;
3092        }
3093        i += 1;
3094    }
3095    FREE_THREADS = free;
3096    ACTIVE_THREADS.store(active, Ordering::Release);
3097}
3098
3099unsafe fn run_key_dtors(slot: &mut Thread) {
3100    for _ in 0..PTHREAD_DESTRUCTOR_ITERATIONS {
3101        let mut any = false;
3102        for i in 0..PTHREAD_KEYS_MAX {
3103            let val = slot.tsd[i];
3104            if !val.is_null() {
3105                if let Some(dtor) = KEY_DTORS[i] {
3106                    slot.tsd[i] = core::ptr::null_mut();
3107                    any = true;
3108                    dtor(val);
3109                }
3110            }
3111        }
3112        if !any { break; }
3113    }
3114}
3115
3116unsafe extern "C" fn thread_entry(slot: *mut c_void) -> *mut c_void {
3117    let slot = &mut *(slot as *mut Thread);
3118    let tp = tcb_slot(THREAD_TCB_OFFSET);
3119    if !tp.is_null() {
3120        core::ptr::write_unaligned(tp, slot as *mut Thread as usize);
3121    }
3122    // A reused slot may still carry the previous thread's robust-list state;
3123    // register a fresh list for this thread.
3124    slot.robust_list.list.next = core::ptr::null_mut();
3125    slot.robust_list.futex_offset = 0;
3126    slot.robust_list.pending = core::ptr::null_mut();
3127    ensure_robust_list(slot);
3128    let mut set: SigSetT = 0;
3129    sigemptyset(&mut set);
3130    sigaddset(&mut set, SIGCANCEL);
3131    pthread_sigmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
3132    let user_fn: unsafe extern "C" fn(*mut c_void) -> *mut c_void =
3133        core::mem::transmute::<usize, _>(slot.user_fn);
3134    let ret = user_fn(slot.user_arg);
3135    run_key_dtors(slot);
3136    vdso_getrandom_thread_exit();
3137    slot.result = ret;
3138    a_store(&raw mut slot.detach_state, DT_EXITED);
3139    futex_wake(&raw mut slot.detach_state, 1);
3140    if ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel) <= 1 {
3141        exit(0);
3142    }
3143    sys_exit_thread(0)
3144}
3145
3146unsafe fn init_thread_slot(slot: *mut Thread, me: c_int) {
3147    (*slot).tid = me;
3148    (*slot).detach_state = DT_JOINABLE;
3149    (*slot).result = core::ptr::null_mut();
3150    (*slot).cancel = 0;
3151    (*slot).cancel_state = PTHREAD_CANCEL_ENABLE;
3152    (*slot).cancel_type = PTHREAD_CANCEL_DEFERRED;
3153    (*slot).cancelbuf = core::ptr::null_mut();
3154    core::ptr::write_bytes((*slot).tsd.as_mut_ptr(), 0, PTHREAD_KEYS_MAX);
3155    (*slot).robust_list.list.next = core::ptr::null_mut();
3156    (*slot).robust_list.futex_offset = 0;
3157    (*slot).robust_list.pending = core::ptr::null_mut();
3158    (*slot).free_next = core::ptr::null_mut();
3159}
3160
3161unsafe fn register_main_thread() -> Option<&'static mut Thread> {
3162    let me = sys_gettid() as c_int;
3163    let tp = tcb_slot(THREAD_TCB_OFFSET);
3164    if !tp.is_null() {
3165        let p = core::ptr::read_unaligned(tp) as *mut Thread;
3166        if !p.is_null() && (*p).tid == me {
3167            return Some(&mut *p);
3168        }
3169    }
3170    let slot = core::ptr::addr_of_mut!(THREADS[0]);
3171    init_thread_slot(slot, me);
3172    if !tp.is_null() {
3173        core::ptr::write_unaligned(tp, slot as usize);
3174    }
3175    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3176    Some(&mut *slot)
3177}
3178
3179unsafe fn register_current_thread() -> Option<&'static mut Thread> {
3180    let me = sys_gettid() as c_int;
3181    let slot_ref = alloc_thread_slot()?;
3182    let slot = slot_ref as *mut Thread;
3183    init_thread_slot(slot, me);
3184    let tp = tcb_slot(THREAD_TCB_OFFSET);
3185    if !tp.is_null() {
3186        core::ptr::write_unaligned(tp, slot as usize);
3187    }
3188    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3189    Some(&mut *slot)
3190}
3191
3192unsafe fn find_thread() -> Option<&'static mut Thread> {
3193    let me = sys_gettid() as c_int;
3194    let tp = tcb_slot(THREAD_TCB_OFFSET);
3195    if !tp.is_null() {
3196        let p = core::ptr::read_unaligned(tp) as *mut Thread;
3197        if !p.is_null() && (*p).tid == me {
3198            return Some(&mut *p);
3199        }
3200    }
3201    let main = core::ptr::addr_of_mut!(THREADS[0]);
3202    if (*main).tid == me {
3203        if !tp.is_null() {
3204            core::ptr::write_unaligned(tp, main as usize);
3205        }
3206        return Some(&mut *main);
3207    }
3208    let count = thread_slot_count();
3209    let mut i = 0usize;
3210    while i < count {
3211        let slot = thread_slot_at(i);
3212        if core::ptr::read_volatile(&raw const (*slot).tid) == me {
3213            if !tp.is_null() {
3214                core::ptr::write_unaligned(tp, slot as usize);
3215            }
3216            return Some(&mut *slot);
3217        }
3218        i += 1;
3219    }
3220    register_current_thread()
3221}
3222
3223#[no_mangle]
3224pub unsafe extern "C" fn pthread_self() -> PthreadT {
3225    match find_thread() {
3226        Some(slot) => slot as *mut Thread as PthreadT,
3227        None => 0,
3228    }
3229}
3230
3231#[no_mangle]
3232pub unsafe extern "C" fn pthread_equal(t1: PthreadT, t2: PthreadT) -> c_int {
3233    (t1 == t2) as c_int
3234}
3235
3236#[no_mangle]
3237pub unsafe extern "C" fn pthread_create(
3238    thread: *mut PthreadT,
3239    attr: *const pthread_attr_t,
3240    start_routine: usize,
3241    arg: *mut c_void,
3242) -> c_int {
3243    if start_routine == 0 || thread.is_null() { return EINVAL; }
3244    let Some(slot_ref) = alloc_thread_slot() else { return EAGAIN; };
3245    let slot = slot_ref as *mut Thread;
3246    let stack_size = if !attr.is_null() {
3247        let s = *((*attr).__i.as_ptr() as *const usize);
3248        if s > 0 { s } else { STACK_SIZE }
3249    } else { STACK_SIZE };
3250    // musl stores the stack *top* in pthread_attr_t; zero means "allocate".
3251    let user_top = if !attr.is_null() {
3252        *((*attr).__i.as_ptr().add(4) as *const *mut c_void)
3253    } else {
3254        core::ptr::null_mut()
3255    };
3256    let stack_owned = user_top.is_null();
3257    let stack = if stack_owned {
3258        sys_mmap(null_mut(), stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
3259    } else {
3260        (user_top as *mut u8).sub(stack_size)
3261    };
3262    if stack == MMAP_FAILED { release_thread_slot(slot); return EAGAIN; }
3263    let static_mode = RC_STATIC_EXEC;
3264    let tls_total = if static_mode {
3265        STATIC_TLS_BLOCK_SIZE
3266    } else {
3267        __keel_tls_block_size()
3268    };
3269    let mut stack_top = stack.add(stack_size);
3270    let mut tls_owned = true;
3271    let fs_base = if static_mode {
3272        if !stack_owned && tls_total > 0 && stack_size > tls_total + 4096 {
3273            let block = ((user_top as usize - tls_total) & !63usize) as *mut u8;
3274            let fs = static_tls_init_block(block);
3275            if fs.is_null() {
3276                static_tls_create_block()
3277            } else {
3278                stack_top = block;
3279                tls_owned = false;
3280                fs
3281            }
3282        } else {
3283            static_tls_create_block()
3284        }
3285    } else if !stack_owned && tls_total > 0 && stack_size > tls_total + 4096 {
3286        // Carve TLS out of the top of the application-provided stack (musl
3287        // behaviour). A separate mmap here can land directly below the stack
3288        // and prevent MAP_GROWSDOWN from expanding it.
3289        let block = ((user_top as usize - tls_total) & !63usize) as *mut u8;
3290        let fs = __keel_init_thread_tls_at(block);
3291        if fs.is_null() {
3292            __keel_create_thread_tls()
3293        } else {
3294            stack_top = block;
3295            tls_owned = false;
3296            fs
3297        }
3298    } else {
3299        __keel_create_thread_tls()
3300    };
3301    if fs_base.is_null() {
3302        if stack_owned { sys_munmap(stack, stack_size); }
3303        release_thread_slot(slot);
3304        return EAGAIN;
3305    }
3306    let tls_base = if static_mode {
3307        fs_base.sub(STATIC_TLS_TP_OFFSET)
3308    } else {
3309        fs_base.sub(__keel_tls_base_offset())
3310    };
3311    let tls_size = if tls_owned { tls_total } else { 0 };
3312    (*slot).detach_state = DT_JOINABLE;
3313    (*slot).result = core::ptr::null_mut();
3314    (*slot).cancel = 0;
3315    (*slot).cancel_state = PTHREAD_CANCEL_ENABLE;
3316    (*slot).cancel_type = PTHREAD_CANCEL_DEFERRED;
3317    core::ptr::write_bytes((*slot).tsd.as_mut_ptr(), 0, PTHREAD_KEYS_MAX);
3318    (*slot).tid = 1;
3319    (*slot).user_fn = start_routine;
3320    (*slot).user_arg = arg;
3321    (*slot).stack = stack;
3322    (*slot).stack_size = stack_size;
3323    (*slot).stack_owned = stack_owned;
3324    (*slot).fs_base = fs_base;
3325    (*slot).tls_base = tls_base;
3326    (*slot).tls_size = tls_size;
3327    let tid_ptr = &raw mut (*slot).tid;
3328    let flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD
3329        | CLONE_SYSVSEM | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SETTLS;
3330    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3331    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);
3332    if tid < 0 {
3333        ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel);
3334        (*slot).tid = -1;
3335        if stack_owned { sys_munmap(stack, stack_size); }
3336        if tls_size > 0 { sys_munmap(tls_base, tls_size); }
3337        release_thread_slot(slot);
3338        return EAGAIN;
3339    }
3340    if !attr.is_null() && (*attr).__i[6] == PTHREAD_CREATE_DETACHED {
3341        (*slot).detach_state = DT_DETACHED;
3342    }
3343    *thread = slot as PthreadT;
3344    0
3345}
3346
3347#[no_mangle]
3348pub unsafe extern "C" fn pthread_join(thread: PthreadT, retval: *mut *mut c_void) -> c_int {
3349    let slot = thread as *mut Thread;
3350    if slot.is_null() { return EINVAL; }
3351    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
3352    let tid_ptr = &raw mut (*slot).tid;
3353    loop {
3354        pthread_testcancel();
3355        let tid = core::ptr::read_volatile(tid_ptr);
3356        if tid == 0 { break; }
3357        if tid < 0 { return EINVAL; }
3358        sys_futex(tid_ptr, FUTEX_WAIT, tid, null_mut(), null_mut(), 0);
3359        pthread_testcancel();
3360    }
3361    if !retval.is_null() { *retval = (*slot).result; }
3362    let stack = (*slot).stack;
3363    let stack_size = (*slot).stack_size;
3364    let stack_owned = (*slot).stack_owned;
3365    let tls_base = (*slot).tls_base;
3366    let tls_size = (*slot).tls_size;
3367    (*slot).tid = -1;
3368    (*slot).detach_state = DT_JOINABLE;
3369    (*slot).result = core::ptr::null_mut();
3370    (*slot).stack = core::ptr::null_mut();
3371    (*slot).stack_size = 0;
3372    (*slot).stack_owned = false;
3373    (*slot).fs_base = core::ptr::null_mut();
3374    (*slot).tls_base = core::ptr::null_mut();
3375    (*slot).tls_size = 0;
3376    if stack_owned && !stack.is_null() && stack_size > 0 { sys_munmap(stack, stack_size); }
3377    // Keep the TLS mapping but return its pages to the kernel. Some runtimes
3378    // (notably V8) retain pointers into an exited thread's TLS and read them
3379    // during process teardown; unmapping makes that a SIGSEGV, while zero
3380    // pages are handled gracefully. The VA range is tiny (TLS_TOTAL_SIZE).
3381    // Retain the TLS block instead of unmapping it. V8 keeps pointers into a
3382    // joined thread's TLS and dereferences them during process teardown;
3383    // unmapping turns that into SIGSEGV, and MADV_DONTNEED races with it.
3384    // The block is small (TLS_TOTAL_SIZE + TCB_SIZE) and bounded by thread
3385    // creation, so keeping it mapped is the safe trade-off.
3386    let _ = (tls_base, tls_size);
3387    release_thread_slot(slot);
3388    0
3389}
3390
3391#[no_mangle]
3392pub unsafe extern "C" fn pthread_detach(thread: PthreadT) -> c_int {
3393    let slot = thread as *mut Thread;
3394    if slot.is_null() { return EINVAL; }
3395    let old = a_cas(&raw mut (*slot).detach_state, DT_JOINABLE, DT_DETACHED);
3396    if old == DT_EXITED {
3397        let stack = (*slot).stack;
3398        let stack_size = (*slot).stack_size;
3399        let stack_owned = (*slot).stack_owned;
3400        let tls_base = (*slot).tls_base;
3401        let tls_size = (*slot).tls_size;
3402        (*slot).tid = -1;
3403        (*slot).stack = core::ptr::null_mut();
3404        (*slot).stack_size = 0;
3405        (*slot).stack_owned = false;
3406        (*slot).fs_base = core::ptr::null_mut();
3407        (*slot).tls_base = core::ptr::null_mut();
3408        (*slot).tls_size = 0;
3409        if stack_owned && !stack.is_null() && stack_size > 0 { sys_munmap(stack, stack_size); }
3410        // See pthread_join: keep the TLS block mapped after the thread dies.
3411        let _ = (tls_base, tls_size);
3412        release_thread_slot(slot);
3413    }
3414    0
3415}
3416
3417#[no_mangle]
3418pub unsafe extern "C" fn pthread_exit(retval: *mut c_void) -> ! {
3419    if let Some(slot) = find_thread() {
3420        run_cleanup_handlers(slot);
3421        run_key_dtors(slot);
3422        vdso_getrandom_thread_exit();
3423        slot.result = retval;
3424        slot.detach_state = DT_EXITED;
3425        futex_wake(&slot.detach_state as *const c_int as *mut c_int, 1);
3426
3427        // If this is the last thread, run atexit handlers via exit().
3428        if ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel) <= 1 {
3429            exit(0);
3430        }
3431    }
3432    sys_exit_thread(0);
3433}
3434
3435// --- pthread_attr_* ---
3436#[no_mangle]
3437pub unsafe extern "C" fn pthread_attr_init(attr: *mut pthread_attr_t) -> c_int {
3438    core::ptr::write_bytes(attr, 0, 1);
3439    *((*attr).__i.as_mut_ptr() as *mut usize) = STACK_SIZE;
3440    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = 4096;
3441    (*attr).__i[6] = PTHREAD_CREATE_JOINABLE;
3442    (*attr).__i[7] = PTHREAD_INHERIT_SCHED;
3443    0
3444}
3445#[no_mangle]
3446pub unsafe extern "C" fn pthread_attr_destroy(_attr: *mut pthread_attr_t) -> c_int { 0 }
3447#[no_mangle]
3448pub unsafe extern "C" fn pthread_attr_setdetachstate(attr: *mut pthread_attr_t, s: c_int) -> c_int {
3449    if s != PTHREAD_CREATE_JOINABLE && s != PTHREAD_CREATE_DETACHED { return EINVAL; }
3450    (*attr).__i[6] = s; 0
3451}
3452#[no_mangle]
3453pub unsafe extern "C" fn pthread_attr_getdetachstate(attr: *const pthread_attr_t, s: *mut c_int) -> c_int {
3454    *s = (*attr).__i[6]; 0
3455}
3456#[no_mangle]
3457pub unsafe extern "C" fn pthread_attr_setstacksize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
3458    if sz < 2048 { return EINVAL; }
3459    *((*attr).__i.as_mut_ptr() as *mut usize) = sz;
3460    *((*attr).__i.as_mut_ptr().add(4) as *mut *mut c_void) = core::ptr::null_mut();
3461    0
3462}
3463#[no_mangle]
3464pub unsafe extern "C" fn pthread_attr_getstacksize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
3465    *sz = *((*attr).__i.as_ptr() as *const usize); 0
3466}
3467#[no_mangle]
3468pub unsafe extern "C" fn pthread_attr_setstack(attr: *mut pthread_attr_t, addr: *mut c_void, sz: usize) -> c_int {
3469    if sz < 2048 { return EINVAL; }
3470    *((*attr).__i.as_mut_ptr() as *mut usize) = sz;
3471    // musl stores the top of the stack, not its base.
3472    *((*attr).__i.as_mut_ptr().add(4) as *mut *mut c_void) = (addr as *mut u8).add(sz) as *mut c_void;
3473    0
3474}
3475#[no_mangle]
3476pub unsafe extern "C" fn pthread_attr_getstack(attr: *const pthread_attr_t, addr: *mut *mut c_void, sz: *mut usize) -> c_int {
3477    let size = *((*attr).__i.as_ptr() as *const usize);
3478    *sz = size;
3479    let top = *((*attr).__i.as_ptr().add(4) as *const *mut c_void);
3480    *addr = if top.is_null() {
3481        core::ptr::null_mut()
3482    } else {
3483        (top as *mut u8).sub(size) as *mut c_void
3484    };
3485    0
3486}
3487#[no_mangle]
3488pub unsafe extern "C" fn pthread_attr_setguardsize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
3489    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = sz; 0
3490}
3491#[no_mangle]
3492pub unsafe extern "C" fn pthread_attr_getguardsize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
3493    *sz = *((*attr).__i.as_ptr().add(2) as *const usize); 0
3494}
3495#[no_mangle]
3496pub unsafe extern "C" fn pthread_attr_setscope(_attr: *mut pthread_attr_t, scope: c_int) -> c_int {
3497    if scope != PTHREAD_SCOPE_SYSTEM { return EINVAL; }
3498    0
3499}
3500#[no_mangle]
3501pub unsafe extern "C" fn pthread_attr_getscope(_attr: *const pthread_attr_t, scope: *mut c_int) -> c_int {
3502    *scope = PTHREAD_SCOPE_SYSTEM; 0
3503}
3504#[no_mangle]
3505pub unsafe extern "C" fn pthread_attr_setinheritsched(attr: *mut pthread_attr_t, inh: c_int) -> c_int {
3506    if inh != PTHREAD_INHERIT_SCHED && inh != PTHREAD_EXPLICIT_SCHED { return EINVAL; }
3507    (*attr).__i[7] = inh; 0
3508}
3509#[no_mangle]
3510pub unsafe extern "C" fn pthread_attr_getinheritsched(attr: *const pthread_attr_t, inh: *mut c_int) -> c_int {
3511    *inh = (*attr).__i[7]; 0
3512}
3513#[no_mangle]
3514pub unsafe extern "C" fn pthread_attr_setschedpolicy(attr: *mut pthread_attr_t, p: c_int) -> c_int {
3515    (*attr).__i[8] = p; 0
3516}
3517#[no_mangle]
3518pub unsafe extern "C" fn pthread_attr_getschedpolicy(attr: *const pthread_attr_t, p: *mut c_int) -> c_int {
3519    *p = (*attr).__i[8]; 0
3520}
3521#[no_mangle]
3522pub unsafe extern "C" fn pthread_attr_setschedparam(attr: *mut pthread_attr_t, param: *const sched_param) -> c_int {
3523    (*attr).__i[9] = (*param).sched_priority; 0
3524}
3525#[no_mangle]
3526pub unsafe extern "C" fn pthread_attr_getschedparam(attr: *const pthread_attr_t, param: *mut sched_param) -> c_int {
3527    (*param).sched_priority = (*attr).__i[9]; 0
3528}
3529
3530// --- pthread_mutexattr_* ---
3531#[no_mangle]
3532pub unsafe extern "C" fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> c_int {
3533    (*attr).__attr = 0; 0
3534}
3535#[no_mangle]
3536pub unsafe extern "C" fn pthread_mutexattr_destroy(_attr: *mut pthread_mutexattr_t) -> c_int { 0 }
3537#[no_mangle]
3538pub unsafe extern "C" fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, t: c_int) -> c_int {
3539    if (t as c_uint) > 2 { return EINVAL; }
3540    (*attr).__attr = ((*attr).__attr & !3) | t as c_uint; 0
3541}
3542#[no_mangle]
3543pub unsafe extern "C" fn pthread_mutexattr_gettype(attr: *const pthread_mutexattr_t, t: *mut c_int) -> c_int {
3544    *t = ((*attr).__attr & 3) as c_int; 0
3545}
3546#[no_mangle]
3547pub unsafe extern "C" fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, p: c_int) -> c_int {
3548    if (p as c_uint) > 1 { return EINVAL; }
3549    (*attr).__attr = ((*attr).__attr & !128) | ((p as c_uint) << 7); 0
3550}
3551#[no_mangle]
3552pub unsafe extern "C" fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, p: *mut c_int) -> c_int {
3553    *p = (((*attr).__attr >> 7) & 1) as c_int; 0
3554}
3555
3556#[no_mangle]
3557pub unsafe extern "C" fn pthread_mutexattr_setprotocol(attr: *mut pthread_mutexattr_t, protocol: c_int) -> c_int {
3558    match protocol {
3559        0 => { (*attr).__attr &= !(MUTEX_PI as c_uint); 0 }
3560        1 => {
3561            let mut lk: c_int = 0;
3562            let r = sys_futex(&raw mut lk, FUTEX_LOCK_PI, 0, null_mut(), null_mut(), 0);
3563            if r < 0 { return (-r) as c_int; }
3564            sys_futex(&raw mut lk, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
3565            (*attr).__attr |= MUTEX_PI as c_uint;
3566            0
3567        }
3568        2 => ENOTSUP,
3569        _ => EINVAL,
3570    }
3571}
3572#[no_mangle]
3573pub unsafe extern "C" fn pthread_mutexattr_getprotocol(attr: *const pthread_mutexattr_t, protocol: *mut c_int) -> c_int {
3574    *protocol = (((*attr).__attr >> 3) & 3) as c_int; 0
3575}
3576
3577const ENOTSUP: c_int = 95;
3578
3579#[no_mangle]
3580pub unsafe extern "C" fn pthread_mutexattr_setrobust(attr: *mut pthread_mutexattr_t, robust: c_int) -> c_int {
3581    if (robust as c_uint) > 1 { return EINVAL; }
3582    if robust != 0 {
3583        (*attr).__attr |= MUTEX_ROBUST as c_uint;
3584    } else {
3585        (*attr).__attr &= !(MUTEX_ROBUST as c_uint);
3586    }
3587    0
3588}
3589#[no_mangle]
3590pub unsafe extern "C" fn pthread_mutexattr_getrobust(attr: *const pthread_mutexattr_t, robust: *mut c_int) -> c_int {
3591    *robust = (((*attr).__attr >> 2) & 1) as c_int; 0
3592}
3593
3594#[no_mangle]
3595pub unsafe extern "C" fn pthread_mutex_consistent(m: *mut pthread_mutex_t) -> c_int {
3596    let old = a_load(&raw const (*m).__i[1]);
3597    let own = old & 0x3fffffff;
3598    if ((*m).__i[0] & MUTEX_ROBUST) == 0 || own == 0 || (old & 0x40000000) == 0 {
3599        return EINVAL;
3600    }
3601    let self_tid = sys_gettid() as c_int;
3602    if own != self_tid { return EPERM; }
3603    a_and(&raw mut (*m).__i[1], !(0x40000000i32));
3604    0
3605}
3606
3607unsafe fn a_and(addr: *mut c_int, val: c_int) {
3608    let a = &*(addr as *const AtomicI32);
3609    a.fetch_and(val, Ordering::AcqRel);
3610}
3611
3612// --- pthread_mutex_* ---
3613const MUTEX_TYPE_MASK: c_int = 3;
3614const MUTEX_ROBUST: c_int = 4;
3615const MUTEX_PI: c_int = 8;
3616const MUTEX_PSHARED: c_int = 128;
3617
3618unsafe fn ensure_robust_list(slot: &mut Thread) {
3619    if slot.robust_list.futex_offset == 0 {
3620        slot.robust_list.futex_offset = -28;
3621        slot.robust_list.pending = core::ptr::null_mut();
3622        sys_set_robust_list(&mut slot.robust_list, 24);
3623    }
3624}
3625
3626unsafe fn mutex_trylock(m: *mut pthread_mutex_t) -> c_int {
3627    let type_ = (*m).__i[0];
3628    // Fast path: plain NORMAL only (no PI, no robust, no pshared).
3629    // A failed CAS must report EBUSY unconditionally: the old value may be
3630    // the waiter bit (0x80000000), whose low bits are zero, and masking it
3631    // with EBUSY would falsely report that the lock was acquired.
3632    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL {
3633        let old = a_cas(&raw mut (*m).__i[1], 0, EBUSY);
3634        return if old == 0 { 0 } else { EBUSY };
3635    }
3636    let base_type = type_ & MUTEX_TYPE_MASK;
3637    let self_tid = sys_gettid() as c_int;
3638    let old = a_load(&raw const (*m).__i[1]);
3639    let own = old & 0x3fffffff;
3640    if own == self_tid {
3641        if (type_ & MUTEX_PI) != 0 && (*m).__i[5] < 0 {
3642            (*m).__i[5] = 0;
3643            return 0;
3644        }
3645        if base_type == PTHREAD_MUTEX_RECURSIVE {
3646            if (*m).__i[5] >= c_int::MAX { return EAGAIN; }
3647            (*m).__i[5] += 1;
3648            return 0;
3649        }
3650        if base_type == PTHREAD_MUTEX_ERRORCHECK { return EDEADLK; }
3651        return EBUSY;
3652    }
3653    if own == 0x3fffffff { return ENOTRECOVERABLE; }
3654    if own != 0 || (old != 0 && (type_ & MUTEX_ROBUST) == 0) { return EBUSY; }
3655    let mut newtid = self_tid;
3656    if (type_ & MUTEX_ROBUST) != 0 {
3657        if (*m).__i[2] != 0 { newtid |= 1i32 << 31; }
3658        newtid |= old & 0x40000000;
3659    }
3660    if a_cas(&raw mut (*m).__i[1], old, newtid) == old {
3661        (*m).__i[5] = 0;
3662        if (type_ & MUTEX_ROBUST) != 0 {
3663            if let Some(slot) = find_thread() {
3664                ensure_robust_list(slot);
3665                let m_next = &raw mut (*m).__i[8] as *mut robust_list;
3666                let head = &mut slot.robust_list.list;
3667                (*m_next).next = head.next;
3668                head.next = m_next;
3669            }
3670        }
3671        if old != 0 { return EOWNERDEAD; }
3672        0
3673    } else { EBUSY }
3674}
3675
3676unsafe fn mutex_lock_internal(m: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3677    let type_ = (*m).__i[0];
3678    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL && a_cas(&raw mut (*m).__i[1], 0, EBUSY) == 0 {
3679        return 0;
3680    }
3681    let r = mutex_trylock(m);
3682    if r != EBUSY { return r; }
3683    if (type_ & MUTEX_PI) != 0 {
3684        let timeout_ptr = if abs_timeout.is_null() { core::ptr::null() } else { abs_timeout };
3685        loop {
3686            let e = futex_lock_pi(&raw mut (*m).__i[1], timeout_ptr);
3687            match e {
3688                0 => {
3689                    if (type_ & MUTEX_ROBUST) != 0 && (((*m).__i[1] & 0x40000000) != 0 || (*m).__i[2] != 0) {
3690                        (*m).__i[5] = -1;
3691                        let _ = mutex_trylock(m);
3692                        return EOWNERDEAD;
3693                    }
3694                    if (type_ & MUTEX_ROBUST) == 0 && (((*m).__i[1] & 0x40000000) != 0 || (*m).__i[2] != 0) {
3695                        (*m).__i[2] = -1;
3696                        futex_unlock_pi(&raw mut (*m).__i[1]);
3697                        return EBUSY;
3698                    }
3699                    (*m).__i[5] = -1;
3700                    let r2 = mutex_trylock(m);
3701                    if r2 == 0 { return 0; }
3702                    return r2;
3703                }
3704                EINTR => continue,
3705                EDEADLK => {
3706                    if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK { return e; }
3707                    loop { pause(); }
3708                }
3709                EOWNERDEAD => {
3710                    (*m).__i[5] = -1;
3711                    let _ = mutex_trylock(m);
3712                    return EOWNERDEAD;
3713                }
3714                _ => return e,
3715            }
3716        }
3717    }
3718    let mut spins = 100;
3719    while spins > 0 {
3720        let r = mutex_trylock(m);
3721        if r != EBUSY { return r; }
3722        core::hint::spin_loop();
3723        spins -= 1;
3724    }
3725    loop {
3726        let r = mutex_trylock(m);
3727        if r != EBUSY { return r; }
3728        if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK {
3729            let self_tid = sys_gettid() as c_int;
3730            if (a_load(&raw const (*m).__i[1]) & 0x3fffffff) == self_tid { return EDEADLK; }
3731        }
3732        a_fetch_add(&raw mut (*m).__i[2], 1);
3733        let val = a_load(&raw const (*m).__i[1]);
3734        // If the previous owner released the lock between trylock() and the
3735        // load above, retry instead of publishing a waiter-only lock word
3736        // (0x80000000) that no thread owns.
3737        if val == 0 {
3738            a_fetch_sub(&raw mut (*m).__i[2], 1);
3739            continue;
3740        }
3741        a_cas(&raw mut (*m).__i[1], val, val | (1i32 << 31));
3742        let e = futex_timedwait(&raw mut (*m).__i[1], val | (1i32 << 31), abs_timeout);
3743        a_fetch_sub(&raw mut (*m).__i[2], 1);
3744        if e != 0 && e != EINTR { return e; }
3745    }
3746}
3747
3748#[no_mangle]
3749pub unsafe extern "C" fn pthread_mutex_init(mutex: *mut pthread_mutex_t, attr: *const pthread_mutexattr_t) -> c_int {
3750    core::ptr::write_bytes(mutex, 0, 1);
3751    if !attr.is_null() { (*mutex).__i[0] = (*attr).__attr as c_int; }
3752    0
3753}
3754#[no_mangle]
3755pub unsafe extern "C" fn pthread_mutex_destroy(_mutex: *mut pthread_mutex_t) -> c_int { 0 }
3756#[no_mangle]
3757pub unsafe extern "C" fn pthread_mutex_lock(mutex: *mut pthread_mutex_t) -> c_int {
3758    mutex_lock_internal(mutex, core::ptr::null())
3759}
3760#[no_mangle]
3761pub unsafe extern "C" fn pthread_mutex_trylock(mutex: *mut pthread_mutex_t) -> c_int {
3762    mutex_trylock(mutex)
3763}
3764#[no_mangle]
3765pub unsafe extern "C" fn pthread_mutex_timedlock(mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3766    mutex_lock_internal(mutex, abs_timeout)
3767}
3768#[no_mangle]
3769pub unsafe extern "C" fn pthread_mutex_unlock(mutex: *mut pthread_mutex_t) -> c_int {
3770    let type_ = (*mutex).__i[0];
3771    let base_type = type_ & MUTEX_TYPE_MASK;
3772    let old = a_load(&raw const (*mutex).__i[1]);
3773    if base_type != PTHREAD_MUTEX_NORMAL {
3774        let self_tid = sys_gettid() as c_int;
3775        if (old & 0x3fffffff) != self_tid { return EPERM; }
3776        if base_type == PTHREAD_MUTEX_RECURSIVE && (*mutex).__i[5] > 0 {
3777            (*mutex).__i[5] -= 1;
3778            return 0;
3779        }
3780    }
3781    let mut new = 0;
3782    if (type_ & MUTEX_ROBUST) != 0 && (old & 0x40000000) != 0 {
3783        new = 0x7fffffff;
3784    }
3785    if (type_ & MUTEX_PI) != 0 {
3786        if old < 0 || a_cas(&raw mut (*mutex).__i[1], old, new) != old {
3787            if new != 0 { a_store(&raw mut (*mutex).__i[2], -1); }
3788            return futex_unlock_pi(&raw mut (*mutex).__i[1]);
3789        }
3790        return 0;
3791    }
3792    a_store(&raw mut (*mutex).__i[1], new);
3793    if new == 0 && (a_load(&raw const (*mutex).__i[2]) > 0 || old < 0) {
3794        futex_wake(&raw mut (*mutex).__i[1], 1);
3795    }
3796    0
3797}
3798
3799// --- pthread_condattr_* ---
3800#[no_mangle]
3801pub unsafe extern "C" fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> c_int {
3802    (*attr).__attr = 0; 0
3803}
3804#[no_mangle]
3805pub unsafe extern "C" fn pthread_condattr_destroy(_attr: *mut pthread_condattr_t) -> c_int { 0 }
3806#[no_mangle]
3807pub unsafe extern "C" fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, clk: c_int) -> c_int {
3808    if clk != CLOCK_REALTIME && clk != CLOCK_MONOTONIC { return EINVAL; }
3809    (*attr).__attr = ((*attr).__attr & 0x80000000) | clk as c_uint; 0
3810}
3811#[no_mangle]
3812pub unsafe extern "C" fn pthread_condattr_getclock(attr: *const pthread_condattr_t, clk: *mut c_int) -> c_int {
3813    *clk = ((*attr).__attr & 0x7fffffff) as c_int; 0
3814}
3815#[no_mangle]
3816pub unsafe extern "C" fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, p: c_int) -> c_int {
3817    if (p as c_uint) > 1 { return EINVAL; }
3818    (*attr).__attr = ((*attr).__attr & 0x7fffffff) | ((p as c_uint) << 31); 0
3819}
3820#[no_mangle]
3821pub unsafe extern "C" fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, p: *mut c_int) -> c_int {
3822    *p = ((*attr).__attr >> 31) as c_int; 0
3823}
3824
3825// --- pthread_cond_* ---
3826#[no_mangle]
3827pub unsafe extern "C" fn pthread_cond_init(cond: *mut pthread_cond_t, attr: *const pthread_condattr_t) -> c_int {
3828    core::ptr::write_bytes(cond, 0, 1);
3829    if !attr.is_null() {
3830        (*cond).__i[4] = ((*attr).__attr & 0x7fffffff) as c_int;
3831    }
3832    0
3833}
3834#[no_mangle]
3835pub unsafe extern "C" fn pthread_cond_destroy(_cond: *mut pthread_cond_t) -> c_int { 0 }
3836#[no_mangle]
3837pub unsafe extern "C" fn pthread_cond_wait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t) -> c_int {
3838    pthread_cond_timedwait(cond, mutex, core::ptr::null())
3839}
3840
3841
3842#[no_mangle]
3843pub unsafe extern "C" fn pthread_cond_timedwait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3844    pthread_testcancel();
3845    let seq_ptr = &raw mut (*cond).__i[2];
3846    let waiters_ptr = &raw mut (*cond).__i[3];
3847    let seq = a_load(seq_ptr);
3848    a_fetch_add(waiters_ptr, 1);
3849    pthread_mutex_unlock(mutex);
3850    let e = futex_timedwait(seq_ptr, seq, abs_timeout);
3851    a_fetch_sub(waiters_ptr, 1);
3852    let r = pthread_mutex_lock(mutex);
3853    if r != 0 { return r; }
3854    if e == EINTR {
3855        pthread_testcancel();
3856    }
3857    if e != 0 && e != EINTR { return e; }
3858    0
3859}
3860#[no_mangle]
3861pub unsafe extern "C" fn pthread_cond_signal(cond: *mut pthread_cond_t) -> c_int {
3862    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
3863    a_fetch_add(&raw mut (*cond).__i[2], 1);
3864    futex_wake(&raw mut (*cond).__i[2], 1);
3865    0
3866}
3867#[no_mangle]
3868pub unsafe extern "C" fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> c_int {
3869    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
3870    a_fetch_add(&raw mut (*cond).__i[2], 1);
3871    futex_wake(&raw mut (*cond).__i[2], -1);
3872    0
3873}
3874
3875// --- pthread_rwlockattr_* ---
3876#[no_mangle]
3877pub unsafe extern "C" fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> c_int {
3878    (*attr).__attr = [0; 2]; 0
3879}
3880#[no_mangle]
3881pub unsafe extern "C" fn pthread_rwlockattr_destroy(_attr: *mut pthread_rwlockattr_t) -> c_int { 0 }
3882#[no_mangle]
3883pub unsafe extern "C" fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, p: c_int) -> c_int {
3884    if (p as c_uint) > 1 { return EINVAL; }
3885    (*attr).__attr[0] = ((*attr).__attr[0] & !128) | ((p as c_uint) << 7); 0
3886}
3887#[no_mangle]
3888pub unsafe extern "C" fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, p: *mut c_int) -> c_int {
3889    *p = (((*attr).__attr[0] >> 7) & 1) as c_int; 0
3890}
3891
3892// --- pthread_rwlock_* ---
3893unsafe fn rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int {
3894    loop {
3895        let val = a_load(&raw const (*rw).__i[0]);
3896        let cnt = val & 0x7fffffff;
3897        if cnt == 0x7fffffff { return EBUSY; }
3898        if cnt == 0x7ffffffe { return EAGAIN; }
3899        if a_cas(&raw mut (*rw).__i[0], val, val + 1) == val { return 0; }
3900    }
3901}
3902unsafe fn rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int {
3903    if a_cas(&raw mut (*rw).__i[0], 0, 0x7fffffff) == 0 { 0 } else { EBUSY }
3904}
3905unsafe fn rwlock_timedrdlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
3906    let r = rwlock_tryrdlock(rw);
3907    if r != EBUSY { return r; }
3908    let mut spins = 100;
3909    while spins > 0 { let r = rwlock_tryrdlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
3910    loop {
3911        let r = rwlock_tryrdlock(rw);
3912        if r != EBUSY { return r; }
3913        let val = a_load(&raw const (*rw).__i[0]);
3914        if val & 0x7fffffff != 0x7fffffff { continue; }
3915        a_fetch_add(&raw mut (*rw).__i[1], 1);
3916        a_cas(&raw mut (*rw).__i[0], val, val | (1i32 << 31));
3917        let e = futex_timedwait(&raw mut (*rw).__i[0], val | (1i32 << 31), abs_timeout);
3918        a_fetch_sub(&raw mut (*rw).__i[1], 1);
3919        if e != 0 && e != EINTR { return e; }
3920    }
3921}
3922unsafe fn rwlock_timedwrlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
3923    let r = rwlock_trywrlock(rw);
3924    if r != EBUSY { return r; }
3925    let mut spins = 100;
3926    while spins > 0 { let r = rwlock_trywrlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
3927    loop {
3928        let r = rwlock_trywrlock(rw);
3929        if r != EBUSY { return r; }
3930        let val = a_load(&raw const (*rw).__i[0]);
3931        if val == 0 { continue; }
3932        a_fetch_add(&raw mut (*rw).__i[1], 1);
3933        a_cas(&raw mut (*rw).__i[0], val, val | (1i32 << 31));
3934        let e = futex_timedwait(&raw mut (*rw).__i[0], val | (1i32 << 31), abs_timeout);
3935        a_fetch_sub(&raw mut (*rw).__i[1], 1);
3936        if e != 0 && e != EINTR { return e; }
3937    }
3938}
3939
3940#[no_mangle]
3941pub unsafe extern "C" fn pthread_rwlock_init(rw: *mut pthread_rwlock_t, attr: *const pthread_rwlockattr_t) -> c_int {
3942    core::ptr::write_bytes(rw, 0, 1);
3943    if !attr.is_null() { (*rw).__i[2] = (*attr).__attr[0] as c_int & 128; }
3944    0
3945}
3946#[no_mangle]
3947pub unsafe extern "C" fn pthread_rwlock_destroy(_rw: *mut pthread_rwlock_t) -> c_int { 0 }
3948#[no_mangle]
3949pub unsafe extern "C" fn pthread_rwlock_rdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedrdlock(rw, core::ptr::null()) }
3950#[no_mangle]
3951pub unsafe extern "C" fn pthread_rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_tryrdlock(rw) }
3952#[no_mangle]
3953pub unsafe extern "C" fn pthread_rwlock_timedrdlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedrdlock(rw, t) }
3954#[no_mangle]
3955pub unsafe extern "C" fn pthread_rwlock_wrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedwrlock(rw, core::ptr::null()) }
3956#[no_mangle]
3957pub unsafe extern "C" fn pthread_rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_trywrlock(rw) }
3958#[no_mangle]
3959pub unsafe extern "C" fn pthread_rwlock_timedwrlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedwrlock(rw, t) }
3960#[no_mangle]
3961pub unsafe extern "C" fn pthread_rwlock_unlock(rw: *mut pthread_rwlock_t) -> c_int {
3962    loop {
3963        let val = a_load(&raw const (*rw).__i[0]);
3964        let cnt = val & 0x7fffffff;
3965        let new_val = if cnt == 0x7fffffff || cnt == 1 { 0 } else { val - 1 };
3966        if a_cas(&raw mut (*rw).__i[0], val, new_val) == val {
3967            if new_val == 0 && (a_load(&raw const (*rw).__i[1]) > 0 || val < 0) {
3968                futex_wake(&raw mut (*rw).__i[0], cnt);
3969            }
3970            return 0;
3971        }
3972    }
3973}
3974
3975// --- pthread_barrierattr_* ---
3976#[no_mangle]
3977pub unsafe extern "C" fn pthread_barrierattr_init(attr: *mut pthread_barrierattr_t) -> c_int { (*attr).__attr = 0; 0 }
3978#[no_mangle]
3979pub unsafe extern "C" fn pthread_barrierattr_destroy(_attr: *mut pthread_barrierattr_t) -> c_int { 0 }
3980#[no_mangle]
3981pub unsafe extern "C" fn pthread_barrierattr_setpshared(attr: *mut pthread_barrierattr_t, p: c_int) -> c_int {
3982    if (p as c_uint) > 1 { return EINVAL; }
3983    (*attr).__attr = p as c_uint; 0
3984}
3985#[no_mangle]
3986pub unsafe extern "C" fn pthread_barrierattr_getpshared(attr: *const pthread_barrierattr_t, p: *mut c_int) -> c_int {
3987    *p = (*attr).__attr as c_int; 0
3988}
3989
3990// --- pthread_barrier_* ---
3991#[no_mangle]
3992pub unsafe extern "C" fn pthread_barrier_init(b: *mut pthread_barrier_t, _attr: *const pthread_barrierattr_t, count: c_uint) -> c_int {
3993    if count == 0 { return EINVAL; }
3994    core::ptr::write_bytes(b, 0, 1);
3995    (*b).__i[2] = count as c_int - 1;
3996    0
3997}
3998#[no_mangle]
3999pub unsafe extern "C" fn pthread_barrier_destroy(_b: *mut pthread_barrier_t) -> c_int { 0 }
4000#[no_mangle]
4001pub unsafe extern "C" fn pthread_barrier_wait(b: *mut pthread_barrier_t) -> c_int {
4002    let limit = (*b).__i[2];
4003    if limit == 0 { return PTHREAD_BARRIER_SERIAL_THREAD; }
4004    spinlock_lock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4005    let arrived = a_load(&raw const (*b).__i[3]) + 1;
4006    a_store(&raw mut (*b).__i[3], arrived);
4007    if arrived > limit {
4008        a_store(&raw mut (*b).__i[3], 0);
4009        let gen = a_load(&raw const (*b).__i[4]);
4010        a_store(&raw mut (*b).__i[4], gen + 1);
4011        spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4012        futex_wake(&raw mut (*b).__i[4], -1);
4013        return PTHREAD_BARRIER_SERIAL_THREAD;
4014    }
4015    let gen = a_load(&raw const (*b).__i[4]);
4016    spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4017    while a_load(&raw const (*b).__i[4]) == gen {
4018        futex_wait(&raw mut (*b).__i[4], gen);
4019    }
4020    0
4021}
4022
4023// --- pthread_spin_* ---
4024#[no_mangle]
4025pub unsafe extern "C" fn pthread_spin_init(s: *mut pthread_spinlock_t, _pshared: c_int) -> c_int { a_store(s, 0); 0 }
4026#[no_mangle]
4027pub unsafe extern "C" fn pthread_spin_destroy(_s: *mut pthread_spinlock_t) -> c_int { 0 }
4028#[no_mangle]
4029pub unsafe extern "C" fn pthread_spin_lock(s: *mut pthread_spinlock_t) -> c_int {
4030    while a_load(s) != 0 || a_cas(s, 0, EBUSY) != 0 { core::hint::spin_loop(); }
4031    0
4032}
4033#[no_mangle]
4034pub unsafe extern "C" fn pthread_spin_trylock(s: *mut pthread_spinlock_t) -> c_int { a_cas(s, 0, EBUSY) }
4035#[no_mangle]
4036pub unsafe extern "C" fn pthread_spin_unlock(s: *mut pthread_spinlock_t) -> c_int { a_store(s, 0); 0 }
4037
4038// --- sem_* ---
4039#[no_mangle]
4040pub unsafe extern "C" fn sem_init(sem: *mut sem_t, pshared: c_int, value: c_uint) -> c_int {
4041    if value > SEM_VALUE_MAX as c_uint { return EINVAL; }
4042    (*sem).__val[0] = value as c_int;
4043    (*sem).__val[1] = 0;
4044    (*sem).__val[2] = if pshared != 0 { 0 } else { 128 };
4045    0
4046}
4047#[no_mangle]
4048pub unsafe extern "C" fn sem_destroy(_sem: *mut sem_t) -> c_int { 0 }
4049
4050unsafe fn sem_trywait_internal(sem: *mut sem_t) -> c_int {
4051    loop {
4052        let val = a_load(&raw const (*sem).__val[0]);
4053        if val & SEM_VALUE_MAX == 0 { return EAGAIN; }
4054        if a_cas(&raw mut (*sem).__val[0], val, val - 1) == val { return 0; }
4055    }
4056}
4057
4058#[no_mangle]
4059pub unsafe extern "C" fn sem_trywait(sem: *mut sem_t) -> c_int {
4060    if sem_trywait_internal(sem) == 0 { 0 } else { ERRNO!() = EAGAIN; -1 }
4061}
4062#[no_mangle]
4063pub unsafe extern "C" fn sem_wait(sem: *mut sem_t) -> c_int {
4064    pthread_testcancel();
4065    if sem_trywait_internal(sem) == 0 { return 0; }
4066    let mut spins = 100;
4067    while spins > 0 { if sem_trywait_internal(sem) == 0 { return 0; } core::hint::spin_loop(); spins -= 1; }
4068    loop {
4069        pthread_testcancel();
4070        if sem_trywait_internal(sem) == 0 { return 0; }
4071        let val = a_load(&raw const (*sem).__val[0]);
4072        if val & SEM_VALUE_MAX != 0 { continue; }
4073        a_cas(&raw mut (*sem).__val[0], val, val | (1i32 << 31));
4074        a_fetch_add(&raw mut (*sem).__val[1], 1);
4075        futex_wait(&raw mut (*sem).__val[0], 1i32 << 31);
4076        a_fetch_sub(&raw mut (*sem).__val[1], 1);
4077    }
4078}
4079#[no_mangle]
4080pub unsafe extern "C" fn sem_timedwait(sem: *mut sem_t, abs_timeout: *const timespec) -> c_int {
4081    pthread_testcancel();
4082    if sem_trywait_internal(sem) == 0 { return 0; }
4083    let mut spins = 100;
4084    while spins > 0 { if sem_trywait_internal(sem) == 0 { return 0; } core::hint::spin_loop(); spins -= 1; }
4085    loop {
4086        pthread_testcancel();
4087        if sem_trywait_internal(sem) == 0 { return 0; }
4088        let val = a_load(&raw const (*sem).__val[0]);
4089        if val & SEM_VALUE_MAX != 0 { continue; }
4090        a_cas(&raw mut (*sem).__val[0], val, val | (1i32 << 31));
4091        a_fetch_add(&raw mut (*sem).__val[1], 1);
4092        let e = futex_timedwait(&raw mut (*sem).__val[0], 1i32 << 31, abs_timeout);
4093        a_fetch_sub(&raw mut (*sem).__val[1], 1);
4094        if e != 0 && e != EINTR { ERRNO!() = e; return -1; }
4095    }
4096}
4097#[no_mangle]
4098pub unsafe extern "C" fn sem_post(sem: *mut sem_t) -> c_int {
4099    loop {
4100        let val = a_load(&raw const (*sem).__val[0]);
4101        if (val & SEM_VALUE_MAX) == SEM_VALUE_MAX { ERRNO!() = EOVERFLOW; return -1; }
4102        let mut new = val + 1;
4103        let waiters = a_load(&raw const (*sem).__val[1]);
4104        if waiters <= 1 { new &= !(1i32 << 31); }
4105        if a_cas(&raw mut (*sem).__val[0], val, new) == val {
4106            if val < 0 || waiters > 0 {
4107                futex_wake(&raw mut (*sem).__val[0], if waiters > 1 { 1 } else { -1 });
4108            }
4109            return 0;
4110        }
4111    }
4112}
4113#[no_mangle]
4114pub unsafe extern "C" fn sem_getvalue(sem: *mut sem_t, sval: *mut c_int) -> c_int {
4115    *sval = a_load(&raw const (*sem).__val[0]) & SEM_VALUE_MAX;
4116    0
4117}
4118
4119// ============================================================
4120// POSIX shared memory + named semaphores
4121// ============================================================
4122
4123const NAME_MAX: usize = 255;
4124const SEM_NSEMS_MAX: usize = 256;
4125
4126// ponytail: global spinlock for semtab, upgrade to per-entry if contention matters
4127static SEMTAB_LOCK: AtomicI32 = AtomicI32::new(0);
4128
4129struct SemEntry {
4130    ino: u64,
4131    sem: *mut sem_t,
4132    refcnt: u32,
4133}
4134
4135// ponytail: zero-init is fine for static mut (all-zero = free slots)
4136static mut SEMTAB: [SemEntry; SEM_NSEMS_MAX] = {
4137    const ZERO: SemEntry = SemEntry { ino: 0, sem: core::ptr::null_mut(), refcnt: 0 };
4138    [ZERO; SEM_NSEMS_MAX]
4139};
4140
4141unsafe fn semtab_lock() {
4142    while SEMTAB_LOCK.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed).is_err() {
4143        core::hint::spin_loop();
4144    }
4145}
4146
4147unsafe fn semtab_unlock() {
4148    SEMTAB_LOCK.store(0, Ordering::Release);
4149}
4150
4151// Validate shm/sem name and construct /dev/shm/<name> path.
4152// Returns path length or -1 with ERRNO set.
4153unsafe fn shm_mapname(name: *const c_char, buf: *mut u8) -> c_int {
4154    let mut p = name;
4155    // strip leading /
4156    while *p == b'/' as c_char { p = p.add(1); }
4157    let start = p;
4158    // find end of first component
4159    while *p != 0 && *p != b'/' as c_char { p = p.add(1); }
4160    let len = p.offset_from(start) as usize;
4161    // no trailing /, not empty, not "." or ".."
4162    if len == 0 || *p != 0 {
4163        ERRNO!() = EINVAL;
4164        return -1;
4165    }
4166    if len == 1 && *start == b'.' as c_char {
4167        ERRNO!() = EINVAL;
4168        return -1;
4169    }
4170    if len == 2 && *start == b'.' as c_char && *start.add(1) == b'.' as c_char {
4171        ERRNO!() = EINVAL;
4172        return -1;
4173    }
4174    if len > NAME_MAX {
4175        ERRNO!() = ENAMETOOLONG;
4176        return -1;
4177    }
4178    // build /dev/shm/<name>
4179    let prefix = b"/dev/shm/\0";
4180    let mut i = 0;
4181    while prefix[i] != 0 {
4182        *buf.add(i) = prefix[i];
4183        i += 1;
4184    }
4185    let mut j = 0;
4186    while j < len {
4187        *buf.add(i + j) = *start.add(j) as u8;
4188        j += 1;
4189    }
4190    *buf.add(i + j) = 0;
4191    (i + j) as c_int
4192}
4193
4194#[no_mangle]
4195pub unsafe extern "C" fn shm_open(name: *const c_char, flags: c_int, mode: mode_t) -> c_int {
4196    let mut buf = [0u8; 16 + NAME_MAX + 1];
4197    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
4198    let fd = sys_open(buf.as_ptr(), (flags | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
4199    if fd < 0 { ERRNO!() = (-fd) as c_int; return -1; }
4200    fd as c_int
4201}
4202
4203#[no_mangle]
4204pub unsafe extern "C" fn shm_unlink(name: *const c_char) -> c_int {
4205    let mut buf = [0u8; 16 + NAME_MAX + 1];
4206    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
4207    let r = sys_unlink(buf.as_ptr());
4208    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
4209    0
4210}
4211
4212#[no_mangle]
4213pub unsafe extern "C" fn sem_open(name: *const c_char, flags: c_int, mut args: ...) -> *mut sem_t {
4214    let mut buf = [0u8; 16 + NAME_MAX + 1];
4215    if shm_mapname(name, buf.as_mut_ptr()).is_negative() {
4216        return core::ptr::null_mut(); // SEM_FAILED
4217    }
4218
4219    let oflags = flags & (O_CREAT | O_EXCL);
4220
4221    semtab_lock();
4222
4223    // find a free slot
4224    let mut slot: c_int = -1;
4225    for i in 0..SEMTAB_LEN {
4226        if SEMTAB[i].sem.is_null() && slot < 0 { slot = i as c_int; }
4227    }
4228    if slot < 0 {
4229        ERRNO!() = EMFILE;
4230        semtab_unlock();
4231        return core::ptr::null_mut();
4232    }
4233    // reserve slot
4234    SEMTAB[slot as usize].sem = !0usize as *mut sem_t; // sentinel
4235    semtab_unlock();
4236
4237    // extract va_args for O_CREAT
4238    let mut mode: mode_t = 0;
4239    let mut value: c_uint = 0;
4240    if oflags & O_CREAT != 0 {
4241        mode = args.next_arg::<mode_t>() & 0o666;
4242        value = args.next_arg::<c_uint>();
4243        if value > SEM_VALUE_MAX as c_uint {
4244            ERRNO!() = EINVAL;
4245            semtab_lock();
4246            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4247            semtab_unlock();
4248            return core::ptr::null_mut();
4249        }
4250    }
4251
4252    // try opening existing first (unless O_CREAT|O_EXCL)
4253    if oflags != O_CREAT | O_EXCL {
4254        let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
4255        if fd >= 0 {
4256            let map = sys_mmap(
4257                core::ptr::null_mut(),
4258                core::mem::size_of::<sem_t>(),
4259                PROT_READ | PROT_WRITE,
4260                MAP_SHARED,
4261                fd as i32,
4262                0,
4263            );
4264            sys_close(fd);
4265            if map != MMAP_FAILED {
4266                let st_ino = get_ino(fd as c_int, buf.as_ptr());
4267                return sem_register(map as *mut sem_t, st_ino, slot);
4268            }
4269        }
4270        if oflags == 0 {
4271            // no O_CREAT and file doesn't exist
4272            semtab_lock();
4273            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4274            semtab_unlock();
4275            return core::ptr::null_mut();
4276        }
4277    }
4278
4279    // create: write sem_t to temp file, mmap, link
4280    let mut tmp = [0u8; 32];
4281    let tmpname = b"/dev/shm/tmp-XXXXXX\0";
4282    tmp[..tmpname.len()].copy_from_slice(tmpname);
4283    // use clock for unique name
4284    let mut ts: timespec = core::mem::zeroed();
4285    sys_clock_gettime(0, &mut ts);
4286    // append ns to tmp name
4287    let mut n = ts.tv_nsec;
4288    let mut pos = tmpname.len() - 1;
4289    tmp[pos] = 0;
4290    pos -= 1;
4291    loop {
4292        tmp[pos] = b'0' + (n % 10) as u8;
4293        n /= 10;
4294        if n == 0 || pos == 0 { break; }
4295        pos -= 1;
4296    }
4297        // shift to start of number part
4298        let tmp_path = tmp.as_ptr();
4299
4300    let mut newsem: sem_t = core::mem::zeroed();
4301    newsem.__val[0] = value as c_int;
4302    newsem.__val[1] = 0;
4303    newsem.__val[2] = 128; // pshared=0 flag
4304
4305    loop {
4306        let fd = sys_open(tmp_path as *const u8, (O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
4307        if fd < 0 {
4308            if (-fd) as c_int == EEXIST { continue; }
4309            semtab_lock();
4310            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4311            semtab_unlock();
4312            return core::ptr::null_mut();
4313        }
4314        let written = sys_write(fd, &newsem as *const sem_t as *const u8, core::mem::size_of::<sem_t>());
4315        if written != core::mem::size_of::<sem_t>() as i64 {
4316            sys_close(fd);
4317            sys_unlink(tmp_path);
4318            semtab_lock();
4319            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4320            semtab_unlock();
4321            return core::ptr::null_mut();
4322        }
4323        let map = sys_mmap(
4324            core::ptr::null_mut(),
4325            core::mem::size_of::<sem_t>(),
4326            PROT_READ | PROT_WRITE,
4327            MAP_SHARED,
4328            fd as i32,
4329            0,
4330        );
4331        sys_close(fd);
4332        if map == MMAP_FAILED {
4333            sys_unlink(tmp_path);
4334            semtab_lock();
4335            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4336            semtab_unlock();
4337            return core::ptr::null_mut();
4338        }
4339        // link to final name
4340        let r = sys_linkat(AT_FDCWD, tmp_path, AT_FDCWD, buf.as_ptr(), 0);
4341        let e = if r < 0 { (-r) as c_int } else { 0 };
4342        sys_unlink(tmp_path);
4343        if e == 0 {
4344            let st_ino = get_ino(-1, buf.as_ptr());
4345            return sem_register(map as *mut sem_t, st_ino, slot);
4346        }
4347        sys_munmap(map, core::mem::size_of::<sem_t>());
4348        if e != EEXIST || oflags == O_CREAT | O_EXCL {
4349            ERRNO!() = e;
4350            semtab_lock();
4351            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4352            semtab_unlock();
4353            return core::ptr::null_mut();
4354        }
4355        // EEXIST without O_EXCL: retry open existing
4356        break;
4357    }
4358
4359    // fallthrough: try opening the existing file that won the race
4360    let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
4361    if fd < 0 {
4362        semtab_lock();
4363        SEMTAB[slot as usize].sem = core::ptr::null_mut();
4364        semtab_unlock();
4365        return core::ptr::null_mut();
4366    }
4367    let map = sys_mmap(
4368        core::ptr::null_mut(),
4369        core::mem::size_of::<sem_t>(),
4370        PROT_READ | PROT_WRITE,
4371        MAP_SHARED,
4372        fd as i32,
4373        0,
4374    );
4375    sys_close(fd);
4376    if map == MMAP_FAILED {
4377        semtab_lock();
4378        SEMTAB[slot as usize].sem = core::ptr::null_mut();
4379        semtab_unlock();
4380        return core::ptr::null_mut();
4381    }
4382    let st_ino = get_ino(-1, buf.as_ptr());
4383    sem_register(map as *mut sem_t, st_ino, slot)
4384}
4385
4386unsafe fn get_ino(_fd_hint: c_int, path: *const u8) -> u64 {
4387    let mut st: Stat = core::mem::zeroed();
4388    if sys_newfstatat(AT_FDCWD, path as *const c_char, &mut st as *mut Stat as *mut u8, 0) == 0 {
4389        st.st_ino
4390    } else {
4391        0
4392    }
4393}
4394
4395unsafe fn sem_register(map: *mut sem_t, ino: u64, slot_hint: c_int) -> *mut sem_t {
4396    semtab_lock();
4397    // check if already mapped (by inode)
4398    for i in 0..SEMTAB_LEN {
4399        if SEMTAB[i].ino == ino && !SEMTAB[i].sem.is_null() && SEMTAB[i].sem != !0usize as *mut sem_t {
4400            // already mapped: unmap new, use existing, release hint slot
4401            sys_munmap(map as *mut u8, core::mem::size_of::<sem_t>());
4402            SEMTAB[slot_hint as usize].sem = core::ptr::null_mut();
4403            SEMTAB[i].refcnt += 1;
4404            let ret = SEMTAB[i].sem;
4405            semtab_unlock();
4406            return ret;
4407        }
4408    }
4409    // new entry
4410    SEMTAB[slot_hint as usize].sem = map;
4411    SEMTAB[slot_hint as usize].ino = ino;
4412    SEMTAB[slot_hint as usize].refcnt = 1;
4413    semtab_unlock();
4414    map
4415}
4416
4417const SEMTAB_LEN: usize = SEM_NSEMS_MAX;
4418
4419#[no_mangle]
4420pub unsafe extern "C" fn sem_close(sem: *mut sem_t) -> c_int {
4421    semtab_lock();
4422    for i in 0..SEMTAB_LEN {
4423        if SEMTAB[i].sem == sem {
4424            SEMTAB[i].refcnt -= 1;
4425            if SEMTAB[i].refcnt == 0 {
4426                SEMTAB[i].sem = core::ptr::null_mut();
4427                SEMTAB[i].ino = 0;
4428                semtab_unlock();
4429                sys_munmap(sem as *mut u8, core::mem::size_of::<sem_t>());
4430                return 0;
4431            }
4432            semtab_unlock();
4433            return 0;
4434        }
4435    }
4436    semtab_unlock();
4437    0
4438}
4439
4440#[no_mangle]
4441pub unsafe extern "C" fn sem_unlink(name: *const c_char) -> c_int {
4442    shm_unlink(name)
4443}
4444
4445// --- pthread_once ---
4446#[no_mangle]
4447pub unsafe extern "C" fn pthread_once(control: *mut pthread_once_t, init_routine: Option<unsafe extern "C" fn()>) -> c_int {
4448    if a_load(control) == 2 { return 0; }
4449    loop {
4450        match a_cas(control, 0, 1) {
4451            0 => {
4452                if let Some(f) = init_routine { f(); }
4453                if a_swap(control, 2) == 3 { futex_wake(control, -1); }
4454                return 0;
4455            }
4456            1 => { a_cas(control, 1, 3); }
4457            3 => { futex_wait(control, 3); }
4458            _ => { return 0; }
4459        }
4460    }
4461}
4462
4463// --- pthread_key_* ---
4464#[no_mangle]
4465pub unsafe extern "C" fn pthread_key_create(key: *mut pthread_key_t, dtor: Option<unsafe extern "C" fn(*mut c_void)>) -> c_int {
4466    let start = NEXT_KEY.load(Ordering::Relaxed);
4467    let mut j = start;
4468    loop {
4469        if KEY_DTORS[j].is_none() {
4470            KEY_DTORS[j] = dtor;
4471            NEXT_KEY.store((j + 1) % PTHREAD_KEYS_MAX, Ordering::Relaxed);
4472            *key = j as pthread_key_t;
4473            return 0;
4474        }
4475        j = (j + 1) % PTHREAD_KEYS_MAX;
4476        if j == start { return EAGAIN; }
4477    }
4478}
4479#[no_mangle]
4480pub unsafe extern "C" fn pthread_key_delete(key: pthread_key_t) -> c_int {
4481    KEY_DTORS[key as usize] = None;
4482    let count = thread_slot_count();
4483    let mut i = 0usize;
4484    while i < count {
4485        let slot = thread_slot_at(i);
4486        if core::ptr::read_volatile(&raw const (*slot).tid) > 0 {
4487            (*slot).tsd[key as usize] = core::ptr::null_mut();
4488        }
4489        i += 1;
4490    }
4491    0
4492}
4493#[no_mangle]
4494pub unsafe extern "C" fn pthread_getspecific(key: pthread_key_t) -> *mut c_void {
4495    if let Some(slot) = find_thread() { slot.tsd[key as usize] } else { core::ptr::null_mut() }
4496}
4497#[no_mangle]
4498pub unsafe extern "C" fn pthread_setspecific(key: pthread_key_t, value: *const c_void) -> c_int {
4499    if let Some(slot) = find_thread() {
4500        slot.tsd[key as usize] = value as *mut c_void;
4501        0
4502    } else { EINVAL }
4503}
4504
4505// --- pthread_cancel/state ---
4506unsafe fn run_cleanup_handlers(slot: &mut Thread) {
4507    let mut cb = slot.cancelbuf;
4508    while !cb.is_null() {
4509        let cur = &*cb;
4510        let f = cur.__f;
4511        let x = cur.__x;
4512        cb = cur.__next;
4513        if let Some(func) = f {
4514            func(x);
4515        }
4516    }
4517    slot.cancelbuf = core::ptr::null_mut();
4518}
4519
4520unsafe fn do_cancel() -> ! {
4521    if let Some(slot) = find_thread() {
4522        run_cleanup_handlers(slot);
4523        slot.result = !0usize as *mut c_void; // PTHREAD_CANCELED
4524        slot.detach_state = DT_EXITED;
4525        futex_wake(&raw mut slot.detach_state, 1);
4526    }
4527    sys_exit_thread(0);
4528}
4529
4530extern "C" fn cancel_handler(_sig: c_int) {
4531    unsafe {
4532        if let Some(slot) = find_thread() {
4533            // In asynchronous mode, cancel immediately from the signal handler.
4534            // In deferred mode, the signal just interrupts blocking syscalls so
4535            // the next cancellation point can act on the pending request.
4536            if slot.cancel != 0
4537                && slot.cancel_state == PTHREAD_CANCEL_ENABLE
4538                && slot.cancel_type == PTHREAD_CANCEL_ASYNCHRONOUS
4539            {
4540                do_cancel();
4541            }
4542        }
4543    }
4544}
4545
4546static CANCEL_INIT: AtomicI32 = AtomicI32::new(0);
4547
4548unsafe fn ensure_cancel_handler() {
4549    if CANCEL_INIT.swap(1, Ordering::AcqRel) == 0 {
4550        let act = KSigAction {
4551            sa_handler: cancel_handler as *const () as usize,
4552            sa_flags: SA_RESTORER,
4553            sa_restorer: sig_restorer as *const () as usize,
4554            sa_mask: [!0u64],
4555        };
4556        sys_rt_sigaction(SIGCANCEL, &act as *const KSigAction, core::ptr::null_mut(), 8);
4557    }
4558}
4559
4560#[no_mangle]
4561pub unsafe extern "C" fn pthread_cancel(thread: PthreadT) -> c_int {
4562    let slot = thread as *mut Thread;
4563    if slot.is_null() { return EINVAL; }
4564    ensure_cancel_handler();
4565    a_store(&raw mut (*slot).cancel, 1);
4566    let tid = (*slot).tid;
4567    if tid > 0 {
4568        sys_tgkill(sys_getpid() as c_int, tid, SIGCANCEL);
4569    }
4570    0
4571}
4572#[no_mangle]
4573pub unsafe extern "C" fn pthread_setcancelstate(state: c_int, oldstate: *mut c_int) -> c_int {
4574    if state != PTHREAD_CANCEL_ENABLE && state != PTHREAD_CANCEL_DISABLE { return EINVAL; }
4575    if let Some(slot) = find_thread() {
4576        if !oldstate.is_null() { *oldstate = slot.cancel_state; }
4577        slot.cancel_state = state;
4578        0
4579    } else { EINVAL }
4580}
4581#[no_mangle]
4582pub unsafe extern "C" fn pthread_setcanceltype(type_: c_int, oldtype: *mut c_int) -> c_int {
4583    if type_ != PTHREAD_CANCEL_DEFERRED && type_ != PTHREAD_CANCEL_ASYNCHRONOUS { return EINVAL; }
4584    if let Some(slot) = find_thread() {
4585        if !oldtype.is_null() { *oldtype = slot.cancel_type; }
4586        slot.cancel_type = type_;
4587        0
4588    } else { EINVAL }
4589}
4590#[no_mangle]
4591pub unsafe extern "C" fn pthread_testcancel() {
4592    if let Some(slot) = find_thread() {
4593        if slot.cancel != 0 && slot.cancel_state == PTHREAD_CANCEL_ENABLE {
4594            do_cancel();
4595        }
4596    }
4597}
4598
4599#[no_mangle]
4600pub unsafe extern "C" fn _pthread_cleanup_push(cb: *mut __ptcb, f: Option<unsafe extern "C" fn(*mut c_void)>, x: *mut c_void) {
4601    (*cb).__f = f;
4602    (*cb).__x = x;
4603    if let Some(slot) = find_thread() {
4604        (*cb).__next = slot.cancelbuf;
4605        slot.cancelbuf = cb;
4606    } else {
4607        (*cb).__next = core::ptr::null_mut();
4608    }
4609}
4610
4611#[no_mangle]
4612pub unsafe extern "C" fn _pthread_cleanup_pop(cb: *mut __ptcb, run: c_int) {
4613    if let Some(slot) = find_thread() {
4614        slot.cancelbuf = (*cb).__next;
4615    }
4616    if run != 0 {
4617        if let Some(f) = (*cb).__f {
4618            f((*cb).__x);
4619        }
4620    }
4621}
4622
4623#[no_mangle]
4624pub unsafe extern "C" fn pthread_kill(thread: PthreadT, sig: c_int) -> c_int {
4625    let slot = thread as *mut Thread;
4626    if slot.is_null() { return EINVAL; }
4627    let tid = (*slot).tid;
4628    if tid <= 0 { return EINVAL; }
4629    if sys_tgkill(sys_getpid() as c_int, tid, sig) < 0 { -1 } else { 0 }
4630}
4631
4632#[no_mangle]
4633pub unsafe extern "C" fn pthread_sigmask(how: c_int, set: *const SigSetT, oldset: *mut SigSetT) -> c_int {
4634    // POSIX pthread functions return the error number itself, not -1/errno.
4635    if sigprocmask(how, set, oldset) < 0 { ERRNO!() } else { 0 }
4636}
4637
4638
4639#[repr(C)]
4640pub struct lconv {
4641    pub decimal_point: *mut c_char,
4642    pub thousands_sep: *mut c_char,
4643    pub grouping: *mut c_char,
4644    pub int_curr_symbol: *mut c_char,
4645    pub currency_symbol: *mut c_char,
4646    pub mon_decimal_point: *mut c_char,
4647    pub mon_thousands_sep: *mut c_char,
4648    pub mon_grouping: *mut c_char,
4649    pub positive_sign: *mut c_char,
4650    pub negative_sign: *mut c_char,
4651    pub int_frac_digits: c_char,
4652    pub frac_digits: c_char,
4653    pub p_cs_precedes: c_char,
4654    pub p_sep_by_space: c_char,
4655    pub n_cs_precedes: c_char,
4656    pub n_sep_by_space: c_char,
4657    pub p_sign_posn: c_char,
4658    pub n_sign_posn: c_char,
4659    pub int_p_cs_precedes: c_char,
4660    pub int_p_sep_by_space: c_char,
4661    pub int_n_cs_precedes: c_char,
4662    pub int_n_sep_by_space: c_char,
4663    pub int_p_sign_posn: c_char,
4664    pub int_n_sign_posn: c_char,
4665}
4666
4667static UTF8_NAME: [u8; 6] = [b'U', b'T', b'F', b'-', b'8', 0];
4668static C_NAME: [u8; 2] = [b'C', 0];
4669static mut LOCALE_NAME: *const c_char = C_NAME.as_ptr() as *const c_char;
4670static mut LOCALE_CTYPE_UTF8: bool = true;
4671static mut EMPTY_STR: [c_char; 1] = [0];
4672static mut DECIMAL_POINT: [c_char; 2] = [b'.' as c_char, 0];
4673static mut LCONV: lconv = lconv {
4674    decimal_point: core::ptr::null_mut(),
4675    thousands_sep: core::ptr::null_mut(),
4676    grouping: core::ptr::null_mut(),
4677    int_curr_symbol: core::ptr::null_mut(),
4678    currency_symbol: core::ptr::null_mut(),
4679    mon_decimal_point: core::ptr::null_mut(),
4680    mon_thousands_sep: core::ptr::null_mut(),
4681    mon_grouping: core::ptr::null_mut(),
4682    positive_sign: core::ptr::null_mut(),
4683    negative_sign: core::ptr::null_mut(),
4684    int_frac_digits: (-1i32) as c_char,
4685    frac_digits: (-1i32) as c_char,
4686    p_cs_precedes: (-1i32) as c_char,
4687    p_sep_by_space: (-1i32) as c_char,
4688    n_cs_precedes: (-1i32) as c_char,
4689    n_sep_by_space: (-1i32) as c_char,
4690    p_sign_posn: (-1i32) as c_char,
4691    n_sign_posn: (-1i32) as c_char,
4692    int_p_cs_precedes: (-1i32) as c_char,
4693    int_p_sep_by_space: (-1i32) as c_char,
4694    int_n_cs_precedes: (-1i32) as c_char,
4695    int_n_sep_by_space: (-1i32) as c_char,
4696    int_p_sign_posn: (-1i32) as c_char,
4697    int_n_sign_posn: (-1i32) as c_char,
4698};
4699
4700unsafe fn cstr_contains_ci(s: *const u8, needle: &[u8]) -> bool {
4701    let len = strlen(s as *const c_char) as usize;
4702    let s_slice = core::slice::from_raw_parts(s, len);
4703    if needle.len() > len { return false; }
4704    for i in 0..=len - needle.len() {
4705        if s_slice[i..i + needle.len()].eq_ignore_ascii_case(needle) {
4706            return true;
4707        }
4708    }
4709    false
4710}
4711
4712#[no_mangle]
4713pub unsafe extern "C" fn setlocale(_category: c_int, locale: *const c_char) -> *mut c_char {
4714    if locale.is_null() || *locale == 0 {
4715        return LOCALE_NAME as *mut c_char;
4716    }
4717    let name = locale as *const u8;
4718    if strcmp(name, b"C\0".as_ptr()) == 0 || strcmp(name, b"POSIX\0".as_ptr()) == 0 {
4719        LOCALE_CTYPE_UTF8 = false;
4720        return LOCALE_NAME as *mut c_char;
4721    }
4722    if cstr_contains_ci(name, b"UTF-8") || cstr_contains_ci(name, b"UTF8") {
4723        LOCALE_CTYPE_UTF8 = true;
4724        return LOCALE_NAME as *mut c_char;
4725    }
4726    core::ptr::null_mut()
4727}
4728
4729#[no_mangle]
4730pub unsafe extern "C" fn localeconv() -> *mut lconv {
4731    let empty = core::ptr::addr_of_mut!(EMPTY_STR) as *mut c_char;
4732    let lconv = core::ptr::addr_of_mut!(LCONV);
4733    (*lconv).decimal_point = core::ptr::addr_of_mut!(DECIMAL_POINT) as *mut c_char;
4734    (*lconv).thousands_sep = empty;
4735    (*lconv).grouping = empty;
4736    (*lconv).int_curr_symbol = empty;
4737    (*lconv).currency_symbol = empty;
4738    (*lconv).mon_decimal_point = empty;
4739    (*lconv).mon_thousands_sep = empty;
4740    (*lconv).mon_grouping = empty;
4741    (*lconv).positive_sign = empty;
4742    (*lconv).negative_sign = empty;
4743    lconv
4744}
4745
4746pub type locale_t = *mut c_void;
4747static mut CURRENT_LOCALE: locale_t = LC_GLOBAL_LOCALE;
4748
4749static mut C_LOCALE_STORAGE: c_int = 0;
4750const C_LOCALE: locale_t = core::ptr::addr_of_mut!(C_LOCALE_STORAGE) as locale_t;
4751const LC_GLOBAL_LOCALE: locale_t = usize::MAX as locale_t;
4752
4753#[no_mangle]
4754pub unsafe extern "C" fn newlocale(_mask: c_int, name: *const c_char, base: locale_t) -> locale_t {
4755    if !name.is_null() && *name != 0 {
4756        let n = name as *const u8;
4757        if strcmp(n, b"C\0".as_ptr()) != 0
4758            && strcmp(n, b"POSIX\0".as_ptr()) != 0
4759        {
4760            return core::ptr::null_mut();
4761        }
4762    }
4763    if base.is_null() || base == C_LOCALE || base == LC_GLOBAL_LOCALE {
4764        C_LOCALE
4765    } else {
4766        core::ptr::null_mut()
4767    }
4768}
4769
4770#[no_mangle]
4771pub unsafe extern "C" fn freelocale(_loc: locale_t) {}
4772
4773#[no_mangle]
4774pub unsafe extern "C" fn uselocale(loc: locale_t) -> locale_t {
4775    let old = CURRENT_LOCALE;
4776    if !loc.is_null() {
4777        CURRENT_LOCALE = loc;
4778    }
4779    old
4780}
4781
4782#[no_mangle]
4783pub unsafe extern "C" fn duplocale(loc: locale_t) -> locale_t {
4784    if loc.is_null() {
4785        return core::ptr::null_mut();
4786    }
4787    C_LOCALE
4788}
4789
4790const NL_ITEM_CODESET: c_int = 14;
4791const NL_ITEM_RADIXCHAR: c_int = 0x10000;
4792const NL_ITEM_THOUSEP: c_int = 0x10001;
4793const NL_ITEM_YESEXPR: c_int = 0x50000;
4794const NL_ITEM_NOEXPR: c_int = 0x50001;
4795
4796const C_TIME_STRINGS: &[u8] = b"Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat\0\
4797Sunday\0Monday\0Tuesday\0Wednesday\0Thursday\0Friday\0Saturday\0\
4798Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec\0\
4799January\0February\0March\0April\0May\0June\0July\0August\0\
4800September\0October\0November\0December\0\
4801AM\0PM\0\
4802%a %b %e %T %Y\0%m/%d/%y\0%H:%M:%S\0%I:%M:%S %p\0\
4803\0\0%m/%d/%y\00123456789\0%a %b %e %T %Y\0%H:%M:%S\0";
4804
4805const C_NUMERIC_STRINGS: &[u8] = b".\0\0";
4806const C_MESSAGES_STRINGS: &[u8] = b"^[yY]\0^[nN]\0";
4807
4808unsafe fn langinfo_str(table: *const u8, mut idx: c_int) -> *mut c_char {
4809    let mut p = table;
4810    while idx > 0 {
4811        while *p != 0 { p = p.add(1); }
4812        p = p.add(1);
4813        idx -= 1;
4814    }
4815    p as *mut c_char
4816}
4817
4818#[no_mangle]
4819pub unsafe extern "C" fn nl_langinfo(item: c_int) -> *mut c_char {
4820    if item == NL_ITEM_CODESET {
4821        return if LOCALE_CTYPE_UTF8 {
4822            b"UTF-8\0".as_ptr() as *mut c_char
4823        } else {
4824            b"US-ASCII\0".as_ptr() as *mut c_char
4825        };
4826    }
4827    let cat = item >> 16;
4828    let idx = item & 0xFFFF;
4829    match cat {
4830        1 => {
4831            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
4832            langinfo_str(C_NUMERIC_STRINGS.as_ptr(), idx)
4833        }
4834        2 => {
4835            if idx > 49 { return b"\0".as_ptr() as *mut c_char; }
4836            langinfo_str(C_TIME_STRINGS.as_ptr(), idx)
4837        }
4838        5 => {
4839            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
4840            langinfo_str(C_MESSAGES_STRINGS.as_ptr(), idx)
4841        }
4842        _ => b"\0".as_ptr() as *mut c_char,
4843    }
4844}
4845
4846pub type nl_catd = *mut c_void;
4847
4848#[no_mangle]
4849pub unsafe extern "C" fn catopen(_name: *const c_char, _oflag: c_int) -> nl_catd {
4850    !0usize as nl_catd
4851}
4852
4853#[no_mangle]
4854pub unsafe extern "C" fn catclose(_catd: nl_catd) -> c_int { 0 }
4855
4856#[no_mangle]
4857pub unsafe extern "C" fn catgets(catd: nl_catd, _set_id: c_int, _msg_id: c_int, s: *const c_char) -> *mut c_char {
4858    if catd == !0usize as nl_catd { return s as *mut c_char; }
4859    s as *mut c_char
4860}
4861
4862pub type IconvT = *mut c_void;
4863
4864const ENC_UTF8: i32 = 1;
4865const ENC_UTF16LE: i32 = 2;
4866const ENC_UTF16BE: i32 = 3;
4867const ENC_UTF32LE: i32 = 4;
4868const ENC_UTF32BE: i32 = 5;
4869const ENC_WCHAR_T: i32 = 6;
4870const ENC_ASCII: i32 = 7;
4871const ENC_LATIN1: i32 = 8;
4872const ENC_WIN1252: i32 = 9;
4873const ENC_WIN1251: i32 = 10;
4874const ENC_KOI8R: i32 = 11;
4875const ENC_GBK: i32 = 12;
4876const ENC_GB2312: i32 = 13;
4877const ENC_BIG5: i32 = 14;
4878const ENC_EUCJP: i32 = 15;
4879const ENC_SHIFTJIS: i32 = 16;
4880const ENC_ISO8859_2: i32 = 17;
4881const ENC_ISO8859_3: i32 = 18;
4882const ENC_ISO8859_4: i32 = 19;
4883const ENC_ISO8859_5: i32 = 20;
4884const ENC_ISO8859_6: i32 = 21;
4885const ENC_ISO8859_7: i32 = 22;
4886const ENC_ISO8859_8: i32 = 23;
4887const ENC_ISO8859_9: i32 = 24;
4888const ENC_ISO8859_10: i32 = 25;
4889const ENC_ISO8859_11: i32 = 26;
4890const ENC_ISO8859_13: i32 = 27;
4891const ENC_ISO8859_14: i32 = 28;
4892const ENC_ISO8859_15: i32 = 29;
4893const ENC_ISO8859_16: i32 = 30;
4894
4895include!("iconv_iso8859.rs");
4896
4897fn make_cd(from: i32, to: i32) -> IconvT {
4898    ((from as usize) << 16 | (to as usize) << 1 | 1) as IconvT
4899}
4900fn extract_from(cd: IconvT) -> i32 {
4901    ((cd as usize) >> 16) as i32
4902}
4903fn extract_to(cd: IconvT) -> i32 {
4904    (((cd as usize) >> 1) & 0x7fff) as i32
4905}
4906
4907unsafe fn match_name(input: *const u8, target: &[u8]) -> bool {
4908    let mut i = input;
4909    let mut j = 0;
4910    while *i != 0 && j < target.len() {
4911        let mut c = *i;
4912        if !c.is_ascii_alphanumeric() { i = i.add(1); continue; }
4913        c = c.to_ascii_lowercase();
4914        if c != target[j] { return false; }
4915        i = i.add(1);
4916        j += 1;
4917    }
4918    while *i != 0 && !(*i).is_ascii_alphanumeric() { i = i.add(1); }
4919    *i == 0 && j == target.len()
4920}
4921
4922unsafe fn find_encoding(name: *const u8) -> i32 {
4923    if name.is_null() { return -1; }
4924    if match_name(name, b"utf8") || match_name(name, b"utf-8") || match_name(name, b"char") { return ENC_UTF8; }
4925    if match_name(name, b"utf16le") || match_name(name, b"utf-16le") { return ENC_UTF16LE; }
4926    if match_name(name, b"utf16be") || match_name(name, b"utf-16be") { return ENC_UTF16BE; }
4927    if match_name(name, b"utf32le") || match_name(name, b"utf-32le") || match_name(name, b"ucs4le") { return ENC_UTF32LE; }
4928    if match_name(name, b"utf32be") || match_name(name, b"utf-32be") || match_name(name, b"ucs4be") { return ENC_UTF32BE; }
4929    if match_name(name, b"wchart") || match_name(name, b"wchar-t") { return ENC_WCHAR_T; }
4930    if match_name(name, b"ascii") || match_name(name, b"usascii") || match_name(name, b"iso646") { return ENC_ASCII; }
4931    if match_name(name, b"iso88591") || match_name(name, b"iso-8859-1") || match_name(name, b"latin1") { return ENC_LATIN1; }
4932    if match_name(name, b"iso88592") || match_name(name, b"iso-8859-2") { return ENC_ISO8859_2; }
4933    if match_name(name, b"iso88593") || match_name(name, b"iso-8859-3") { return ENC_ISO8859_3; }
4934    if match_name(name, b"iso88594") || match_name(name, b"iso-8859-4") { return ENC_ISO8859_4; }
4935    if match_name(name, b"iso88595") || match_name(name, b"iso-8859-5") { return ENC_ISO8859_5; }
4936    if match_name(name, b"iso88596") || match_name(name, b"iso-8859-6") { return ENC_ISO8859_6; }
4937    if match_name(name, b"iso88597") || match_name(name, b"iso-8859-7") { return ENC_ISO8859_7; }
4938    if match_name(name, b"iso88598") || match_name(name, b"iso-8859-8") { return ENC_ISO8859_8; }
4939    if match_name(name, b"iso88599") || match_name(name, b"iso-8859-9") { return ENC_ISO8859_9; }
4940    if match_name(name, b"iso885910") || match_name(name, b"iso-8859-10") { return ENC_ISO8859_10; }
4941    if match_name(name, b"iso885911") || match_name(name, b"iso-8859-11") || match_name(name, b"tis620") { return ENC_ISO8859_11; }
4942    if match_name(name, b"iso885913") || match_name(name, b"iso-8859-13") { return ENC_ISO8859_13; }
4943    if match_name(name, b"iso885914") || match_name(name, b"iso-8859-14") { return ENC_ISO8859_14; }
4944    if match_name(name, b"iso885915") || match_name(name, b"iso-8859-15") { return ENC_ISO8859_15; }
4945    if match_name(name, b"iso885916") || match_name(name, b"iso-8859-16") { return ENC_ISO8859_16; }
4946    if match_name(name, b"cp1252") || match_name(name, b"windows1252") || match_name(name, b"windows-1252") { return ENC_WIN1252; }
4947    if match_name(name, b"cp1251") || match_name(name, b"windows1251") || match_name(name, b"windows-1251") { return ENC_WIN1251; }
4948    if match_name(name, b"koi8r") || match_name(name, b"koi8-r") { return ENC_KOI8R; }
4949    if match_name(name, b"gbk") || match_name(name, b"cp936") { return ENC_GBK; }
4950    if match_name(name, b"gb2312") { return ENC_GB2312; }
4951    if match_name(name, b"big5") || match_name(name, b"bigfive") || match_name(name, b"cp950") { return ENC_BIG5; }
4952    if match_name(name, b"eucjp") || match_name(name, b"euc-jp") { return ENC_EUCJP; }
4953    if match_name(name, b"shiftjis") || match_name(name, b"sjis") || match_name(name, b"cp932") { return ENC_SHIFTJIS; }
4954    -1
4955}
4956
4957fn uni_to_jis(c: u32) -> u16 {
4958    let mut b = 0usize;
4959    let mut nel = REV_JIS.len();
4960    loop {
4961        let i = nel / 2;
4962        let j = REV_JIS[b + i] as usize;
4963        let row = j / 256;
4964        let col = j % 256;
4965        let d = JIS0208[row * 94 + col] as u32;
4966        if d == c { return (j as u16) + 0x2121; }
4967        if nel == 1 { return 0; }
4968        if c < d { nel /= 2; }
4969        else { b += i; nel -= nel / 2; }
4970    }
4971}
4972
4973unsafe fn iconv_decode(enc: i32, src: *const u8, src_left: usize) -> (u32, usize, c_int) {
4974    if src_left == 0 { return (0, 0, EINVAL); }
4975    match enc {
4976        ENC_UTF8 => {
4977            let c = *src;
4978            if c < 128 { return (c as u32, 1, 0); }
4979            if c < 0xC2 { return (0, 0, EILSEQ); }
4980            if c < 0xE0 {
4981                if src_left < 2 || (*src.add(1) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
4982                return (((c as u32 & 0x1F) << 6) | (*src.add(1) as u32 & 0x3F), 2, 0);
4983            }
4984            if c < 0xF0 {
4985                if src_left < 3 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
4986                let cp = ((c as u32 & 0x0F) << 12) | ((*src.add(1) as u32 & 0x3F) << 6) | (*src.add(2) as u32 & 0x3F);
4987                if cp < 0x800 { return (0, 0, EILSEQ); }
4988                return (cp, 3, 0);
4989            }
4990            if c < 0xF8 {
4991                if src_left < 4 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 || (*src.add(3) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
4992                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);
4993                if cp < 0x10000 || cp >= 0x110000 { return (0, 0, EILSEQ); }
4994                return (cp, 4, 0);
4995            }
4996            (0, 0, EILSEQ)
4997        }
4998        ENC_UTF16LE => {
4999            if src_left < 2 { return (0, 0, EINVAL); }
5000            let c = (*src as u32) | ((*src.add(1) as u32) << 8);
5001            if c >= 0xD800 && c <= 0xDBFF {
5002                if src_left < 4 { return (0, 0, EINVAL); }
5003                let d = (*src.add(2) as u32) | ((*src.add(3) as u32) << 8);
5004                if d < 0xDC00 || d > 0xDFFF { return (0, 0, EILSEQ); }
5005                return (((c - 0xD800) << 10) + (d - 0xDC00) + 0x10000, 4, 0);
5006            }
5007            if c >= 0xDC00 && c <= 0xDFFF { return (0, 0, EILSEQ); }
5008            (c, 2, 0)
5009        }
5010        ENC_UTF16BE => {
5011            if src_left < 2 { return (0, 0, EINVAL); }
5012            let c = ((*src as u32) << 8) | (*src.add(1) as u32);
5013            if c >= 0xD800 && c <= 0xDBFF {
5014                if src_left < 4 { return (0, 0, EINVAL); }
5015                let d = ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
5016                if d < 0xDC00 || d > 0xDFFF { return (0, 0, EILSEQ); }
5017                return (((c - 0xD800) << 10) + (d - 0xDC00) + 0x10000, 4, 0);
5018            }
5019            if c >= 0xDC00 && c <= 0xDFFF { return (0, 0, EILSEQ); }
5020            (c, 2, 0)
5021        }
5022        ENC_UTF32LE => {
5023            if src_left < 4 { return (0, 0, EINVAL); }
5024            let c = (*src as u32) | ((*src.add(1) as u32) << 8) | ((*src.add(2) as u32) << 16) | ((*src.add(3) as u32) << 24);
5025            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
5026            if c >= 0x110000 { return (0, 0, EILSEQ); }
5027            (c, 4, 0)
5028        }
5029        ENC_UTF32BE => {
5030            if src_left < 4 { return (0, 0, EINVAL); }
5031            let c = ((*src as u32) << 24) | ((*src.add(1) as u32) << 16) | ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
5032            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
5033            if c >= 0x110000 { return (0, 0, EILSEQ); }
5034            (c, 4, 0)
5035        }
5036        ENC_WCHAR_T => {
5037            if src_left < 4 { return (0, 0, EINVAL); }
5038            let c = *(src as *const u32);
5039            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
5040            if c >= 0x110000 { return (0, 0, EILSEQ); }
5041            (c, 4, 0)
5042        }
5043        ENC_ASCII => {
5044            let c = *src as u32;
5045            if c >= 128 { return (0, 0, EILSEQ); }
5046            (c, 1, 0)
5047        }
5048        ENC_LATIN1 => (*src as u32, 1, 0),
5049        ENC_ISO8859_2 => (iso8859_to_u(&ISO8859_2_TO_U, *src), 1, 0),
5050        ENC_ISO8859_3 => (iso8859_to_u(&ISO8859_3_TO_U, *src), 1, 0),
5051        ENC_ISO8859_4 => (iso8859_to_u(&ISO8859_4_TO_U, *src), 1, 0),
5052        ENC_ISO8859_5 => (iso8859_to_u(&ISO8859_5_TO_U, *src), 1, 0),
5053        ENC_ISO8859_6 => (iso8859_to_u(&ISO8859_6_TO_U, *src), 1, 0),
5054        ENC_ISO8859_7 => (iso8859_to_u(&ISO8859_7_TO_U, *src), 1, 0),
5055        ENC_ISO8859_8 => (iso8859_to_u(&ISO8859_8_TO_U, *src), 1, 0),
5056        ENC_ISO8859_9 => (iso8859_to_u(&ISO8859_9_TO_U, *src), 1, 0),
5057        ENC_ISO8859_10 => (iso8859_to_u(&ISO8859_10_TO_U, *src), 1, 0),
5058        ENC_ISO8859_11 => (iso8859_to_u(&ISO8859_11_TO_U, *src), 1, 0),
5059        ENC_ISO8859_13 => (iso8859_to_u(&ISO8859_13_TO_U, *src), 1, 0),
5060        ENC_ISO8859_14 => (iso8859_to_u(&ISO8859_14_TO_U, *src), 1, 0),
5061        ENC_ISO8859_15 => (iso8859_to_u(&ISO8859_15_TO_U, *src), 1, 0),
5062        ENC_ISO8859_16 => (iso8859_to_u(&ISO8859_16_TO_U, *src), 1, 0),
5063        ENC_WIN1252 => {
5064            let b = *src;
5065            if b < 128 { return (b as u32, 1, 0); }
5066            (WIN1252_TO_U[b as usize - 128], 1, 0)
5067        }
5068        ENC_WIN1251 => {
5069            let b = *src;
5070            if b < 128 { return (b as u32, 1, 0); }
5071            (WIN1251_TO_U[b as usize - 128], 1, 0)
5072        }
5073        ENC_KOI8R => {
5074            let b = *src;
5075            if b < 128 { return (b as u32, 1, 0); }
5076            (KOI8R_TO_U[b as usize - 128], 1, 0)
5077        }
5078        ENC_GBK | ENC_GB2312 => {
5079            let c = *src;
5080            if c < 128 { return (c as u32, 1, 0); }
5081            if c == 128 { return (0x20AC, 1, 0); }
5082            if src_left < 2 { return (0, 0, EINVAL); }
5083            let d = *src.add(1);
5084            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
5085            let row = (c as usize).wrapping_sub(0x81);
5086            if row >= 126 { return (0, 0, EILSEQ); }
5087            let mut col = (d as usize) - 0x40;
5088            if col > 63 { col -= 1; }
5089            let cp = GB18030_TABLE[row * 190 + col] as u32;
5090            if cp == 0 { return (0, 0, EILSEQ); }
5091            (cp, 2, 0)
5092        }
5093        ENC_BIG5 => {
5094            let c = *src;
5095            if c < 128 { return (c as u32, 1, 0); }
5096            if src_left < 2 { return (0, 0, EINVAL); }
5097            let d = *src.add(1);
5098            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
5099            let mut col = (d as usize) - 0x40;
5100            if col > 0x3E { col -= 0x22; }
5101            if c >= 0xA1 && c < 0xFA {
5102                let row = (c as usize) - 0xA1;
5103                if row >= 89 { return (0, 0, EILSEQ); }
5104                let cp = BIG5_TABLE[row * 157 + col] as u32;
5105                if cp == 0 { return (0, 0, EILSEQ); }
5106                return (cp, 2, 0);
5107            }
5108            (0, 0, EILSEQ)
5109        }
5110        ENC_EUCJP => {
5111            let c = *src;
5112            if c < 128 { return (c as u32, 1, 0); }
5113            if c == 0x8E {
5114                if src_left < 2 { return (0, 0, EINVAL); }
5115                let d = *src.add(1);
5116                if d < 0xA1 || d > 0xDF { return (0, 0, EILSEQ); }
5117                return ((d as u32) + 0xFF61 - 0xA1, 2, 0);
5118            }
5119            if c < 0xA1 { return (0, 0, EILSEQ); }
5120            if src_left < 2 { return (0, 0, EINVAL); }
5121            let d = *src.add(1);
5122            if d < 0xA1 || d > 0xFE { return (0, 0, EILSEQ); }
5123            let row = (c as usize) - 0xA1;
5124            let col = (d as usize) - 0xA1;
5125            if row >= 84 || col >= 94 { return (0, 0, EILSEQ); }
5126            let cp = JIS0208[row * 94 + col] as u32;
5127            if cp == 0 { return (0, 0, EILSEQ); }
5128            (cp, 2, 0)
5129        }
5130        ENC_SHIFTJIS => {
5131            let c = *src;
5132            if c < 128 { return (c as u32, 1, 0); }
5133            if c >= 0xA1 && c <= 0xDF { return ((c as u32) + 0xFF61 - 0xA1, 1, 0); }
5134            if src_left < 2 { return (0, 0, EINVAL); }
5135            let d = *src.add(1);
5136            if d < 0x40 || d == 0x7F || d > 0xFC { return (0, 0, EILSEQ); }
5137            let row = if c >= 129 && c <= 159 { (c as usize) - 129 }
5138                      else if c >= 224 && c <= 239 { (c as usize) - 193 }
5139                      else { return (0, 0, EILSEQ); };
5140            let (col, row_adj) = if d >= 64 && d <= 158 && d != 127 {
5141                let mut dd = d as usize;
5142                if dd > 127 { dd -= 1; }
5143                (dd - 64, row * 2)
5144            } else if d >= 159 && d <= 252 {
5145                ((d as usize) - 159, row * 2 + 1)
5146            } else {
5147                return (0, 0, EILSEQ);
5148            };
5149            if row_adj >= 84 { return (0, 0, EILSEQ); }
5150            let cp = JIS0208[row_adj * 94 + col] as u32;
5151            if cp == 0 { return (0, 0, EILSEQ); }
5152            (cp, 2, 0)
5153        }
5154        _ => (0, 0, EILSEQ),
5155    }
5156}
5157
5158unsafe fn iconv_encode(enc: i32, c: u32, dst: *mut u8, dst_left: usize) -> (usize, c_int) {
5159    match enc {
5160        ENC_UTF8 => {
5161            if c < 0x80 {
5162                if dst_left < 1 { return (0, E2BIG); }
5163                *dst = c as u8; return (1, 0);
5164            }
5165            if c < 0x800 {
5166                if dst_left < 2 { return (0, E2BIG); }
5167                *dst = (0xC0 | (c >> 6)) as u8;
5168                *dst.add(1) = (0x80 | (c & 0x3F)) as u8;
5169                return (2, 0);
5170            }
5171            if c < 0x10000 {
5172                if dst_left < 3 { return (0, E2BIG); }
5173                *dst = (0xE0 | (c >> 12)) as u8;
5174                *dst.add(1) = (0x80 | ((c >> 6) & 0x3F)) as u8;
5175                *dst.add(2) = (0x80 | (c & 0x3F)) as u8;
5176                return (3, 0);
5177            }
5178            if dst_left < 4 { return (0, E2BIG); }
5179            *dst = (0xF0 | (c >> 18)) as u8;
5180            *dst.add(1) = (0x80 | ((c >> 12) & 0x3F)) as u8;
5181            *dst.add(2) = (0x80 | ((c >> 6) & 0x3F)) as u8;
5182            *dst.add(3) = (0x80 | (c & 0x3F)) as u8;
5183            (4, 0)
5184        }
5185        ENC_UTF16LE => {
5186            if c < 0x10000 {
5187                if dst_left < 2 { return (0, E2BIG); }
5188                *dst = (c & 0xFF) as u8;
5189                *dst.add(1) = (c >> 8) as u8;
5190                return (2, 0);
5191            }
5192            if dst_left < 4 { return (0, E2BIG); }
5193            let c = c - 0x10000;
5194            let hi = ((c >> 10) + 0xD800) as u16;
5195            let lo = ((c & 0x3FF) + 0xDC00) as u16;
5196            *dst = (hi & 0xFF) as u8; *dst.add(1) = (hi >> 8) as u8;
5197            *dst.add(2) = (lo & 0xFF) as u8; *dst.add(3) = (lo >> 8) as u8;
5198            (4, 0)
5199        }
5200        ENC_UTF16BE => {
5201            if c < 0x10000 {
5202                if dst_left < 2 { return (0, E2BIG); }
5203                *dst = (c >> 8) as u8;
5204                *dst.add(1) = (c & 0xFF) as u8;
5205                return (2, 0);
5206            }
5207            if dst_left < 4 { return (0, E2BIG); }
5208            let c = c - 0x10000;
5209            let hi = ((c >> 10) + 0xD800) as u16;
5210            let lo = ((c & 0x3FF) + 0xDC00) as u16;
5211            *dst = (hi >> 8) as u8; *dst.add(1) = (hi & 0xFF) as u8;
5212            *dst.add(2) = (lo >> 8) as u8; *dst.add(3) = (lo & 0xFF) as u8;
5213            (4, 0)
5214        }
5215        ENC_UTF32LE => {
5216            if dst_left < 4 { return (0, E2BIG); }
5217            *dst = (c & 0xFF) as u8; *dst.add(1) = ((c >> 8) & 0xFF) as u8;
5218            *dst.add(2) = ((c >> 16) & 0xFF) as u8; *dst.add(3) = (c >> 24) as u8;
5219            (4, 0)
5220        }
5221        ENC_UTF32BE => {
5222            if dst_left < 4 { return (0, E2BIG); }
5223            *dst = (c >> 24) as u8; *dst.add(1) = ((c >> 16) & 0xFF) as u8;
5224            *dst.add(2) = ((c >> 8) & 0xFF) as u8; *dst.add(3) = (c & 0xFF) as u8;
5225            (4, 0)
5226        }
5227        ENC_WCHAR_T => {
5228            if dst_left < 4 { return (0, E2BIG); }
5229            *(dst as *mut u32) = c;
5230            (4, 0)
5231        }
5232        ENC_ASCII => {
5233            if c < 128 {
5234                if dst_left < 1 { return (0, E2BIG); }
5235                *dst = c as u8; return (1, 0);
5236            }
5237            (0, EILSEQ)
5238        }
5239        ENC_LATIN1 => {
5240            if c < 256 {
5241                if dst_left < 1 { return (0, E2BIG); }
5242                *dst = c as u8; return (1, 0);
5243            }
5244            (0, EILSEQ)
5245        }
5246        ENC_ISO8859_2 => {
5247            if let Some(b) = u_to_iso8859(&ISO8859_2_TO_U, c) {
5248                if dst_left < 1 { return (0, E2BIG); }
5249                *dst = b; return (1, 0);
5250            }
5251            (0, EILSEQ)
5252        }
5253        ENC_ISO8859_3 => {
5254            if let Some(b) = u_to_iso8859(&ISO8859_3_TO_U, c) {
5255                if dst_left < 1 { return (0, E2BIG); }
5256                *dst = b; return (1, 0);
5257            }
5258            (0, EILSEQ)
5259        }
5260        ENC_ISO8859_4 => {
5261            if let Some(b) = u_to_iso8859(&ISO8859_4_TO_U, c) {
5262                if dst_left < 1 { return (0, E2BIG); }
5263                *dst = b; return (1, 0);
5264            }
5265            (0, EILSEQ)
5266        }
5267        ENC_ISO8859_5 => {
5268            if let Some(b) = u_to_iso8859(&ISO8859_5_TO_U, c) {
5269                if dst_left < 1 { return (0, E2BIG); }
5270                *dst = b; return (1, 0);
5271            }
5272            (0, EILSEQ)
5273        }
5274        ENC_ISO8859_6 => {
5275            if let Some(b) = u_to_iso8859(&ISO8859_6_TO_U, c) {
5276                if dst_left < 1 { return (0, E2BIG); }
5277                *dst = b; return (1, 0);
5278            }
5279            (0, EILSEQ)
5280        }
5281        ENC_ISO8859_7 => {
5282            if let Some(b) = u_to_iso8859(&ISO8859_7_TO_U, c) {
5283                if dst_left < 1 { return (0, E2BIG); }
5284                *dst = b; return (1, 0);
5285            }
5286            (0, EILSEQ)
5287        }
5288        ENC_ISO8859_8 => {
5289            if let Some(b) = u_to_iso8859(&ISO8859_8_TO_U, c) {
5290                if dst_left < 1 { return (0, E2BIG); }
5291                *dst = b; return (1, 0);
5292            }
5293            (0, EILSEQ)
5294        }
5295        ENC_ISO8859_9 => {
5296            if let Some(b) = u_to_iso8859(&ISO8859_9_TO_U, c) {
5297                if dst_left < 1 { return (0, E2BIG); }
5298                *dst = b; return (1, 0);
5299            }
5300            (0, EILSEQ)
5301        }
5302        ENC_ISO8859_10 => {
5303            if let Some(b) = u_to_iso8859(&ISO8859_10_TO_U, c) {
5304                if dst_left < 1 { return (0, E2BIG); }
5305                *dst = b; return (1, 0);
5306            }
5307            (0, EILSEQ)
5308        }
5309        ENC_ISO8859_11 => {
5310            if let Some(b) = u_to_iso8859(&ISO8859_11_TO_U, c) {
5311                if dst_left < 1 { return (0, E2BIG); }
5312                *dst = b; return (1, 0);
5313            }
5314            (0, EILSEQ)
5315        }
5316        ENC_ISO8859_13 => {
5317            if let Some(b) = u_to_iso8859(&ISO8859_13_TO_U, c) {
5318                if dst_left < 1 { return (0, E2BIG); }
5319                *dst = b; return (1, 0);
5320            }
5321            (0, EILSEQ)
5322        }
5323        ENC_ISO8859_14 => {
5324            if let Some(b) = u_to_iso8859(&ISO8859_14_TO_U, c) {
5325                if dst_left < 1 { return (0, E2BIG); }
5326                *dst = b; return (1, 0);
5327            }
5328            (0, EILSEQ)
5329        }
5330        ENC_ISO8859_15 => {
5331            if let Some(b) = u_to_iso8859(&ISO8859_15_TO_U, c) {
5332                if dst_left < 1 { return (0, E2BIG); }
5333                *dst = b; return (1, 0);
5334            }
5335            (0, EILSEQ)
5336        }
5337        ENC_ISO8859_16 => {
5338            if let Some(b) = u_to_iso8859(&ISO8859_16_TO_U, c) {
5339                if dst_left < 1 { return (0, E2BIG); }
5340                *dst = b; return (1, 0);
5341            }
5342            (0, EILSEQ)
5343        }
5344        ENC_WIN1252 => {
5345            if c < 128 {
5346                if dst_left < 1 { return (0, E2BIG); }
5347                *dst = c as u8; return (1, 0);
5348            }
5349            if c >= 0xA0 && c <= 0xFF && WIN1252_TO_U[c as usize - 128] == c {
5350                if dst_left < 1 { return (0, E2BIG); }
5351                *dst = c as u8; return (1, 0);
5352            }
5353            for i in 0..128usize {
5354                if WIN1252_TO_U[i] == c {
5355                    if dst_left < 1 { return (0, E2BIG); }
5356                    *dst = (i + 128) as u8; return (1, 0);
5357                }
5358            }
5359            (0, EILSEQ)
5360        }
5361        ENC_WIN1251 => {
5362            if c < 128 {
5363                if dst_left < 1 { return (0, E2BIG); }
5364                *dst = c as u8; return (1, 0);
5365            }
5366            for i in 0..128usize {
5367                if WIN1251_TO_U[i] == c {
5368                    if dst_left < 1 { return (0, E2BIG); }
5369                    *dst = (i + 128) as u8; return (1, 0);
5370                }
5371            }
5372            (0, EILSEQ)
5373        }
5374        ENC_KOI8R => {
5375            if c < 128 {
5376                if dst_left < 1 { return (0, E2BIG); }
5377                *dst = c as u8; return (1, 0);
5378            }
5379            for i in 0..128usize {
5380                if KOI8R_TO_U[i] == c {
5381                    if dst_left < 1 { return (0, E2BIG); }
5382                    *dst = (i + 128) as u8; return (1, 0);
5383                }
5384            }
5385            (0, EILSEQ)
5386        }
5387        ENC_GBK | ENC_GB2312 => {
5388            if c < 128 {
5389                if dst_left < 1 { return (0, E2BIG); }
5390                *dst = c as u8; return (1, 0);
5391            }
5392            if c == 0x20AC {
5393                if dst_left < 1 { return (0, E2BIG); }
5394                *dst = 128; return (1, 0);
5395            }
5396            for row in 0..126usize {
5397                for col in 0..190usize {
5398                    if GB18030_TABLE[row * 190 + col] as u32 == c {
5399                        if dst_left < 2 { return (0, E2BIG); }
5400                        *dst = (row + 0x81) as u8;
5401                        *dst.add(1) = if col <= 62 { (col + 0x40) as u8 } else { (col + 0x41) as u8 };
5402                        return (2, 0);
5403                    }
5404                }
5405            }
5406            (0, EILSEQ)
5407        }
5408        ENC_BIG5 => {
5409            if c < 128 {
5410                if dst_left < 1 { return (0, E2BIG); }
5411                *dst = c as u8; return (1, 0);
5412            }
5413            for row in 0..89usize {
5414                for col in 0..157usize {
5415                    if BIG5_TABLE[row * 157 + col] as u32 == c {
5416                        if dst_left < 2 { return (0, E2BIG); }
5417                        *dst = (row + 0xA1) as u8;
5418                        *dst.add(1) = if col <= 0x3E { (col + 0x40) as u8 } else { (col + 0x62) as u8 };
5419                        return (2, 0);
5420                    }
5421                }
5422            }
5423            (0, EILSEQ)
5424        }
5425        ENC_EUCJP => {
5426            if c < 128 {
5427                if dst_left < 1 { return (0, E2BIG); }
5428                *dst = c as u8; return (1, 0);
5429            }
5430            if c >= 0xFF61 && c <= 0xFF9F {
5431                if dst_left < 2 { return (0, E2BIG); }
5432                *dst = 0x8E;
5433                *dst.add(1) = (c - 0xFF61 + 0xA1) as u8;
5434                return (2, 0);
5435            }
5436            let jis = uni_to_jis(c);
5437            if jis == 0 { return (0, EILSEQ); }
5438            if dst_left < 2 { return (0, E2BIG); }
5439            *dst = ((jis >> 8) as u8).wrapping_add(0x80);
5440            *dst.add(1) = ((jis & 0xFF) as u8).wrapping_add(0x80);
5441            (2, 0)
5442        }
5443        ENC_SHIFTJIS => {
5444            if c < 128 {
5445                if dst_left < 1 { return (0, E2BIG); }
5446                *dst = c as u8; return (1, 0);
5447            }
5448            if c >= 0xFF61 && c <= 0xFF9F {
5449                if dst_left < 1 { return (0, E2BIG); }
5450                *dst = (c - 0xFF61 + 0xA1) as u8;
5451                return (1, 0);
5452            }
5453            let jis = uni_to_jis(c);
5454            if jis == 0 { return (0, EILSEQ); }
5455            if dst_left < 2 { return (0, E2BIG); }
5456            let r = (jis >> 8) as usize;
5457            let d = (jis & 0xFF) as usize;
5458            *dst = ((r + 1) / 2 + if r < 95 { 112 } else { 176 }) as u8;
5459            *dst.add(1) = if r % 2 == 1 { (d + 31 + d / 96) as u8 } else { (d + 126) as u8 };
5460            (2, 0)
5461        }
5462        _ => (0, EILSEQ),
5463    }
5464}
5465
5466#[no_mangle]
5467pub unsafe extern "C" fn iconv_open(tocode: *const c_char, fromcode: *const c_char) -> IconvT {
5468    let to = find_encoding(tocode as *const u8);
5469    let from = find_encoding(fromcode as *const u8);
5470    if to < 0 || from < 0 {
5471        ERRNO!() = EINVAL;
5472        return !0usize as IconvT;
5473    }
5474    make_cd(from, to)
5475}
5476
5477#[no_mangle]
5478pub unsafe extern "C" fn iconv(
5479    cd: IconvT,
5480    inbuf: *mut *mut c_char,
5481    inbytesleft: *mut SizeT,
5482    outbuf: *mut *mut c_char,
5483    outbytesleft: *mut SizeT,
5484) -> SizeT {
5485    if cd == !0usize as IconvT {
5486        ERRNO!() = EINVAL;
5487        return !0usize;
5488    }
5489    if inbuf.is_null() || outbuf.is_null() { return 0; }
5490    let from = extract_from(cd);
5491    let to = extract_to(cd);
5492    let mut src = *inbuf as *const u8;
5493    let mut dst = *outbuf as *mut u8;
5494    let mut src_left = *inbytesleft;
5495    let mut dst_left = *outbytesleft;
5496    let mut subst = 0usize;
5497    while src_left > 0 {
5498        let (cp, consumed, err) = iconv_decode(from, src, src_left);
5499        if err != 0 {
5500            if err == EINVAL { break; }
5501            ERRNO!() = err;
5502            return !0usize;
5503        }
5504        let (written, err) = iconv_encode(to, cp, dst, dst_left);
5505        if err != 0 {
5506            if err == E2BIG {
5507                ERRNO!() = E2BIG;
5508                return !0usize;
5509            }
5510            if dst_left < 1 {
5511                ERRNO!() = E2BIG;
5512                return !0usize;
5513            }
5514            *dst = b'*';
5515            dst = dst.add(1);
5516            dst_left -= 1;
5517            subst += 1;
5518        } else {
5519            dst = dst.add(written);
5520            dst_left -= written;
5521        }
5522        src = src.add(consumed);
5523        src_left -= consumed;
5524    }
5525    *inbuf = src as *mut c_char;
5526    *outbuf = dst as *mut c_char;
5527    *inbytesleft = src_left;
5528    *outbytesleft = dst_left;
5529    subst
5530}
5531
5532#[no_mangle]
5533pub unsafe extern "C" fn iconv_close(_cd: IconvT) -> c_int { 0 }
5534
5535// ============================================================
5536// Syscall wrappers as public C ABI
5537// ============================================================
5538
5539#[no_mangle]
5540pub unsafe extern "C" fn write(fd: c_int, buf: *const c_void, count: SizeT) -> SSizeT {
5541    syscall_ret(sys_write(fd as i64, buf as *const u8, count)) as SSizeT
5542}
5543
5544#[no_mangle]
5545pub unsafe extern "C" fn read(fd: c_int, buf: *mut c_void, count: SizeT) -> SSizeT {
5546    syscall_ret(sys_read(fd as i64, buf as *mut u8, count)) as SSizeT
5547}
5548
5549#[no_mangle]
5550pub unsafe extern "C" fn open(path: *const c_char, flags: c_int, mode: c_int) -> c_int {
5551    syscall_ret(sys_open(path as *const u8, flags as i64, mode as i64)) as c_int
5552}
5553
5554#[no_mangle]
5555pub unsafe extern "C" fn close(fd: c_int) -> c_int {
5556    syscall_ret(sys_close(fd as i64)) as c_int
5557}
5558
5559#[no_mangle]
5560pub unsafe extern "C" fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64 {
5561    syscall_ret(sys_lseek(fd as i64, offset, whence as i64))
5562}
5563
5564// ============================================================
5565// Additional syscall wrappers for stdio
5566// ============================================================
5567
5568const O_RDONLY: i32 = 0;
5569const O_WRONLY: i32 = 1;
5570const O_RDWR: i32 = 2;
5571const O_CREAT: i32 = 64;
5572const O_TRUNC: i32 = 512;
5573const O_APPEND: i32 = 1024;
5574const O_EXCL: i32 = 128;
5575const O_NONBLOCK: i32 = 2048;
5576const O_NOFOLLOW: i32 = if cfg!(target_arch = "aarch64") { 0o100000 } else { 0o400000 };
5577const O_DIRECTORY: i32 = if cfg!(target_arch = "aarch64") { 0o40000 } else { 0o200000 };
5578const O_CLOEXEC: i32 = 0x80000;
5579
5580const F_GETFD: i32 = 1;
5581const F_SETFD: i32 = 2;
5582const F_GETFL: i32 = 3;
5583const F_SETFL: i32 = 4;
5584const F_GETLK: i32 = 5;
5585const F_SETLK: i32 = 6;
5586const F_SETLKW: i32 = 7;
5587const F_DUPFD: i32 = 0;
5588const F_DUPFD_CLOEXEC: i32 = 1030;
5589const FD_CLOEXEC: i32 = 1;
5590
5591const TIOCGWINSZ: u32 = 0x5413;
5592
5593#[repr(C)]
5594struct winsize {
5595    ws_row: u16,
5596    ws_col: u16,
5597    ws_xpixel: u16,
5598    ws_ypixel: u16,
5599}
5600
5601#[inline]
5602unsafe fn sys_pipe2(fds: *mut c_int, flags: i32) -> i64 {
5603    <Arch as Syscalls>::syscall2(SYS_PIPE2, fds as i64, flags as i64)
5604}
5605
5606#[inline]
5607unsafe fn sys_dup3(oldfd: i32, newfd: i32, flags: i32) -> i64 {
5608    <Arch as Syscalls>::syscall3(SYS_DUP3, oldfd as i64, newfd as i64, flags as i64)
5609}
5610
5611#[inline]
5612unsafe fn sys_fcntl(fd: i32, cmd: i32, arg: i64) -> i64 {
5613    <Arch as Syscalls>::syscall3(SYS_FCNTL, fd as i64, cmd as i64, arg as i64)
5614}
5615
5616#[inline]
5617unsafe fn sys_ioctl(fd: c_int, request: u32, arg: *mut u8) -> i64 {
5618    <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg as i64)
5619}
5620
5621#[inline]
5622unsafe fn sys_unlinkat(dirfd: i32, path: *const u8, flags: i32) -> i64 {
5623    <Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, path as i64, flags as i64)
5624}
5625
5626#[inline]
5627unsafe fn sys_renameat2(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: u32) -> i64 {
5628    <Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
5629}
5630
5631// ============================================================
5632// FILE / stdio (buffered, musl-compatible layout)
5633// ============================================================
5634
5635const UNGET: usize = 8;
5636const F_PERM: u32 = 1;
5637const F_NORD: u32 = 4;
5638const F_NOWR: u32 = 8;
5639const F_EOF: u32 = 16;
5640const F_ERR: u32 = 32;
5641const F_SVB: u32 = 64;
5642const F_APP: u32 = 128;
5643
5644const BUFSIZ: usize = 1024;
5645
5646const _IOFBF: c_int = 0;
5647const _IOLBF: c_int = 1;
5648const _IONBF: c_int = 2;
5649
5650const SEEK_SET: c_int = 0;
5651const SEEK_CUR: c_int = 1;
5652const SEEK_END: c_int = 2;
5653
5654// ponytail: buffered FILE, musl x86_64 layout subset
5655#[repr(C)]
5656pub struct FILE {
5657    flags: c_uint,
5658    rpos: *mut u8,
5659    rend: *mut u8,
5660    close: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
5661    wend: *mut u8,
5662    wpos: *mut u8,
5663    mustbezero_1: *mut u8,
5664    wbase: *mut u8,
5665    read_fn: Option<unsafe extern "C" fn(*mut FILE, *mut u8, usize) -> usize>,
5666    write_fn: Option<unsafe extern "C" fn(*mut FILE, *const u8, usize) -> usize>,
5667    seek_fn: Option<unsafe extern "C" fn(*mut FILE, i64, c_int) -> i64>,
5668    buf: *mut u8,
5669    buf_size: usize,
5670    prev: *mut FILE,
5671    next: *mut FILE,
5672    fd: c_int,
5673    pipe_pid: c_int,
5674    lockcount: c_long,
5675    mode: c_int,
5676    lock: c_int,
5677    lbf: c_int,
5678    cookie: *mut c_void,
5679    off: i64,
5680    getln_buf: *mut c_char,
5681    mustbezero_2: *mut c_void,
5682    shend: *mut u8,
5683    shlim: i64,
5684    shcnt: i64,
5685    ungotten: [c_int; UNGET],
5686    ungotten_count: c_int,
5687    _eof: c_int,
5688    _err: c_int,
5689}
5690
5691static mut STDIN_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5692static mut STDOUT_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5693static mut STDERR_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5694
5695static mut STDIN_FILE: FILE = FILE {
5696    flags: 0, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5697    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5698    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5699    read_fn: None, write_fn: None, seek_fn: None,
5700    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5701    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5702    fd: 0, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5703    cookie: core::ptr::null_mut(), off: 0,
5704    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5705    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5706    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5707};
5708static mut STDOUT_FILE: FILE = FILE {
5709    flags: F_NOWR as u32 + F_SVB as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5710    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5711    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5712    read_fn: None, write_fn: None, seek_fn: None,
5713    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5714    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5715    fd: 1, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5716    cookie: core::ptr::null_mut(), off: 0,
5717    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5718    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5719    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5720};
5721static mut STDERR_FILE: FILE = FILE {
5722    flags: F_NOWR as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5723    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5724    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5725    read_fn: None, write_fn: None, seek_fn: None,
5726    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5727    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5728    fd: 2, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5729    cookie: core::ptr::null_mut(), off: 0,
5730    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5731    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5732    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5733};
5734
5735#[no_mangle]
5736pub static mut stdin: *mut FILE = &raw mut STDIN_FILE as *mut FILE;
5737#[no_mangle]
5738pub static mut stdout: *mut FILE = &raw mut STDOUT_FILE as *mut FILE;
5739#[no_mangle]
5740pub static mut stderr: *mut FILE = &raw mut STDERR_FILE as *mut FILE;
5741
5742// ============================================================
5743// FILE helpers
5744// ============================================================
5745
5746unsafe fn __stdio_init() {
5747    STDIN_FILE.buf = core::ptr::addr_of_mut!(STDIN_BUF) as *mut u8;
5748    STDIN_FILE.buf_size = BUFSIZ;
5749    STDIN_FILE.read_fn = Some(__stdio_read);
5750    STDIN_FILE.write_fn = Some(__stdio_write);
5751    STDIN_FILE.seek_fn = Some(__stdio_seek);
5752    STDOUT_FILE.buf = core::ptr::addr_of_mut!(STDOUT_BUF) as *mut u8;
5753    STDOUT_FILE.buf_size = BUFSIZ;
5754    STDOUT_FILE.lbf = b'\n' as c_int;
5755    STDOUT_FILE.read_fn = Some(__stdio_read);
5756    STDOUT_FILE.write_fn = Some(__stdio_write);
5757    STDOUT_FILE.seek_fn = Some(__stdio_seek);
5758    STDERR_FILE.buf = core::ptr::addr_of_mut!(STDERR_BUF) as *mut u8;
5759    STDERR_FILE.buf_size = BUFSIZ;
5760    STDERR_FILE.read_fn = Some(__stdio_read);
5761    STDERR_FILE.write_fn = Some(__stdio_write);
5762    STDERR_FILE.seek_fn = Some(__stdio_seek);
5763}
5764
5765unsafe fn buf_ptr(f: *mut FILE) -> *mut u8 {
5766    (f as *mut u8).add(core::mem::size_of::<FILE>())
5767}
5768
5769unsafe extern "C" fn __stdio_read(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
5770    let n = sys_read((*f).fd as i64, buf, len);
5771    if n <= 0 {
5772        if n == 0 { (*f).flags |= F_EOF; } else { (*f).flags |= F_ERR; (*f)._err = 1; }
5773        return 0;
5774    }
5775    n as usize
5776}
5777
5778unsafe extern "C" fn __stdio_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
5779    let l = (*f).wpos as usize - (*f).wbase as usize;
5780    let mut iov = [
5781        ((*f).wbase as *const u8, l),
5782        (buf, len),
5783    ];
5784    if iov[0].1 == 0 { iov = [iov[1], (core::ptr::null(), 0)]; }
5785    if (*f).flags & F_APP != 0 {
5786        let _ = sys_lseek((*f).fd as i64, 0, SEEK_END as i64);
5787    }
5788    let mut rem = iov[0].1 + iov[1].1;
5789    let mut idx = 0usize;
5790    while rem > 0 {
5791        let ptr = iov[idx].0;
5792        let cnt = iov[idx].1;
5793        if cnt == 0 { idx += 1; continue; }
5794        let n = sys_write((*f).fd as i64, ptr, cnt);
5795        if n <= 0 {
5796            (*f).wpos = core::ptr::null_mut();
5797            (*f).wbase = core::ptr::null_mut();
5798            (*f).wend = core::ptr::null_mut();
5799            (*f).flags |= F_ERR;
5800            return if iov[idx].0 == buf { 0 } else { len };
5801        }
5802        rem -= n as usize;
5803        iov[idx].0 = iov[idx].0.add(n as usize);
5804        iov[idx].1 -= n as usize;
5805        if iov[idx].1 == 0 { idx += 1; }
5806    }
5807    (*f).wend = (*f).buf.add((*f).buf_size);
5808    (*f).wbase = (*f).buf;
5809    (*f).wpos = (*f).buf;
5810    len
5811}
5812
5813unsafe extern "C" fn __stdio_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
5814    sys_lseek((*f).fd as i64, off, whence as i64)
5815}
5816
5817unsafe fn init_file(
5818    f: *mut FILE,
5819    fd: c_int,
5820    mode: *const c_char,
5821    close_fn: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
5822    buf_area: *mut u8,
5823    buf_sz: usize,
5824) {
5825    core::ptr::write_bytes(f as *mut u8, 0, core::mem::size_of::<FILE>());
5826    (*f).fd = fd;
5827    (*f).close = close_fn;
5828    (*f).lock = 0;
5829    (*f).lbf = -1;
5830    (*f).buf = buf_area;
5831    (*f).buf_size = buf_sz;
5832    (*f).read_fn = Some(__stdio_read);
5833    (*f).write_fn = Some(__stdio_write);
5834    (*f).seek_fn = Some(__stdio_seek);
5835    let m = *mode;
5836    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
5837    if m == b'r' as c_char && !has_plus {
5838        (*f).flags = F_NORD;
5839    } else if !has_plus {
5840        (*f).flags = F_NOWR;
5841    }
5842}
5843
5844unsafe extern "C" fn __stdio_close(f: *mut FILE) -> c_int {
5845    sys_close((*f).fd as i64);
5846    0
5847}
5848
5849unsafe fn fmodeflags(mode: *const c_char) -> c_int {
5850    let mut flags: c_int;
5851    let m = *mode;
5852    if !strchr(mode as *const u8, b'+' as c_int).is_null() {
5853        flags = O_RDWR;
5854    } else if m == b'r' as c_char {
5855        flags = O_RDONLY;
5856    } else {
5857        flags = O_WRONLY;
5858    }
5859    if !strchr(mode as *const u8, b'x' as c_int).is_null() { flags |= O_EXCL; }
5860    if !strchr(mode as *const u8, b'e' as c_int).is_null() { flags |= O_CLOEXEC; }
5861    if m != b'r' as c_char { flags |= O_CREAT; }
5862    if m == b'w' as c_char { flags |= O_TRUNC; }
5863    if m == b'a' as c_char { flags |= O_APPEND; }
5864    flags
5865}
5866
5867const O_ACCMODE: c_int = O_RDONLY | O_WRONLY | O_RDWR;
5868
5869unsafe fn flush_buf(f: *mut FILE) -> c_int {
5870    if (*f).wpos == (*f).wbase {
5871        if !(*f).wpos.is_null() {
5872            (*f).wend = (*f).buf.add((*f).buf_size);
5873            (*f).wpos = (*f).wbase;
5874        }
5875        return 0;
5876    }
5877    if let Some(wfunc) = (*f).write_fn {
5878        let ret = wfunc(f, core::ptr::null(), 0);
5879        if ret == 0 && (*f).wpos.is_null() { return -1; }
5880        return 0;
5881    }
5882    (*f).flags |= F_ERR;
5883    -1
5884}
5885
5886// ============================================================
5887// fopen / fdopen / freopen / fclose
5888// ============================================================
5889
5890#[no_mangle]
5891pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE {
5892    if filename.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
5893    let m = *mode;
5894    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
5895        ERRNO!() = EINVAL; return core::ptr::null_mut();
5896    }
5897    let flags = fmodeflags(mode);
5898    let fd = sys_open(filename as *const u8, flags as i64, 0o666);
5899    if fd < 0 { ERRNO!() = (-fd) as c_int; return core::ptr::null_mut(); }
5900    fdopen(fd as c_int, mode)
5901}
5902
5903#[no_mangle]
5904pub unsafe extern "C" fn fdopen(fd: c_int, mode: *const c_char) -> *mut FILE {
5905    if fd < 0 || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
5906    let m = *mode;
5907    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
5908        ERRNO!() = EINVAL; return core::ptr::null_mut();
5909    }
5910    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
5911    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
5912    let buf = buf_ptr(f);
5913    init_file(f, fd, mode, Some(__stdio_close), buf, BUFSIZ);
5914    if !strchr(mode as *const u8, b'a' as c_int).is_null() { (*f).flags |= F_APP; }
5915    if !strchr(mode as *const u8, b'e' as c_int).is_null() { sys_fcntl(fd, F_SETFD, FD_CLOEXEC as i64); }
5916    if (*f).flags & F_NOWR == 0 {
5917        let mut ws: winsize = core::mem::zeroed();
5918        if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 {
5919            (*f).lbf = b'\n' as c_int;
5920        }
5921    }
5922    f
5923}
5924
5925#[no_mangle]
5926pub unsafe extern "C" fn freopen(
5927    filename: *const c_char, mode: *const c_char, f: *mut FILE,
5928) -> *mut FILE {
5929    fflush(f);
5930    if (*f).pipe_pid > 0 { let _ = __stdio_close(f); }
5931    if filename.is_null() {
5932        let flags = fmodeflags(mode);
5933        if flags == 0 { return core::ptr::null_mut(); }
5934        let mut fl = flags & !(O_CREAT | O_EXCL | O_CLOEXEC);
5935        if (*f).flags & F_APP != 0 { fl = (fl & !O_ACCMODE) | O_WRONLY | O_APPEND; }
5936        if sys_fcntl((*f).fd, F_SETFL, fl as i64) < 0 { return core::ptr::null_mut(); }
5937        let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
5938        if has_plus {
5939            (*f).flags &= !(F_NORD | F_NOWR);
5940        } else if *mode == b'r' as c_char {
5941            (*f).flags = ((*f).flags & !F_NOWR) | F_NORD;
5942        } else {
5943            (*f).flags = ((*f).flags & !F_NORD) | F_NOWR;
5944        }
5945        return f;
5946    }
5947    let new_f = fopen(filename, mode);
5948    if new_f.is_null() { let _ = __stdio_close(f); return core::ptr::null_mut(); }
5949    if (*new_f).fd == (*f).fd {
5950        (*new_f).fd = -1;
5951    } else {
5952        sys_dup3((*new_f).fd, (*f).fd, 0);
5953        let _ = __stdio_close(new_f);
5954    }
5955    (*f).flags = (*new_f).flags;
5956    (*f).rpos = core::ptr::null_mut();
5957    (*f).rend = core::ptr::null_mut();
5958    (*f).wpos = core::ptr::null_mut();
5959    (*f).wbase = core::ptr::null_mut();
5960    (*f).wend = core::ptr::null_mut();
5961    (*f).lbf = (*new_f).lbf;
5962    (*f).pipe_pid = 0;
5963    free(new_f as *mut c_void);
5964    f
5965}
5966
5967#[no_mangle]
5968pub unsafe extern "C" fn fclose(f: *mut FILE) -> c_int {
5969    if f.is_null() { return -1; }
5970    let r = fflush(f);
5971    if let Some(close_fn) = (*f).close { let _ = close_fn(f); }
5972    if r != 0 { -1 } else { 0 }
5973}
5974
5975// ============================================================
5976// setvbuf / setbuf / setbuffer / fflush
5977// ============================================================
5978
5979#[no_mangle]
5980pub unsafe extern "C" fn setvbuf(f: *mut FILE, buf: *mut c_char, mode: c_int, size: usize) -> c_int {
5981    if mode != _IOFBF && mode != _IOLBF && mode != _IONBF { return -1; }
5982    fflush(f);
5983    (*f).rpos = core::ptr::null_mut();
5984    (*f).rend = core::ptr::null_mut();
5985    (*f).wpos = core::ptr::null_mut();
5986    (*f).wbase = core::ptr::null_mut();
5987    (*f).wend = core::ptr::null_mut();
5988    if mode == _IONBF {
5989        (*f).buf_size = 0;
5990    } else if !buf.is_null() && size > 0 {
5991        (*f).buf = buf as *mut u8;
5992        (*f).buf_size = size;
5993    }
5994    (*f).lbf = if mode == _IOLBF { b'\n' as c_int } else { -1 };
5995    0
5996}
5997
5998#[no_mangle]
5999pub unsafe extern "C" fn setbuf(f: *mut FILE, buf: *mut c_char) {
6000    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
6001    else { setvbuf(f, buf, _IOFBF, BUFSIZ); }
6002}
6003
6004#[no_mangle]
6005pub unsafe extern "C" fn setbuffer(f: *mut FILE, buf: *mut c_char, size: usize) {
6006    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
6007    else { setvbuf(f, buf, _IOFBF, size); }
6008}
6009
6010#[no_mangle]
6011pub unsafe extern "C" fn fflush(f: *mut FILE) -> c_int {
6012    if f.is_null() {
6013        let mut r = 0;
6014        if !stdout.is_null() && !(*stdout).wpos.is_null() && (*stdout).wpos != (*stdout).wbase {
6015            if flush_buf(stdout) != 0 { r = -1; }
6016        }
6017        if !stderr.is_null() && !(*stderr).wpos.is_null() && (*stderr).wpos != (*stderr).wbase {
6018            if flush_buf(stderr) != 0 { r = -1; }
6019        }
6020        return r;
6021    }
6022    if !(*f).wpos.is_null() && (*f).wpos != (*f).wbase {
6023        return flush_buf(f);
6024    }
6025    0
6026}
6027
6028// ============================================================
6029// fwide / feof / ferror / clearerr / fileno
6030// ============================================================
6031
6032#[no_mangle]
6033pub unsafe extern "C" fn fwide(_f: *mut FILE, mode: c_int) -> c_int { mode }
6034
6035#[no_mangle]
6036pub unsafe extern "C" fn feof(f: *mut FILE) -> c_int { if (*f)._eof != 0 { 1 } else { 0 } }
6037
6038#[no_mangle]
6039pub unsafe extern "C" fn ferror(f: *mut FILE) -> c_int { if (*f)._err != 0 { 1 } else { 0 } }
6040
6041#[no_mangle]
6042pub unsafe extern "C" fn clearerr(f: *mut FILE) { (*f)._eof = 0; (*f)._err = 0; }
6043
6044#[no_mangle]
6045pub unsafe extern "C" fn fileno(f: *mut FILE) -> c_int { (*f).fd }
6046
6047// ============================================================
6048// fseek / ftell / rewind / fseeko / ftello / fgetpos / fsetpos
6049// ============================================================
6050
6051#[no_mangle]
6052pub unsafe extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int {
6053    fseeko(stream, offset as i64, whence)
6054}
6055
6056#[no_mangle]
6057pub unsafe extern "C" fn ftell(stream: *mut FILE) -> c_long {
6058    ftello(stream) as c_long
6059}
6060
6061#[no_mangle]
6062pub unsafe extern "C" fn rewind(stream: *mut FILE) {
6063    fseek(stream, 0, SEEK_SET);
6064    (*stream)._eof = 0;
6065    (*stream)._err = 0;
6066}
6067
6068#[no_mangle]
6069pub unsafe extern "C" fn fseeko(stream: *mut FILE, offset: i64, whence: c_int) -> c_int {
6070    if whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END {
6071        ERRNO!() = EINVAL;
6072        return -1;
6073    }
6074    let f = &mut *stream;
6075    let mut adj_offset = offset;
6076    if whence == SEEK_CUR {
6077        if !f.rpos.is_null() {
6078            adj_offset -= f.rend as i64 - f.rpos as i64;
6079        }
6080        adj_offset -= f.ungotten_count as i64;
6081    }
6082    if !f.wpos.is_null() && f.wpos != f.wbase {
6083        if flush_buf(stream) != 0 { return -1; }
6084    }
6085    f.wpos = core::ptr::null_mut();
6086    f.wbase = core::ptr::null_mut();
6087    f.wend = core::ptr::null_mut();
6088    if let Some(sfunc) = f.seek_fn {
6089        let r = sfunc(stream, adj_offset, whence);
6090        if r < 0 { return -1; }
6091    } else {
6092        ERRNO!() = EINVAL;
6093        return -1;
6094    }
6095    f.rpos = core::ptr::null_mut();
6096    f.rend = core::ptr::null_mut();
6097    f._eof = 0;
6098    f.ungotten_count = 0;
6099    0
6100}
6101
6102#[no_mangle]
6103pub unsafe extern "C" fn ftello(stream: *mut FILE) -> i64 {
6104    let f = &mut *stream;
6105    if f.flags & F_APP != 0 && !f.wpos.is_null() && f.wpos != f.wbase {
6106        if fflush(stream) != 0 { return -1; }
6107    }
6108    let sfunc = match f.seek_fn { Some(s) => s, None => return -1 };
6109    let pos = sfunc(stream, 0,
6110        if (f.flags & F_APP) != 0 && !f.wpos.is_null() && f.wpos != f.wbase { SEEK_END } else { SEEK_CUR });
6111    if pos < 0 { return -1; }
6112    let mut pos = pos;
6113    if !f.rpos.is_null() {
6114        pos += f.rpos as i64 - f.rend as i64;
6115    } else if !f.wbase.is_null() {
6116        pos += f.wpos as i64 - f.wbase as i64;
6117    }
6118    pos - f.ungotten_count as i64
6119}
6120
6121#[no_mangle]
6122pub unsafe extern "C" fn fgetpos(stream: *mut FILE, pos: *mut i64) -> c_int {
6123    let off = ftello(stream);
6124    if off < 0 { return -1; }
6125    *pos = off;
6126    0
6127}
6128
6129#[no_mangle]
6130pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const i64) -> c_int {
6131    fseeko(stream, *pos, SEEK_SET)
6132}
6133
6134// ============================================================
6135// fgetc / getc / getchar / ungetc
6136// ============================================================
6137
6138#[no_mangle]
6139pub unsafe extern "C" fn fgetc(stream: *mut FILE) -> c_int {
6140    let f = &mut *stream;
6141    if f.ungotten_count > 0 {
6142        f.ungotten_count -= 1;
6143        return f.ungotten[f.ungotten_count as usize];
6144    }
6145    if !f.rpos.is_null() && f.rpos < f.rend {
6146        let c = *f.rpos;
6147        f.rpos = f.rpos.add(1);
6148        return c as c_int;
6149    }
6150    if f._eof != 0 { return -1; }
6151    if let Some(rfunc) = f.read_fn {
6152        // Fill the stdio buffer in one read. Reading one byte per syscall is
6153        // not only slow, it is wrong for procfs files that only return their
6154        // contents on the first read: a second one-byte read sees EOF.
6155        if !f.buf.is_null() && f.buf_size > 1 {
6156            let n = rfunc(stream, f.buf, f.buf_size);
6157            if n == 0 {
6158                if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
6159                return -1;
6160            }
6161            f.rpos = f.buf;
6162            f.rend = f.buf.add(n);
6163            let c = *f.rpos;
6164            f.rpos = f.rpos.add(1);
6165            return c as c_int;
6166        }
6167        let mut buf = [0u8; 1];
6168        let n = rfunc(stream, buf.as_mut_ptr(), 1);
6169        if n == 0 {
6170            if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
6171            return -1;
6172        }
6173        buf[0] as c_int
6174    } else {
6175        f._eof = 1;
6176        -1
6177    }
6178}
6179
6180#[no_mangle]
6181pub unsafe extern "C" fn getc(stream: *mut FILE) -> c_int { fgetc(stream) }
6182
6183#[no_mangle]
6184pub unsafe extern "C" fn getchar() -> c_int { fgetc(stdin) }
6185
6186#[no_mangle]
6187pub unsafe extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int {
6188    if c == -1 { return -1; }
6189    let f = &mut *stream;
6190    if f.ungotten_count >= UNGET as c_int { return -1; }
6191    f.ungotten[f.ungotten_count as usize] = c;
6192    f.ungotten_count += 1;
6193    f._eof = 0;
6194    c
6195}
6196
6197// ============================================================
6198// fgets / fread
6199// ============================================================
6200
6201#[no_mangle]
6202pub unsafe extern "C" fn fgets(s: *mut c_char, n: c_int, stream: *mut FILE) -> *mut c_char {
6203    if n <= 0 { return null_mut(); }
6204    let max = (n - 1) as usize;
6205    let mut i = 0usize;
6206    while i < max {
6207        let c = fgetc(stream);
6208        if c == -1 { if i == 0 { return null_mut(); } break; }
6209        *s.add(i) = c as c_char;
6210        i += 1;
6211        if c == b'\n' as c_int { break; }
6212    }
6213    *s.add(i) = 0;
6214    s
6215}
6216
6217// ponytail: gets is dangerous, kept for POSIX compliance
6218#[no_mangle]
6219pub unsafe extern "C" fn gets(s: *mut c_char) -> *mut c_char {
6220    let mut i = 0usize;
6221    loop {
6222        let c = fgetc(stdin);
6223        if c == -1 { if i == 0 { return null_mut(); } break; }
6224        if c == b'\n' as c_int { break; }
6225        *s.add(i) = c as c_char;
6226        i += 1;
6227    }
6228    *s.add(i) = 0;
6229    s
6230}
6231
6232#[no_mangle]
6233pub unsafe extern "C" fn fopen64(filename: *const c_char, mode: *const c_char) -> *mut FILE {
6234    fopen(filename, mode)
6235}
6236
6237// ponytail: perror - minimal, just prints "msg: errno\n"
6238const PERROR_BUF_SIZE: usize = 64;
6239static mut PERROR_BUF: [u8; PERROR_BUF_SIZE] = [0; PERROR_BUF_SIZE];
6240
6241#[no_mangle]
6242pub unsafe extern "C" fn perror(msg: *const c_char) {
6243    let fd = (*stderr).fd;
6244    if !msg.is_null() && *msg != 0 {
6245        let len = strlen(msg as *const c_char);
6246        write_str(fd, msg as *const u8, len);
6247        write_str(fd, b": ".as_ptr(), 2);
6248    }
6249    let e = ERRNO!();
6250    let text = strerror(e) as *const u8;
6251    write_str(fd, text, strlen(text as *const c_char));
6252    write_str(fd, b"\n".as_ptr(), 1);
6253}
6254
6255#[no_mangle]
6256pub unsafe extern "C" fn fread(
6257    ptr: *mut c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
6258) -> SizeT {
6259    if size == 0 || nmemb == 0 { return 0; }
6260    let total = size * nmemb;
6261    let mut rd = 0usize;
6262    while rd < total {
6263        let c = fgetc(stream);
6264        if c == -1 { break; }
6265        *(ptr as *mut u8).add(rd) = c as u8;
6266        rd += 1;
6267    }
6268    rd / size
6269}
6270
6271// ============================================================
6272// puts / fputs / fputc / putc / putchar / fwrite
6273// ============================================================
6274
6275unsafe fn write_str(fd: c_int, s: *const u8, len: usize) {
6276    let mut written = 0usize;
6277    while written < len {
6278        let n = sys_write(fd as i64, s.add(written), len - written);
6279        if n <= 0 { break; }
6280        written += n as usize;
6281    }
6282}
6283
6284#[no_mangle]
6285unsafe fn __overflow(f: *mut FILE, c: c_int) -> c_int {
6286    if (*f).wpos.is_null() {
6287        (*f).wbase = (*f).buf;
6288        (*f).wpos = (*f).buf;
6289        (*f).wend = (*f).buf.add((*f).buf_size);
6290    }
6291    if flush_buf(f) == -1 { return -1; }
6292    if (*f).wpos >= (*f).wend {
6293        if let Some(wfunc) = (*f).write_fn {
6294            let byte = c as u8;
6295            let ret = wfunc(f, &byte as *const u8, 1);
6296            if ret == 0 { return -1; }
6297        }
6298        return c;
6299    }
6300    *(*f).wpos = c as u8;
6301    (*f).wpos = (*f).wpos.add(1);
6302    if c == (*f).lbf || (*f).wpos >= (*f).wend { let _ = flush_buf(f); }
6303    c
6304}
6305
6306#[no_mangle]
6307pub unsafe extern "C" fn puts(s: *const c_char) -> c_int {
6308    let len = strlen(s as *const c_char);
6309    let _ = fwrite(s as *const c_void, 1, len, stdout);
6310    let _ = fwrite(b"\n".as_ptr() as *const c_void, 1, 1, stdout);
6311    let f = &mut *stdout;
6312    if f.lbf >= 0 { let _ = flush_buf(stdout); }
6313    (len + 1) as c_int
6314}
6315
6316#[no_mangle]
6317pub unsafe extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int {
6318    let len = strlen(s as *const c_char);
6319    fwrite(s as *const c_void, 1, len, stream) as c_int
6320}
6321
6322#[no_mangle]
6323pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int {
6324    let f = &mut *stream;
6325    if f.wpos.is_null() || f.wpos >= f.wend {
6326        if __overflow(f, c) == -1 { return -1; }
6327        return c;
6328    }
6329    *f.wpos = c as u8;
6330    f.wpos = f.wpos.add(1);
6331    if c == f.lbf || f.wpos >= f.wend { let _ = flush_buf(f); }
6332    c
6333}
6334
6335#[no_mangle]
6336pub unsafe extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int { fputc(c, stream) }
6337
6338#[no_mangle]
6339pub unsafe extern "C" fn putchar(c: c_int) -> c_int { fputc(c, stdout) }
6340
6341#[no_mangle]
6342pub unsafe extern "C" fn fwrite(
6343    ptr: *const c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
6344) -> SizeT {
6345    if size == 0 || nmemb == 0 { return 0; }
6346    let total = size * nmemb;
6347    let f = &mut *stream;
6348    if f.buf_size == 0 {
6349        if let Some(wfunc) = f.write_fn {
6350            let ret = wfunc(stream, ptr as *const u8, total);
6351            return ret / size;
6352        }
6353        return 0;
6354    }
6355    if f.wpos.is_null() {
6356        f.wbase = f.buf;
6357        f.wpos = f.buf;
6358        f.wend = f.buf.add(f.buf_size);
6359    }
6360    let mut remaining = total;
6361    let mut src = ptr as *const u8;
6362    while remaining > 0 {
6363        let space = f.wend as usize - f.wpos as usize;
6364        if space == 0 {
6365            if flush_buf(f as *mut FILE) == -1 { break; }
6366            continue;
6367        }
6368        let n = if remaining < space { remaining } else { space };
6369        core::ptr::copy_nonoverlapping(src, f.wpos, n);
6370        f.wpos = f.wpos.add(n);
6371        src = src.add(n);
6372        remaining -= n;
6373        if f.wpos >= f.wend { let _ = flush_buf(f as *mut FILE); }
6374    }
6375    if f.lbf >= 0 { let _ = flush_buf(f as *mut FILE); }
6376    (total - remaining) / size
6377}
6378
6379// ============================================================
6380// printf / fprintf / vprintf / vfprintf / dprintf / vdprintf
6381// ============================================================
6382
6383unsafe fn wide_to_mb(dst: *mut u8, cap: usize, src: *const wchar_t) -> usize {
6384    let mut o = 0usize;
6385    let mut i = 0usize;
6386    let mut st: c_uint = 0;
6387    while *src.add(i) != 0 {
6388        let mut tmp = [0u8; 8];
6389        let n = wcrtomb(tmp.as_mut_ptr() as *mut c_char, *src.add(i), &mut st);
6390        if n == !0usize || n == 0 { break; }
6391        if o + n > cap { break; }
6392        core::ptr::copy_nonoverlapping(tmp.as_ptr(), dst.add(o), n);
6393        o += n;
6394        i += 1;
6395    }
6396    o
6397}
6398
6399macro_rules! impl_format {
6400    ($fmt:expr, $args:expr, $write_char:expr, $write_str:expr) => {{
6401        let fmt = $fmt;
6402        let args = &mut $args;
6403        let mut count: usize = 0;
6404        let mut i = 0usize;
6405        loop {
6406            let c = *fmt.add(i) as u8;
6407            if c == 0 { break; }
6408            if c != b'%' {
6409                ($write_char)(c);
6410                count += 1; i += 1; continue;
6411            }
6412            i += 1;
6413            // Parse flags
6414            let mut flags: u8 = 0;
6415            loop {
6416                let fc = *fmt.add(i) as u8;
6417                match fc {
6418                    b'-' => { flags |= FLAG_MINUS; i += 1; }
6419                    b'+' => { flags |= FLAG_PLUS; i += 1; }
6420                    b' ' => { flags |= FLAG_SPACE; i += 1; }
6421                    b'0' => { flags |= FLAG_ZERO; i += 1; }
6422                    b'#' => { flags |= FLAG_HASH; i += 1; }
6423                    _ => break,
6424                }
6425            }
6426            // Parse width
6427            let mut width: usize = 0;
6428            if *fmt.add(i) as u8 == b'*' {
6429                width = args.next_arg::<c_int>() as usize; i += 1;
6430            } else {
6431                while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
6432                    width = width * 10 + ((*fmt.add(i) as u8) - b'0') as usize; i += 1;
6433                }
6434            }
6435            // Parse precision
6436            let mut precision: i32 = -1;
6437            if *fmt.add(i) as u8 == b'.' {
6438                i += 1;
6439                if *fmt.add(i) as u8 == b'*' {
6440                    precision = args.next_arg::<c_int>(); i += 1;
6441                } else {
6442                    precision = 0;
6443                    while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
6444                        precision = precision * 10 + ((*fmt.add(i) as u8) - b'0') as i32; i += 1;
6445                    }
6446                }
6447            }
6448            // Parse length modifier
6449            let len_mod = *fmt.add(i) as u8;
6450            let spec: u8;
6451            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' {
6452                i += 1;
6453                let len_mod2 = *fmt.add(i) as u8;
6454                if (len_mod == b'h' && len_mod2 == b'h') || (len_mod == b'l' && len_mod2 == b'l') {
6455                    i += 1;
6456                    spec = *fmt.add(i) as u8;
6457                    // Handle double-length modifiers
6458                    match (len_mod, len_mod2, spec) {
6459                        (b'h', b'h', b'n') => {
6460                            let p = args.next_arg::<*mut c_void>();
6461                            if !p.is_null() { *(p as *mut u8) = count as u8; }
6462                        }
6463                        (b'l', b'l', b'n') => {
6464                            let p = args.next_arg::<*mut c_void>();
6465                            if !p.is_null() { *(p as *mut c_longlong) = count as c_longlong; }
6466                        }
6467                        (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
6468                            let val = args.next_arg::<c_longlong>();
6469                            let neg = val < 0;
6470                            let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
6471                            let b = format_u64(abs);
6472                            let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6473                            let mut fbuf = [0u8; 32];
6474                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6475                            ($write_str)(fbuf.as_ptr(), len); count += len;
6476                        }
6477                        (b'l', b'l', b'u') => {
6478                            let val = args.next_arg::<c_ulonglong>();
6479                            let b = format_u64(val as u64);
6480                            let mut fbuf = [0u8; 32];
6481                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6482                            ($write_str)(fbuf.as_ptr(), len); count += len;
6483                        }
6484                        (b'l', b'l', b'o') => {
6485                            let val = args.next_arg::<c_ulonglong>();
6486                            let b = format_octal(val as u64, flags & FLAG_HASH != 0);
6487                            let mut fbuf = [0u8; 32];
6488                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6489                            ($write_str)(fbuf.as_ptr(), len); count += len;
6490                        }
6491                        (b'l', b'l', b'x') => {
6492                            let val = args.next_arg::<c_ulonglong>();
6493                            let b = format_hex(val as u64, false);
6494                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6495                            let mut fbuf = [0u8; 32];
6496                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6497                            ($write_str)(fbuf.as_ptr(), len); count += len;
6498                        }
6499                        (b'l', b'l', b'X') => {
6500                            let val = args.next_arg::<c_ulonglong>();
6501                            let b = format_hex(val as u64, true);
6502                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6503                            let mut fbuf = [0u8; 32];
6504                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6505                            ($write_str)(fbuf.as_ptr(), len); count += len;
6506                        }
6507                        _ => { ($write_char)(b'%'); ($write_char)(len_mod); ($write_char)(len_mod2); ($write_char)(spec); count += 4; }
6508                    }
6509                } else {
6510                    spec = len_mod2;
6511                    // size_t/ptrdiff_t are 64-bit on all supported targets;
6512                    // treat %z/%t integer conversions like %l.
6513                    let lm = if (len_mod == b'z' || len_mod == b't') && spec != b'n' { b'l' } else { len_mod };
6514                    match (lm, spec) {
6515                        (b'h', b'n') => {
6516                            let p = args.next_arg::<*mut c_void>();
6517                            if !p.is_null() { *(p as *mut u16) = count as u16; }
6518                        }
6519                        (b'l', b'n') => {
6520                            let p = args.next_arg::<*mut c_void>();
6521                            if !p.is_null() { *(p as *mut c_long) = count as c_long; }
6522                        }
6523                        (b'z', b'n') | (b't', b'n') => {
6524                            let p = args.next_arg::<*mut c_void>();
6525                            if !p.is_null() { *(p as *mut usize) = count; }
6526                        }
6527                        (b'j', b'n') => {
6528                            let p = args.next_arg::<*mut c_void>();
6529                            if !p.is_null() { *(p as *mut c_ulonglong) = count as c_ulonglong; }
6530                        }
6531                        (b'l', b'd') | (b'l', b'i') => {
6532                            let val = args.next_arg::<c_long>();
6533                            let neg = val < 0;
6534                            let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
6535                            let b = format_u64(abs);
6536                            let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6537                            let mut fbuf = [0u8; 32];
6538                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6539                            ($write_str)(fbuf.as_ptr(), len); count += len;
6540                        }
6541                        (b'l', b'u') => {
6542                            let val = args.next_arg::<c_ulong>();
6543                            let b = format_u64(val as u64);
6544                            let mut fbuf = [0u8; 32];
6545                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6546                            ($write_str)(fbuf.as_ptr(), len); count += len;
6547                        }
6548                        (b'l', b's') => {
6549                            let p = args.next_arg::<*const wchar_t>();
6550                            if p.is_null() {
6551                                let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
6552                                let pad = width.saturating_sub(slen);
6553                                if flags & FLAG_MINUS != 0 { ($write_str)(b"(null)".as_ptr(), slen); for _ in 0..pad { ($write_char)(b' '); } }
6554                                else { for _ in 0..pad { ($write_char)(b' '); } ($write_str)(b"(null)".as_ptr(), slen); }
6555                                count += slen + pad;
6556                            } else {
6557                                let mut mb = [0u8; 4096];
6558                                let mut n = wide_to_mb(mb.as_mut_ptr(), mb.len(), p);
6559                                if precision >= 0 && (precision as usize) < n { n = precision as usize; }
6560                                let pad = width.saturating_sub(n);
6561                                if flags & FLAG_MINUS != 0 { ($write_str)(mb.as_ptr(), n); for _ in 0..pad { ($write_char)(b' '); } }
6562                                else { for _ in 0..pad { ($write_char)(b' '); } ($write_str)(mb.as_ptr(), n); }
6563                                count += n + pad;
6564                            }
6565                        }
6566                        (b'l', b'c') => {
6567                            let ch = args.next_arg::<c_int>();
6568                            let mut mb = [0u8; 8];
6569                            let mut st: c_uint = 0;
6570                            let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, ch, &mut st);
6571                            if n != !0usize { ($write_str)(mb.as_ptr(), n); count += n; }
6572                        }
6573                        (b'l', b'x') => {
6574                            let val = args.next_arg::<c_ulong>();
6575                            let b = format_hex(val as u64, false);
6576                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6577                            let mut fbuf = [0u8; 32];
6578                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6579                            ($write_str)(fbuf.as_ptr(), len); count += len;
6580                        }
6581                        (b'l', b'X') => {
6582                            let val = args.next_arg::<c_ulong>();
6583                            let b = format_hex(val as u64, true);
6584                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6585                            let mut fbuf = [0u8; 32];
6586                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6587                            ($write_str)(fbuf.as_ptr(), len); count += len;
6588                        }
6589                        (b'l', b'o') => {
6590                            let val = args.next_arg::<c_ulong>();
6591                            let b = format_octal(val as u64, flags & FLAG_HASH != 0);
6592                            let mut fbuf = [0u8; 32];
6593                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6594                            ($write_str)(fbuf.as_ptr(), len); count += len;
6595                        }
6596                        (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
6597                        | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
6598                            let val = args.next_arg::<f64>();
6599                            let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6600                            let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6601                            let mut fbuf = [0u8; 4224];
6602                            let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6603                            let total = apply_width_flags(fbuf.as_mut_ptr().add(4096), fbuf.as_ptr(), flen, width, flags);
6604                            core::ptr::copy_nonoverlapping(fbuf.as_ptr().add(4096), fbuf.as_mut_ptr(), total);
6605                            ($write_str)(fbuf.as_ptr(), total); count += total;
6606                        }
6607                        (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
6608                        | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
6609                            #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
6610                            let val = {
6611                                let lo: u64 = args.next_arg::<u64>();
6612                                let hi: u64 = args.next_arg::<u64>();
6613                                let combined: u128 = ((hi as u128) << 64) | (lo as u128);
6614                                f128::from_bits(combined) as f64
6615                            };
6616                            #[cfg(target_arch = "x86_64")]
6617                            let val = args.next_arg::<f64>();
6618                            let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6619                            let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6620                            let mut fbuf = [0u8; 4224];
6621                            let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6622                            let total = apply_width_flags(fbuf.as_mut_ptr().add(4096), fbuf.as_ptr(), flen, width, flags);
6623                            core::ptr::copy_nonoverlapping(fbuf.as_ptr().add(4096), fbuf.as_mut_ptr(), total);
6624                            ($write_str)(fbuf.as_ptr(), total); count += total;
6625                        }
6626                        _ => { ($write_char)(b'%'); ($write_char)(len_mod); ($write_char)(spec); count += 3; }
6627                    }
6628                }
6629            } else {
6630                spec = *fmt.add(i) as u8;
6631                match spec {
6632                    b's' => {
6633                        let s = args.next_arg::<*const c_char>();
6634                        if s.is_null() {
6635                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
6636                            let padded_len = if width > slen { width } else { slen };
6637                            let pad = padded_len - slen;
6638                            if flags & FLAG_MINUS != 0 {
6639                                ($write_str)(b"(null)".as_ptr(), slen);
6640                                for _ in 0..pad { ($write_char)(b' '); }
6641                            } else {
6642                                for _ in 0..pad { ($write_char)(b' '); }
6643                                ($write_str)(b"(null)".as_ptr(), slen);
6644                            }
6645                            count += padded_len;
6646                        } else {
6647                            let full_len = strlen(s as *const c_char);
6648                            let slen = if precision >= 0 { (precision as usize).min(full_len) } else { full_len };
6649                            let padded_len = if width > slen { width } else { slen };
6650                            let pad = padded_len - slen;
6651                            if flags & FLAG_MINUS != 0 {
6652                                ($write_str)(s as *const u8, slen);
6653                                for _ in 0..pad { ($write_char)(b' '); }
6654                            } else {
6655                                for _ in 0..pad { ($write_char)(b' '); }
6656                                ($write_str)(s as *const u8, slen);
6657                            }
6658                            count += padded_len;
6659                        }
6660                    }
6661                    b'd' | b'i' => {
6662                        let d = args.next_arg::<c_int>();
6663                        let neg = d < 0;
6664                        let abs = if neg { d.wrapping_neg() as u64 } else { d as u64 };
6665                        let b = format_u64(abs);
6666                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6667                        let mut fbuf = [0u8; 32];
6668                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6669                        ($write_str)(fbuf.as_ptr(), len); count += len;
6670                    }
6671                    b'u' => {
6672                        let u = args.next_arg::<c_uint>();
6673                        let b = format_u64(u as u64);
6674                        let mut fbuf = [0u8; 32];
6675                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6676                        ($write_str)(fbuf.as_ptr(), len); count += len;
6677                    }
6678                    b'x' => {
6679                        let x = args.next_arg::<c_uint>();
6680                        let b = format_hex(x as u64, false);
6681                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6682                        let mut fbuf = [0u8; 32];
6683                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6684                        ($write_str)(fbuf.as_ptr(), len); count += len;
6685                    }
6686                    b'X' => {
6687                        let x = args.next_arg::<c_uint>();
6688                        let b = format_hex(x as u64, true);
6689                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6690                        let mut fbuf = [0u8; 32];
6691                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6692                        ($write_str)(fbuf.as_ptr(), len); count += len;
6693                    }
6694                    b'o' => {
6695                        let o = args.next_arg::<c_uint>();
6696                        let b = format_octal(o as u64, flags & FLAG_HASH != 0);
6697                        let mut fbuf = [0u8; 32];
6698                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6699                        ($write_str)(fbuf.as_ptr(), len); count += len;
6700                    }
6701                    b'c' => {
6702                        let ch = args.next_arg::<c_int>();
6703                        if width > 1 {
6704                            let pad = width - 1;
6705                            if flags & FLAG_MINUS != 0 {
6706                                ($write_char)(ch as u8); count += 1;
6707                                for _ in 0..pad { ($write_char)(b' '); count += 1; }
6708                            } else {
6709                                for _ in 0..pad { ($write_char)(b' '); count += 1; }
6710                                ($write_char)(ch as u8); count += 1;
6711                            }
6712                        } else {
6713                            ($write_char)(ch as u8); count += 1;
6714                        }
6715                    }
6716                    b'p' => {
6717                        let p = args.next_arg::<*const c_void>();
6718                        let mut fbuf = [0u8; 20];
6719                        fbuf[0] = b'0'; fbuf[1] = b'x';
6720                        let b = format_hex(p as u64, false);
6721                        core::ptr::copy_nonoverlapping(b.0.as_ptr(), fbuf.as_mut_ptr().add(2), b.1);
6722                        ($write_str)(fbuf.as_ptr(), b.1 + 2); count += b.1 + 2;
6723                    }
6724                    b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
6725                        let val = args.next_arg::<f64>();
6726                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6727                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6728                        let mut fbuf = [0u8; 4224];
6729                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6730                        let total = apply_width_flags(fbuf.as_mut_ptr().add(4096), fbuf.as_ptr(), flen, width, flags);
6731                        core::ptr::copy_nonoverlapping(fbuf.as_ptr().add(4096), fbuf.as_mut_ptr(), total);
6732                        ($write_str)(fbuf.as_ptr(), total); count += total;
6733                    }
6734                    b'%' => { ($write_char)(b'%'); count += 1; }
6735                    b'n' => {
6736                        let p = args.next_arg::<*mut c_void>();
6737                        if !p.is_null() { *(p as *mut c_int) = count as c_int; }
6738                    }
6739                    _ => { ($write_char)(b'%'); ($write_char)(spec); count += 2; }
6740                }
6741            }
6742            i += 1;
6743        }
6744        count as c_int
6745    }};
6746}
6747
6748unsafe fn format_u64(mut val: u64) -> ([u8; 20], usize) {
6749    let mut buf = [0u8; 20];
6750    if val == 0 { buf[0] = b'0'; return (buf, 1); }
6751    let mut tmp = [0u8; 20];
6752    let mut pos = 20;
6753    while val > 0 { pos -= 1; tmp[pos] = b'0' + (val % 10) as u8; val /= 10; }
6754    let len = 20 - pos;
6755    core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6756    (buf, len)
6757}
6758
6759unsafe fn format_i64(val: i64) -> ([u8; 21], usize) {
6760    let mut buf = [0u8; 21];
6761    if val < 0 {
6762        buf[0] = b'-';
6763        let (inner, len) = format_u64((-(val as i128)) as u64);
6764        core::ptr::copy_nonoverlapping(inner.as_ptr(), buf.as_mut_ptr().add(1), len);
6765        (buf, len + 1)
6766    } else {
6767        let (inner, len) = format_u64(val as u64);
6768        core::ptr::copy_nonoverlapping(inner.as_ptr(), buf.as_mut_ptr(), len);
6769        (buf, len)
6770    }
6771}
6772
6773unsafe fn format_hex(mut val: u64, uppercase: bool) -> ([u8; 16], usize) {
6774    let digits = if uppercase { b"0123456789ABCDEF" } else { b"0123456789abcdef" };
6775    let mut buf = [0u8; 16];
6776    if val == 0 { buf[0] = b'0'; return (buf, 1); }
6777    let mut tmp = [0u8; 16];
6778    let mut pos = 16;
6779    while val > 0 { pos -= 1; tmp[pos] = digits[(val & 0xf) as usize]; val >>= 4; }
6780    let len = 16 - pos;
6781    core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6782    (buf, len)
6783}
6784
6785unsafe fn format_octal(mut val: u64, alt: bool) -> ([u8; 24], usize) {
6786    let mut buf = [0u8; 24];
6787    if val == 0 {
6788        buf[0] = b'0';
6789        return (buf, 1);
6790    }
6791    let mut tmp = [0u8; 24];
6792    let mut pos = 24;
6793    while val > 0 {
6794        pos -= 1;
6795        tmp[pos] = b'0' + (val & 7) as u8;
6796        val >>= 3;
6797    }
6798    let len = 24 - pos;
6799    if alt {
6800        tmp[pos - 1] = b'0';
6801        core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos - 1), buf.as_mut_ptr(), len + 1);
6802        (buf, len + 1)
6803    } else {
6804        core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6805        (buf, len)
6806    }
6807}
6808
6809unsafe fn format_int(
6810    dst: *mut u8,
6811    digits: *const u8,
6812    digits_len: usize,
6813    sign: Option<u8>,
6814    prefix: Option<u8>,
6815    precision: i32,
6816    width: usize,
6817    flags: u8,
6818    octal_alt: bool,
6819) -> usize {
6820    let num_digits = if precision == 0 && digits_len == 1 && *digits == b'0' && !octal_alt {
6821        0
6822    } else {
6823        digits_len
6824    };
6825    let prec = precision as usize;
6826    let zero_pad = if precision >= 0 && prec > num_digits { prec - num_digits } else { 0 };
6827
6828    let sign_len = sign.map_or(0, |_| 1);
6829    let prefix_len = prefix.map_or(0, |_| 2);
6830    let content_len = sign_len + prefix_len + zero_pad + num_digits;
6831
6832    let mut buf = [0u8; 32];
6833    let mut pos = 0usize;
6834    if let Some(c) = sign { buf[pos] = c; pos += 1; }
6835    if let Some(c) = prefix { buf[pos] = b'0'; pos += 1; buf[pos] = c; pos += 1; }
6836    for _ in 0..zero_pad { buf[pos] = b'0'; pos += 1; }
6837    if num_digits > 0 {
6838        core::ptr::copy_nonoverlapping(digits, buf.as_mut_ptr().add(pos), num_digits);
6839    }
6840
6841    if content_len >= width {
6842        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, content_len);
6843        return content_len;
6844    }
6845    let pad = width - content_len;
6846    if flags & FLAG_MINUS != 0 {
6847        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, content_len);
6848        for i in 0..pad { *dst.add(content_len + i) = b' '; }
6849    } else if flags & FLAG_ZERO != 0 && precision < 0 {
6850        let fixed = sign_len + prefix_len;
6851        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, fixed);
6852        for i in fixed..width - num_digits { *dst.add(i) = b'0'; }
6853        if num_digits > 0 {
6854            core::ptr::copy_nonoverlapping(digits, dst.add(width - num_digits), num_digits);
6855        }
6856    } else {
6857        for i in 0..pad { *dst.add(i) = b' '; }
6858        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst.add(pad), content_len);
6859    }
6860    width
6861}
6862
6863unsafe fn format_f64(val: f64) -> ([u8; 64], usize) {
6864    let mut buf = [0u8; 64];
6865    let mut pos = 0usize;
6866    let mut v = val;
6867    if v.is_nan() {
6868        let nan = b"nan";
6869        core::ptr::copy_nonoverlapping(nan.as_ptr(), buf.as_mut_ptr(), 3);
6870        return (buf, 3);
6871    }
6872    if v < 0.0 { buf[pos] = b'-'; pos += 1; v = -v; }
6873    if v.is_infinite() {
6874        let inf = b"inf";
6875        core::ptr::copy_nonoverlapping(inf.as_ptr(), buf.as_mut_ptr().add(pos), 3);
6876        return (buf, pos + 3);
6877    }
6878    let int_part = v as u64;
6879    let frac = v - int_part as f64;
6880    let (ibuf, ilen) = format_u64(int_part);
6881    core::ptr::copy_nonoverlapping(ibuf.as_ptr(), buf.as_mut_ptr().add(pos), ilen);
6882    pos += ilen;
6883    buf[pos] = b'.';
6884    pos += 1;
6885    let mut f = frac;
6886    for _ in 0..6 { f *= 10.0; let digit = f as u8; buf[pos] = b'0' + digit; pos += 1; f -= digit as f64; }
6887    (buf, pos)
6888}
6889
6890// Float format specifier type
6891const FMT_F: u8 = 0;
6892const FMT_E: u8 = 1;
6893const FMT_G: u8 = 2;
6894const FMT_A: u8 = 3;
6895
6896const FLAG_HASH: u8 = 1;
6897const FLAG_PLUS: u8 = 2;
6898const FLAG_SPACE: u8 = 4;
6899const FLAG_ZERO: u8 = 8;
6900const FLAG_MINUS: u8 = 16;
6901
6902// === %f formatting helpers ===
6903
6904/// Convert (mant << shift) to decimal string. Returns byte count written to buf.
6905/// mant is a 53-bit significand, shift is the left-shift amount (can be 0..~971).
6906unsafe fn bigint_to_decimal(buf: *mut u8, mant: u64, shift: u32) -> usize {
6907    // Store as little-endian u32 limbs. Max bits: 53 + 971 ≈ 1024 → 32 limbs.
6908    let nlimbs = (2 + (shift + 31) / 32) as usize;
6909    let mut limbs = [0u32; 36];
6910    limbs[0] = mant as u32;
6911    limbs[1] = (mant >> 32) as u32;
6912
6913    let ws = (shift / 32) as usize;
6914    let bs = shift % 32;
6915
6916    // Word-level shift left
6917    if ws > 0 {
6918        let mut i = 1usize;
6919        loop {
6920            limbs[i + ws] = limbs[i];
6921            if i == 0 { break; }
6922            i -= 1;
6923        }
6924        for j in 0..ws { limbs[j] = 0; }
6925    }
6926    // Bit-level shift left
6927    if bs > 0 {
6928        let mut carry = 0u32;
6929        let end = nlimbs.min(ws + 3);
6930        for i in ws..end {
6931            let new_val = (limbs[i] << bs) | carry;
6932            carry = limbs[i] >> (32 - bs);
6933            limbs[i] = new_val;
6934        }
6935    }
6936
6937    // Find highest non-zero limb
6938    let mut used = nlimbs;
6939    while used > 0 && limbs[used - 1] == 0 { used -= 1; }
6940    if used == 0 { *buf = b'0'; return 1; }
6941
6942    // Repeated division by 10 to extract decimal digits
6943    let mut digits = [0u8; 400];
6944    let mut nd = 0usize;
6945    loop {
6946        let mut all_zero = true;
6947        for i in 0..used { if limbs[i] != 0 { all_zero = false; break; } }
6948        if all_zero { break; }
6949        let mut rem = 0u64;
6950        for i in (0..used).rev() {
6951            let val = (rem << 32) | limbs[i] as u64;
6952            limbs[i] = (val / 10) as u32;
6953            rem = val % 10;
6954        }
6955        digits[nd] = rem as u8;
6956        nd += 1;
6957    }
6958    // Write digits in big-endian order
6959    for i in 0..nd { *buf.add(i) = b'0' + digits[nd - 1 - i]; }
6960    nd
6961}
6962
6963/// Compute `count` fractional digits of frac_bits / 2^shift using u128 arithmetic.
6964/// shift must be <= 124. Returns true if any value remains after the last digit.
6965unsafe fn frac_digits_u128(buf: *mut u8, frac_bits: u64, shift: u32, count: usize) -> bool {
6966    let mask: u128 = (1u128 << shift) - 1;
6967    let mut rem = frac_bits as u128;
6968    for i in 0..count {
6969        rem *= 10;
6970        let digit = (rem >> shift) as u8;
6971        rem &= mask;
6972        *buf.add(i) = digit;
6973    }
6974    rem != 0
6975}
6976
6977/// Compute `count` fractional digits of frac_bits / 2^shift using big-integer arithmetic.
6978/// For shift > 124 (up to ~1074). Returns true if any value remains after the last digit.
6979unsafe fn frac_digits_bigint(buf: *mut u8, frac_bits: u64, shift: u32, count: usize) -> bool {
6980    let nlimbs = ((shift + 31) / 32) as usize;
6981    let mut rem = [0u32; 36]; // enough for shift up to 1088
6982    rem[0] = frac_bits as u32;
6983    if nlimbs > 1 { rem[1] = (frac_bits >> 32) as u32; }
6984    // Mask to exactly `shift` bits
6985    let hi_word = (shift / 32) as usize;
6986    let hi_bit = shift % 32;
6987    if hi_bit > 0 && hi_word < nlimbs {
6988        rem[hi_word] &= (1u32 << hi_bit) - 1;
6989    }
6990    // Zero upper limbs beyond shift
6991    let clear_from = if hi_bit > 0 { hi_word + 1 } else { hi_word };
6992    for j in clear_from..nlimbs { rem[j] = 0; }
6993
6994    for i in 0..count {
6995        // Multiply remainder by 10
6996        let mut carry = 0u64;
6997        for j in 0..nlimbs {
6998            let val = rem[j] as u64 * 10 + carry;
6999            rem[j] = val as u32;
7000            carry = val >> 32;
7001        }
7002        // Extract digit from bit position `shift`
7003        let digit: u32;
7004        if hi_bit == 0 {
7005            digit = if hi_word < nlimbs { rem[hi_word] } else { carry as u32 };
7006        } else {
7007            let mut d = if hi_word < nlimbs { rem[hi_word] >> hi_bit } else { 0 };
7008            if hi_word + 1 < nlimbs {
7009                d |= rem[hi_word + 1] << (32 - hi_bit);
7010            } else if carry > 0 {
7011                d |= (carry as u32) << (32 - hi_bit);
7012            }
7013            digit = d;
7014        }
7015        *buf.add(i) = digit.min(9) as u8;
7016        // Clear bits from position `shift` upward (keep remainder < 2^shift)
7017        if hi_bit == 0 {
7018            if hi_word < nlimbs { rem[hi_word] = 0; }
7019        } else {
7020            if hi_word < nlimbs {
7021                rem[hi_word] &= (1u32 << hi_bit) - 1;
7022            }
7023            for j in (hi_word + 1)..nlimbs { rem[j] = 0; }
7024        }
7025    }
7026    // Check if remainder is non-zero
7027    for i in 0..nlimbs { if rem[i] != 0 { return true; } }
7028    false
7029}
7030
7031/// Increment a decimal string stored at buf[0..*len] in-place.
7032unsafe fn increment_decimal(buf: *mut u8, len: &mut usize) {
7033    let mut j = *len;
7034    loop {
7035        if j == 0 {
7036            // Shift right and prepend '1'
7037            let l = *len;
7038            for i in (0..l).rev() { *buf.add(i + 1) = *buf.add(i); }
7039            *buf = b'1';
7040            *len = l + 1;
7041            return;
7042        }
7043        j -= 1;
7044        let d = *buf.add(j);
7045        if d < b'9' { *buf.add(j) = d + 1; return; }
7046        *buf.add(j) = b'0';
7047    }
7048}
7049
7050// Write float to dst. Returns bytes written. Does NOT handle width/flags padding.
7051unsafe fn format_f64_full(
7052    dst: *mut u8, val: f64, fmt_type: u8, precision: i32, flags: u8, uppercase: bool,
7053) -> usize {
7054    let mut pos = 0usize;
7055
7056    // NaN
7057    if val.is_nan() {
7058        let nan_s: &[u8] = if uppercase { b"NAN" } else { b"nan" };
7059        core::ptr::copy_nonoverlapping(nan_s.as_ptr(), dst, 3);
7060        return 3;
7061    }
7062    let neg = val.is_sign_negative();
7063    let v = if neg { -val } else { val };
7064
7065    // Inf
7066    if v.is_infinite() {
7067        if neg { *dst.add(pos) = b'-'; pos += 1; }
7068        else if flags & FLAG_PLUS != 0 { *dst.add(pos) = b'+'; pos += 1; }
7069        else if flags & FLAG_SPACE != 0 { *dst.add(pos) = b' '; pos += 1; }
7070        let inf_s: &[u8] = if uppercase { b"INF" } else { b"inf" };
7071        core::ptr::copy_nonoverlapping(inf_s.as_ptr(), dst.add(pos), 3);
7072        return pos + 3;
7073    }
7074
7075    // Sign
7076    if neg { *dst.add(pos) = b'-'; pos += 1; }
7077    else if flags & FLAG_PLUS != 0 { *dst.add(pos) = b'+'; pos += 1; }
7078    else if flags & FLAG_SPACE != 0 { *dst.add(pos) = b' '; pos += 1; }
7079
7080    // === Hex float ===
7081    if fmt_type == FMT_A {
7082        return pos + fmt_hex_float(dst.add(pos), val, precision, flags, uppercase);
7083    }
7084
7085    // === Decimal formats ===
7086    let p: usize;
7087    let mut exp: i32;
7088    let use_f: bool;
7089
7090    match fmt_type {
7091        FMT_G => {
7092            let gp = if precision < 0 { 6usize } else if precision == 0 { 1usize } else { precision as usize };
7093            exp = if v > 0.0 { compute_exp10(v) } else { 0 };
7094            use_f = exp >= -4 && exp < gp as i32;
7095            if use_f {
7096                p = if exp < 0 { gp + ((-exp) as usize - 1) }
7097                    else if (exp as usize) < gp { gp - exp as usize - 1 }
7098                    else { 0 };
7099            } else {
7100                p = gp - 1;
7101            }
7102        }
7103        FMT_E => {
7104            p = if precision < 0 { 6usize } else { precision as usize };
7105            exp = if v > 0.0 { compute_exp10(v) } else { 0 };
7106            use_f = false;
7107        }
7108        _ => {
7109            p = if precision < 0 { 6usize } else { precision as usize };
7110            exp = 0;
7111            use_f = true;
7112        }
7113    }
7114
7115    if v == 0.0 {
7116        *dst.add(pos) = b'0'; pos += 1;
7117        if !(fmt_type == FMT_G && flags & FLAG_HASH == 0) {
7118            if p > 0 || flags & FLAG_HASH != 0 {
7119                *dst.add(pos) = b'.'; pos += 1;
7120                for _ in 0..p { *dst.add(pos) = b'0'; pos += 1; }
7121            }
7122        }
7123        if !use_f {
7124            let ec = if uppercase { b'E' } else { b'e' };
7125            *dst.add(pos) = ec; pos += 1;
7126            *dst.add(pos) = b'+'; pos += 1;
7127            *dst.add(pos) = b'0'; pos += 1;
7128            *dst.add(pos) = b'0'; pos += 1;
7129        }
7130        return pos;
7131    }
7132
7133    // === %f format: exact bit-based arithmetic, returns early ===
7134    if use_f {
7135        let bits = v.to_bits();
7136        let raw_mant = bits & 0x000FFFFFFFFFFFFF;
7137        let raw_exp_bits = ((bits >> 52) & 0x7FF) as i32;
7138        let (mant_b, bin_exp) = if raw_exp_bits == 0 {
7139            (raw_mant, -1022i32)
7140        } else {
7141            (raw_mant | (1u64 << 52), raw_exp_bits - 1023)
7142        };
7143
7144        // Integer part as decimal string
7145        let mut ibuf = [0u8; 400];
7146        let mut ilen: usize;
7147        if bin_exp < 0 {
7148            ibuf[0] = b'0'; ilen = 1;
7149        } else if bin_exp <= 63 {
7150            let int_val = if bin_exp <= 52 { mant_b >> (52 - bin_exp) }
7151                          else { mant_b << (bin_exp - 52) };
7152            let (buf2, len2) = format_u64(int_val);
7153            ibuf[..len2].copy_from_slice(&buf2[..len2]);
7154            ilen = len2;
7155        } else {
7156            ilen = bigint_to_decimal(ibuf.as_mut_ptr(), mant_b, (bin_exp - 52) as u32);
7157        }
7158
7159        // Fractional digits
7160        let mut fbuf = [0u8; 1100];
7161        let mut has_rest = false;
7162        if p > 0 && bin_exp < 52 {
7163            let shift = (52 - bin_exp) as u32;
7164            let frac_bits = if bin_exp >= 0 { mant_b & ((1u64 << shift) - 1) } else { mant_b };
7165            if shift <= 124 {
7166                has_rest = frac_digits_u128(fbuf.as_mut_ptr(), frac_bits, shift, p + 1);
7167            } else {
7168                has_rest = frac_digits_bigint(fbuf.as_mut_ptr(), frac_bits, shift, p + 1);
7169            }
7170        }
7171
7172        // Rounding
7173        if p > 0 && bin_exp < 52 {
7174            let next_d = fbuf[p];
7175            let last_d = fbuf[p - 1];
7176            if next_d > 5 || (next_d == 5 && (has_rest || last_d & 1 != 0)) {
7177                let mut carry = true;
7178                for j in (0..p).rev() {
7179                    if !carry { break; }
7180                    fbuf[j] += 1;
7181                    if fbuf[j] < 10 { carry = false; break; }
7182                    fbuf[j] = 0;
7183                }
7184                if carry { increment_decimal(ibuf.as_mut_ptr(), &mut ilen); }
7185            }
7186        } else if p == 0 {
7187            // %.0f: round integer based on fractional part
7188            if bin_exp >= 0 && bin_exp < 52 {
7189                let shift = (52 - bin_exp) as u32;
7190                let frac_bits = mant_b & ((1u64 << shift) - 1);
7191                let half = 1u64 << (shift - 1);
7192                let last_d = ibuf[ilen - 1] - b'0';
7193                if frac_bits > half || (frac_bits == half && last_d & 1 != 0) {
7194                    increment_decimal(ibuf.as_mut_ptr(), &mut ilen);
7195                }
7196            }
7197        }
7198
7199        // Output
7200        core::ptr::copy_nonoverlapping(ibuf.as_ptr(), dst.add(pos), ilen);
7201        pos += ilen;
7202        if p > 0 || flags & FLAG_HASH != 0 {
7203            *dst.add(pos) = b'.'; pos += 1;
7204            for i in 0..p { *dst.add(pos) = b'0' + fbuf[i]; pos += 1; }
7205        }
7206        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7207            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7208            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7209        }
7210        return pos;
7211    }
7212
7213    // === %e/%g format: exact big-integer digit extraction ===
7214    // D = floor(v * 10^(p+1-exp)), using v = mant_b * 2^(bin_exp-52)
7215    let mut fbuf = [0u8; 20];
7216    let mut int_part: u64;
7217    {
7218        let bits_v = v.to_bits();
7219        let raw_mant_v = bits_v & 0x000FFFFFFFFFFFFF;
7220        let raw_exp_v = ((bits_v >> 52) & 0x7FF) as i32;
7221        let (mant_b_v, bin_exp_v) = if raw_exp_v == 0 {
7222            (raw_mant_v, -1022i32)
7223        } else {
7224            (raw_mant_v | (1u64 << 52), raw_exp_v - 1023)
7225        };
7226
7227        let s: i32 = (p as i32) + 1 - exp;
7228        let bs: i32 = bin_exp_v - 52 + s;
7229
7230        let mut limbs = [0u32; 40];
7231        limbs[0] = mant_b_v as u32;
7232        limbs[1] = (mant_b_v >> 32) as u32;
7233        let mut nlimbs: usize = if limbs[1] != 0 { 2 } else { 1 };
7234
7235        if s > 0 {
7236            for _ in 0..(s as usize) {
7237                let mut carry = 0u64;
7238                for j in 0..nlimbs {
7239                    let val = limbs[j] as u64 * 5 + carry;
7240                    limbs[j] = val as u32;
7241                    carry = val >> 32;
7242                }
7243                if carry > 0 { limbs[nlimbs] = carry as u32; nlimbs += 1; }
7244            }
7245        }
7246
7247        if bs > 0 {
7248            let ws = (bs as u32 / 32) as usize;
7249            let bit = bs as u32 % 32;
7250            if ws > 0 {
7251                let mut i = nlimbs;
7252                while i > 0 { i -= 1; if i + ws < 40 { limbs[i + ws] = limbs[i]; } limbs[i] = 0; }
7253                nlimbs += ws;
7254            }
7255            if bit > 0 {
7256                let mut carry = 0u32;
7257                for i in ws..nlimbs {
7258                    let new_val = (limbs[i] << bit) | carry;
7259                    carry = limbs[i] >> (32 - bit);
7260                    limbs[i] = new_val;
7261                }
7262                if carry > 0 && nlimbs < 40 { limbs[nlimbs] = carry; nlimbs += 1; }
7263            }
7264        }
7265
7266        let mut has_rest = false;
7267        if s < 0 {
7268            for _ in 0..(-s as usize) {
7269                let mut rem = 0u64;
7270                for i in (0..nlimbs).rev() {
7271                    let val = (rem << 32) | limbs[i] as u64;
7272                    limbs[i] = (val / 5) as u32;
7273                    rem = val % 5;
7274                }
7275                if rem != 0 { has_rest = true; }
7276            }
7277        }
7278
7279        if bs < 0 {
7280            let rshift = (-bs) as u32;
7281            let ws = (rshift / 32) as usize;
7282            let bit = rshift % 32;
7283            if ws > 0 {
7284                for j in 0..ws.min(nlimbs) { if limbs[j] != 0 { has_rest = true; } }
7285                for i in ws..nlimbs { limbs[i - ws] = limbs[i]; }
7286                nlimbs = nlimbs.saturating_sub(ws);
7287            }
7288            if bit > 0 && nlimbs > 0 {
7289                let mask = (1u32 << bit) - 1;
7290                if limbs[0] & mask != 0 { has_rest = true; }
7291                for i in 0..nlimbs - 1 {
7292                    limbs[i] = (limbs[i] >> bit) | (limbs[i + 1] << (32 - bit));
7293                }
7294                limbs[nlimbs - 1] >>= bit;
7295            }
7296        }
7297
7298        while nlimbs > 0 && limbs[nlimbs - 1] == 0 { nlimbs -= 1; }
7299
7300        let ndigits = p + 2;
7301        let mut all_digits = [0u8; 25];
7302        let mut nd = 0usize;
7303        if nlimbs > 0 {
7304            loop {
7305                let mut all_zero = true;
7306                for i in 0..nlimbs { if limbs[i] != 0 { all_zero = false; break; } }
7307                if all_zero { break; }
7308                let mut rem64 = 0u64;
7309                for i in (0..nlimbs).rev() {
7310                    let val = (rem64 << 32) | limbs[i] as u64;
7311                    limbs[i] = (val / 10) as u32;
7312                    rem64 = val % 10;
7313                }
7314                if nd < 25 { all_digits[nd] = rem64 as u8; }
7315                nd += 1;
7316            }
7317        }
7318
7319        if nd >= ndigits {
7320            for i in 0..ndigits { fbuf[ndigits - 1 - i] = all_digits[i]; }
7321        } else {
7322            for i in 0..nd { fbuf[ndigits - 1 - i] = all_digits[i]; }
7323            for i in nd..ndigits { fbuf[ndigits - 1 - i] = 0; }
7324        }
7325
7326        int_part = fbuf[0] as u64;
7327
7328        // Round half to even: next_d is the rounding digit beyond precision
7329        if p > 0 {
7330            let next_d = fbuf[p + 1];
7331            let last_d = fbuf[p];
7332            if next_d > 5 || (next_d == 5 && (has_rest || last_d & 1 != 0)) {
7333                let mut carry = true;
7334                for j in (1..=p).rev() {
7335                    if !carry { break; }
7336                    let d = fbuf[j] + 1;
7337                    if d < 10 { fbuf[j] = d; carry = false; break; }
7338                    fbuf[j] = 0;
7339                }
7340                if carry { int_part += 1; }
7341            }
7342        } else {
7343            let next_d = fbuf[1];
7344            if next_d > 5 || (next_d == 5 && (has_rest || int_part & 1 != 0)) {
7345                int_part += 1;
7346            }
7347        }
7348
7349        // fbuf[1..=p] are now the fractional digits for output
7350        // Shift them to fbuf[0..p] so output code can index fbuf[0..p]
7351        for i in 0..p { fbuf[i] = fbuf[i + 1]; }
7352    }
7353
7354    if !use_f && int_part >= 10 {
7355        exp += 1;
7356        int_part = 1;
7357    }
7358
7359    // Format output
7360    if use_f {
7361        // %f style
7362        let (ibuf, ilen) = format_u64(int_part);
7363        core::ptr::copy_nonoverlapping(ibuf.as_ptr(), dst.add(pos), ilen);
7364        pos += ilen;
7365        if p > 0 || flags & FLAG_HASH != 0 {
7366            *dst.add(pos) = b'.'; pos += 1;
7367            for idx in 0..p { *dst.add(pos) = b'0' + fbuf[idx]; pos += 1; }
7368        }
7369        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7370            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7371            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7372        }
7373    } else {
7374        // %e style
7375        *dst.add(pos) = b'0' + int_part as u8; pos += 1;
7376        if p > 0 || flags & FLAG_HASH != 0 {
7377            *dst.add(pos) = b'.'; pos += 1;
7378            for idx in 0..p { *dst.add(pos) = b'0' + fbuf[idx]; pos += 1; }
7379        }
7380        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7381            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7382            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7383        }
7384        let ec = if uppercase { b'E' } else { b'e' };
7385        *dst.add(pos) = ec; pos += 1;
7386        *dst.add(pos) = if exp < 0 { b'-' } else { b'+' }; pos += 1;
7387        let eabs = if exp < 0 { (-exp) as u32 } else { exp as u32 };
7388        if eabs < 10 { *dst.add(pos) = b'0'; pos += 1; }
7389        let (ebuf, elen) = format_u64(eabs as u64);
7390        core::ptr::copy_nonoverlapping(ebuf.as_ptr(), dst.add(pos), elen);
7391        pos += elen;
7392    }
7393
7394    pos
7395}
7396
7397// Compute decimal exponent: floor(log10(v)) with correction
7398unsafe fn compute_exp10(v: f64) -> i32 {
7399    let e = libm::floor(libm::log10(v)) as i32;
7400    let probe = v / libm::pow(10.0, e as f64);
7401    if probe >= 10.0 { e + 1 }
7402    else if probe < 1.0 { e - 1 }
7403    else { e }
7404}
7405
7406// Write hex float to dst. Returns bytes written.
7407unsafe fn fmt_hex_float(dst: *mut u8, val: f64, precision: i32, _flags: u8, uppercase: bool) -> usize {
7408    // Handle zero (and negative zero) specially
7409    if val.to_bits() & 0x7FFFFFFFFFFFFFFF == 0 {
7410        let lc = !uppercase;
7411        let pfx: &[u8] = if lc { b"0x" } else { b"0X" };
7412        let p = if precision < 0 { 0usize } else { precision as usize };
7413        let mut pos = 0usize;
7414        core::ptr::copy_nonoverlapping(pfx.as_ptr(), dst.add(pos), 2); pos += 2;
7415        *dst.add(pos) = b'0'; pos += 1;
7416        if p > 0 {
7417            *dst.add(pos) = b'.'; pos += 1;
7418            for _ in 0..p { *dst.add(pos) = b'0'; pos += 1; }
7419        }
7420        let pc = if lc { b'p' } else { b'P' };
7421        *dst.add(pos) = pc; pos += 1;
7422        *dst.add(pos) = b'+'; pos += 1;
7423        *dst.add(pos) = b'0'; pos += 1;
7424        return pos;
7425    }
7426    let bits = val.to_bits();
7427    let exp_bits = ((bits >> 52) & 0x7FF) as i32;
7428    let mant_bits = bits & 0x000FFFFFFFFFFFFF;
7429    let (mut e, mut m) = if exp_bits == 0 { (1 - 1023, mant_bits) } else { (exp_bits - 1023, mant_bits | (1u64 << 52)) };
7430    // musl normalizes subnormals so the leading digit is always 1, which
7431    // lets the exponent go below -1022 (e.g. 0x1p-1074 for the smallest).
7432    if exp_bits == 0 && m != 0 {
7433        let shift = m.leading_zeros() as i32 - 11;
7434        m <<= shift;
7435        e -= shift;
7436    }
7437    let explicit = precision >= 0;
7438    let p = if explicit { precision as usize } else { 13usize };
7439    let mut pos = 0usize;
7440    let lc = !uppercase;
7441    let pfx: &[u8] = if lc { b"0x" } else { b"0X" };
7442    core::ptr::copy_nonoverlapping(pfx.as_ptr(), dst.add(pos), 2); pos += 2;
7443
7444    // Leading digit from bit 52 (1 for every normalized value).
7445    let lead_pos = pos;
7446    let mut lead = ((m >> 52) & 0xF) as u8;
7447    *dst.add(pos) = hex_digit_char(lead, lc); pos += 1;
7448    let mut frac_start = pos;
7449    if p > 0 {
7450        *dst.add(pos) = b'.'; pos += 1;
7451        frac_start = pos;
7452    }
7453
7454    // Extract p hex digits from the fraction, most significant nibble first.
7455    let mut rm = m;
7456    for _ in 0..p {
7457        let nib = ((rm >> 48) & 0xF) as u8;
7458        *dst.add(pos) = hex_digit_char(nib, lc); pos += 1;
7459        rm <<= 4;
7460    }
7461
7462    // Round to nearest, ties to even, based on the next nibble.
7463    let round_nib = ((rm >> 48) & 0xF) as u8;
7464    let rest = rm & 0x0000FFFFFFFFFFFF;
7465    let last_nib = if p > 0 {
7466        hex_char_val(*dst.add(pos - 1))
7467    } else {
7468        lead
7469    };
7470    let should_round = round_nib > 8 || (round_nib == 8 && (rest != 0 || (last_nib & 1) != 0));
7471    if should_round {
7472        let mut j = pos;
7473        loop {
7474            if j == frac_start {
7475                // Carry out of the fraction into the leading digit.
7476                lead += 1;
7477                *dst.add(lead_pos) = hex_digit_char(lead, lc);
7478                break;
7479            }
7480            j -= 1;
7481            let v = hex_char_val(*dst.add(j));
7482            if v < 15 {
7483                *dst.add(j) = hex_digit_char(v + 1, lc);
7484                break;
7485            }
7486            *dst.add(j) = b'0';
7487        }
7488    }
7489
7490    // With no explicit precision, print the shortest exact representation:
7491    // trim trailing fractional zeros and drop the radix point if empty.
7492    if !explicit {
7493        while pos > frac_start && *dst.add(pos - 1) == b'0' {
7494            pos -= 1;
7495        }
7496        if pos == frac_start {
7497            pos = frac_start - 1;
7498        }
7499    }
7500
7501    // Exponent
7502    let pc = if lc { b'p' } else { b'P' };
7503    *dst.add(pos) = pc; pos += 1;
7504    *dst.add(pos) = if e < 0 { b'-' } else { b'+' }; pos += 1;
7505    let eabs = if e < 0 { (-e) as u32 } else { e as u32 };
7506    let (ebuf, elen) = format_u64(eabs as u64);
7507    core::ptr::copy_nonoverlapping(ebuf.as_ptr(), dst.add(pos), elen);
7508    pos += elen;
7509    pos
7510}
7511
7512#[inline]
7513fn hex_digit_char(v: u8, lowercase: bool) -> u8 {
7514    if v < 10 { b'0' + v }
7515    else if lowercase { b'a' + v - 10 }
7516    else { b'A' + v - 10 }
7517}
7518
7519#[inline]
7520fn hex_char_val(c: u8) -> u8 {
7521    if c >= b'0' && c <= b'9' { c - b'0' }
7522    else if c >= b'a' && c <= b'f' { c - b'a' + 10 }
7523    else if c >= b'A' && c <= b'F' { c - b'A' + 10 }
7524    else { 0 }
7525}
7526
7527// Apply width and flags padding to a formatted string in buf[0..len].
7528// Writes the final result to dst. Returns total bytes written.
7529unsafe fn apply_width_flags(
7530    dst: *mut u8, buf: *const u8, len: usize, width: usize, flags: u8,
7531) -> usize {
7532    if len >= width {
7533        core::ptr::copy_nonoverlapping(buf, dst, len);
7534        return len;
7535    }
7536    let pad = width - len;
7537    let pad_char = if flags & FLAG_ZERO != 0 && flags & FLAG_MINUS == 0 { b'0' } else { b' ' };
7538    if flags & FLAG_MINUS != 0 {
7539        // Left align
7540        core::ptr::copy_nonoverlapping(buf, dst, len);
7541        for i in 0..pad { *dst.add(len + i) = pad_char; }
7542    } else {
7543        // Right align
7544        // For zero-padded numbers, sign goes before zeros
7545        if flags & FLAG_ZERO != 0 && len > 0 {
7546            let first = *buf;
7547            if first == b'-' || first == b'+' || first == b' ' {
7548                *dst = first;
7549                for i in 0..pad { *dst.add(1 + i) = pad_char; }
7550                core::ptr::copy_nonoverlapping(buf.add(1), dst.add(1 + pad), len - 1);
7551                return width;
7552            }
7553        }
7554        for i in 0..pad { *dst.add(i) = pad_char; }
7555        core::ptr::copy_nonoverlapping(buf, dst.add(pad), len);
7556    }
7557    width
7558}
7559
7560#[no_mangle]
7561pub unsafe extern "C" fn vprintf(fmt: *const c_char, mut args: VaList) -> c_int {
7562    impl_format!(fmt, args,
7563        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stdout); },
7564        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stdout); }
7565    )
7566}
7567
7568#[no_mangle]
7569pub unsafe extern "C" fn vfprintf(stream: *mut FILE, fmt: *const c_char, mut args: VaList) -> c_int {
7570    impl_format!(fmt, args,
7571        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stream); },
7572        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stream); }
7573    )
7574}
7575
7576#[no_mangle]
7577pub unsafe extern "C" fn printf(fmt: *const c_char, mut args: ...) -> c_int {
7578    impl_format!(fmt, args,
7579        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stdout); },
7580        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stdout); }
7581    )
7582}
7583
7584#[no_mangle]
7585pub unsafe extern "C" fn fprintf(stream: *mut FILE, fmt: *const c_char, mut args: ...) -> c_int {
7586    impl_format!(fmt, args,
7587        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stream); },
7588        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stream); }
7589    )
7590}
7591
7592#[no_mangle]
7593unsafe fn format_write_fd(fd: c_int, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
7594    // cgroupfs (and some other pseudo-filesystems) parse one command per
7595    // write() call, so the whole formatted string must go out at once.
7596    let mut stack = [0u8; 4096];
7597    let mut a1 = args.clone();
7598    let n = format_to_buf(stack.as_mut_ptr(), stack.len(), fmt, &mut a1);
7599    if n < 0 { return -1; }
7600    if (n as usize) < stack.len() {
7601        let w = crate::write(fd, stack.as_ptr() as *const c_void, n as usize);
7602        if w < 0 { return -1; }
7603        return n;
7604    }
7605    let heap = crate::malloc(n as usize + 1) as *mut u8;
7606    if heap.is_null() { return -1; }
7607    let mut a2 = args.clone();
7608    let n2 = format_to_buf(heap, n as usize + 1, fmt, &mut a2);
7609    if n2 < 0 { crate::free(heap as *mut c_void); return -1; }
7610    let w = crate::write(fd, heap as *const c_void, n2 as usize);
7611    crate::free(heap as *mut c_void);
7612    if w < 0 { return -1; }
7613    n2
7614}
7615
7616#[no_mangle]
7617pub unsafe extern "C" fn dprintf(fd: c_int, fmt: *const c_char, mut args: ...) -> c_int {
7618    format_write_fd(fd, fmt, &mut args)
7619}
7620
7621#[no_mangle]
7622pub unsafe extern "C" fn vdprintf(fd: c_int, fmt: *const c_char, mut args: VaList) -> c_int {
7623    format_write_fd(fd, fmt, &mut args)
7624}
7625
7626// ============================================================
7627// sprintf / snprintf / vsprintf / vsnprintf
7628// ============================================================
7629
7630unsafe fn format_to_buf(buf: *mut u8, cap: usize, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
7631    let mut pos = 0usize;
7632    let mut i = 0usize;
7633    let mut count = 0usize;
7634    macro_rules! wc {
7635        ($c:expr) => { if pos < cap { *buf.add(pos) = $c; } pos += 1; count += 1; }
7636    }
7637    macro_rules! ws {
7638        ($s:expr, $len:expr) => {{
7639            let __len = $len;
7640            for k in 0..__len { if pos + k < cap { *buf.add(pos + k) = *$s.add(k); } }
7641            pos += __len; count += __len;
7642        }}
7643    }
7644    // Write formatted buffer respecting cap, at current pos
7645    macro_rules! ws_buf {
7646        ($src:expr, $len:expr) => {{
7647            let __len = $len;
7648            for k in 0..__len { if pos + k < cap { *buf.add(pos + k) = *$src.add(k); } }
7649            pos += __len; count += __len;
7650        }}
7651    }
7652    loop {
7653        let c = *fmt.add(i) as u8;
7654        if c == 0 { break; }
7655        if c != b'%' { wc!(c); i += 1; continue; }
7656        i += 1;
7657        // Parse flags
7658        let mut flags: u8 = 0;
7659        loop {
7660            let fc = *fmt.add(i) as u8;
7661            match fc {
7662                b'-' => { flags |= FLAG_MINUS; i += 1; }
7663                b'+' => { flags |= FLAG_PLUS; i += 1; }
7664                b' ' => { flags |= FLAG_SPACE; i += 1; }
7665                b'0' => { flags |= FLAG_ZERO; i += 1; }
7666                b'#' => { flags |= FLAG_HASH; i += 1; }
7667                _ => break,
7668            }
7669        }
7670        // Parse width
7671        let mut width: usize = 0;
7672        if *fmt.add(i) as u8 == b'*' {
7673            width = args.next_arg::<c_int>() as usize; i += 1;
7674        } else {
7675            while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
7676                width = width * 10 + ((*fmt.add(i) as u8) - b'0') as usize; i += 1;
7677            }
7678        }
7679        // Parse precision
7680        let mut precision: i32 = -1;
7681        if *fmt.add(i) as u8 == b'.' {
7682            i += 1;
7683            if *fmt.add(i) as u8 == b'*' {
7684                precision = args.next_arg::<c_int>(); i += 1;
7685            } else {
7686                precision = 0;
7687                while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
7688                    precision = precision * 10 + ((*fmt.add(i) as u8) - b'0') as i32; i += 1;
7689                }
7690            }
7691        }
7692        // Parse length modifier
7693        let len_mod = *fmt.add(i) as u8;
7694        let spec: u8;
7695        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' {
7696            i += 1;
7697            let len_mod2 = *fmt.add(i) as u8;
7698            if (len_mod == b'h' && len_mod2 == b'h') || (len_mod == b'l' && len_mod2 == b'l') {
7699                i += 1;
7700                spec = *fmt.add(i) as u8;
7701                match (len_mod, len_mod2, spec) {
7702                    (b'h', b'h', b'n') => {
7703                        let p = args.next_arg::<*mut c_void>();
7704                        if !p.is_null() { *(p as *mut u8) = count as u8; }
7705                    }
7706                    (b'l', b'l', b'n') => {
7707                        let p = args.next_arg::<*mut c_void>();
7708                        if !p.is_null() { *(p as *mut c_longlong) = count as c_longlong; }
7709                    }
7710                    (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
7711                        let val = args.next_arg::<c_longlong>();
7712                        let neg = val < 0;
7713                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
7714                        let b = format_u64(abs);
7715                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
7716                        let mut fbuf = [0u8; 32];
7717                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
7718                        ws_buf!(fbuf.as_ptr(), len);
7719                    }
7720                    (b'l', b'l', b'u') => {
7721                        let val = args.next_arg::<c_ulonglong>();
7722                        let b = format_u64(val as u64);
7723                        let mut fbuf = [0u8; 32];
7724                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
7725                        ws_buf!(fbuf.as_ptr(), len);
7726                    }
7727                    (b'l', b'l', b'o') => {
7728                        let val = args.next_arg::<c_ulonglong>();
7729                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
7730                        let mut fbuf = [0u8; 32];
7731                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
7732                        ws_buf!(fbuf.as_ptr(), len);
7733                    }
7734                    (b'l', b'l', b'x') | (b'l', b'l', b'X') => {
7735                        let val = args.next_arg::<c_ulonglong>();
7736                        let b = format_hex(val as u64, spec == b'X');
7737                        let pc = if spec == b'X' { b'X' } else { b'x' };
7738                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(pc) } else { None };
7739                        let mut fbuf = [0u8; 32];
7740                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7741                        ws_buf!(fbuf.as_ptr(), len);
7742                    }
7743                    _ => { wc!(b'%'); wc!(len_mod); wc!(len_mod2); wc!(spec); }
7744                }
7745            } else {
7746                spec = len_mod2;
7747                let lm = if (len_mod == b'z' || len_mod == b't') && spec != b'n' { b'l' } else { len_mod };
7748                match (lm, spec) {
7749                    (b'h', b'n') => {
7750                        let p = args.next_arg::<*mut c_void>();
7751                        if !p.is_null() { *(p as *mut u16) = count as u16; }
7752                    }
7753                    (b'l', b'n') => {
7754                        let p = args.next_arg::<*mut c_void>();
7755                        if !p.is_null() { *(p as *mut c_long) = count as c_long; }
7756                    }
7757                    (b'z', b'n') | (b't', b'n') => {
7758                        let p = args.next_arg::<*mut c_void>();
7759                        if !p.is_null() { *(p as *mut usize) = count; }
7760                    }
7761                    (b'j', b'n') => {
7762                        let p = args.next_arg::<*mut c_void>();
7763                        if !p.is_null() { *(p as *mut c_ulonglong) = count as c_ulonglong; }
7764                    }
7765                    (b'l', b'd') | (b'l', b'i') => {
7766                        let val = args.next_arg::<c_long>();
7767                        let neg = val < 0;
7768                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
7769                        let b = format_u64(abs);
7770                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
7771                        let mut fbuf = [0u8; 32];
7772                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
7773                        ws_buf!(fbuf.as_ptr(), len);
7774                    }
7775                    (b'l', b'u') => {
7776                        let val = args.next_arg::<c_ulong>();
7777                        let b = format_u64(val as u64);
7778                        let mut fbuf = [0u8; 32];
7779                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
7780                        ws_buf!(fbuf.as_ptr(), len);
7781                    }
7782                    (b'l', b's') => {
7783                        let p = args.next_arg::<*const wchar_t>();
7784                        if p.is_null() {
7785                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
7786                            let pad = width.saturating_sub(slen);
7787                            if flags & FLAG_MINUS != 0 { ws!(b"(null)".as_ptr(), slen); for _ in 0..pad { wc!(b' '); } }
7788                            else { for _ in 0..pad { wc!(b' '); } ws!(b"(null)".as_ptr(), slen); }
7789                        } else {
7790                            let mut mb = [0u8; 4096];
7791                            let mut n = wide_to_mb(mb.as_mut_ptr(), mb.len(), p);
7792                            if precision >= 0 && (precision as usize) < n { n = precision as usize; }
7793                            let pad = width.saturating_sub(n);
7794                            if flags & FLAG_MINUS != 0 { ws!(mb.as_ptr(), n); for _ in 0..pad { wc!(b' '); } }
7795                            else { for _ in 0..pad { wc!(b' '); } ws!(mb.as_ptr(), n); }
7796                        }
7797                    }
7798                    (b'l', b'c') => {
7799                        let ch = args.next_arg::<c_int>();
7800                        let mut mb = [0u8; 8];
7801                        let mut st: c_uint = 0;
7802                        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, ch, &mut st);
7803                        if n != !0usize { ws!(mb.as_ptr(), n); }
7804                    }
7805                    (b'l', b'x') => {
7806                        let val = args.next_arg::<c_ulong>();
7807                        let b = format_hex(val as u64, false);
7808                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
7809                        let mut fbuf = [0u8; 32];
7810                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7811                        ws_buf!(fbuf.as_ptr(), len);
7812                    }
7813                    (b'l', b'X') => {
7814                        let val = args.next_arg::<c_ulong>();
7815                        let b = format_hex(val as u64, true);
7816                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
7817                        let mut fbuf = [0u8; 32];
7818                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7819                        ws_buf!(fbuf.as_ptr(), len);
7820                    }
7821                    (b'l', b'o') => {
7822                        let val = args.next_arg::<c_ulong>();
7823                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
7824                        let mut fbuf = [0u8; 32];
7825                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
7826                        ws_buf!(fbuf.as_ptr(), len);
7827                    }
7828                    (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
7829                    | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
7830                        let val = args.next_arg::<f64>();
7831                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
7832                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
7833                        let mut fbuf = [0u8; 4224];
7834                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
7835                        let mut wbuf = [0u8; 4224];
7836                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
7837                        ws_buf!(wbuf.as_ptr(), wlen);
7838                    }
7839                    (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
7840                    | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
7841                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
7842                        let val = {
7843                            let lo: u64 = args.next_arg::<u64>();
7844                            let hi: u64 = args.next_arg::<u64>();
7845                            let combined: u128 = ((hi as u128) << 64) | (lo as u128);
7846                            f128::from_bits(combined) as f64
7847                        };
7848                        #[cfg(target_arch = "x86_64")]
7849                        let val = args.next_arg::<f64>();
7850                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
7851                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
7852                        let mut fbuf = [0u8; 4224];
7853                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
7854                        let mut wbuf = [0u8; 4224];
7855                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
7856                        ws_buf!(wbuf.as_ptr(), wlen);
7857                    }
7858                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); }
7859                }
7860            }
7861        } else {
7862            spec = *fmt.add(i) as u8;
7863            match spec {
7864                b's' => {
7865                    let s = args.next_arg::<*const c_char>();
7866                    if s.is_null() {
7867                        let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
7868                        let padded_len = if width > slen { width } else { slen };
7869                        let pad = padded_len - slen;
7870                        if flags & FLAG_MINUS != 0 {
7871                            ws!(b"(null)".as_ptr(), slen);
7872                            for _ in 0..pad { wc!(b' '); }
7873                        } else {
7874                            for _ in 0..pad { wc!(b' '); }
7875                            ws!(b"(null)".as_ptr(), slen);
7876                        }
7877                    } else {
7878                        let full_len = strlen(s as *const c_char);
7879                        let slen = if precision >= 0 { (precision as usize).min(full_len) } else { full_len };
7880                        let padded_len = if width > slen { width } else { slen };
7881                        let pad = padded_len - slen;
7882                        if flags & FLAG_MINUS != 0 {
7883                            ws!(s as *const u8, slen);
7884                            for _ in 0..pad { wc!(b' '); }
7885                        } else {
7886                            for _ in 0..pad { wc!(b' '); }
7887                            ws!(s as *const u8, slen);
7888                        }
7889                    }
7890                }
7891                b'd' | b'i' => {
7892                    let d = args.next_arg::<c_int>();
7893                    let neg = d < 0;
7894                    let abs = if neg { d.wrapping_neg() as u64 } else { d as u64 };
7895                    let b = format_u64(abs);
7896                    let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
7897                    let mut fbuf = [0u8; 32];
7898                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
7899                    ws_buf!(fbuf.as_ptr(), len);
7900                }
7901                b'u' => {
7902                    let u = args.next_arg::<c_uint>();
7903                    let b = format_u64(u as u64);
7904                    let mut fbuf = [0u8; 32];
7905                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
7906                    ws_buf!(fbuf.as_ptr(), len);
7907                }
7908                b'x' => {
7909                    let x = args.next_arg::<c_uint>();
7910                    let b = format_hex(x as u64, false);
7911                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
7912                    let mut fbuf = [0u8; 32];
7913                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7914                    ws_buf!(fbuf.as_ptr(), len);
7915                }
7916                b'X' => {
7917                    let x = args.next_arg::<c_uint>();
7918                    let b = format_hex(x as u64, true);
7919                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
7920                    let mut fbuf = [0u8; 32];
7921                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
7922                    ws_buf!(fbuf.as_ptr(), len);
7923                }
7924                b'o' => {
7925                    let o = args.next_arg::<c_uint>();
7926                    let b = format_octal(o as u64, flags & FLAG_HASH != 0);
7927                    let mut fbuf = [0u8; 32];
7928                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
7929                    ws_buf!(fbuf.as_ptr(), len);
7930                }
7931                b'c' => {
7932                    let ch = args.next_arg::<c_int>();
7933                    if width > 1 {
7934                        let pad = width - 1;
7935                        if flags & FLAG_MINUS != 0 {
7936                            wc!(ch as u8);
7937                            for _ in 0..pad { wc!(b' '); }
7938                        } else {
7939                            for _ in 0..pad { wc!(b' '); }
7940                            wc!(ch as u8);
7941                        }
7942                    } else {
7943                        wc!(ch as u8);
7944                    }
7945                }
7946                b'p' => {
7947                    wc!(b'0'); wc!(b'x');
7948                    let p = args.next_arg::<*const c_void>();
7949                    let b = format_hex(p as u64, false);
7950                    ws!(b.0.as_ptr(), b.1);
7951                }
7952                b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
7953                    let val = args.next_arg::<f64>();
7954                    let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
7955                    let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
7956                    let mut fbuf = [0u8; 4224];
7957                    let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
7958                    let mut wbuf = [0u8; 4224];
7959                    let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
7960                    ws_buf!(wbuf.as_ptr(), wlen);
7961                }
7962                b'%' => { wc!(b'%'); }
7963                b'n' => {
7964                    let p = args.next_arg::<*mut c_void>();
7965                    if !p.is_null() { *(p as *mut c_int) = count as c_int; }
7966                }
7967                _ => { wc!(b'%'); wc!(spec); }
7968            }
7969        }
7970        i += 1;
7971    }
7972    if cap > 0 { let null_pos = if pos < cap { pos } else { cap - 1 }; *buf.add(null_pos) = 0; }
7973    count as c_int
7974}
7975
7976#[no_mangle]
7977pub unsafe extern "C" fn vsprintf(buf: *mut c_char, fmt: *const c_char, mut args: VaList) -> c_int {
7978    format_to_buf(buf as *mut u8, usize::MAX, fmt, &mut args)
7979}
7980
7981#[no_mangle]
7982pub unsafe extern "C" fn vsnprintf(buf: *mut c_char, size: usize, fmt: *const c_char, mut args: VaList) -> c_int {
7983    format_to_buf(buf as *mut u8, size, fmt, &mut args)
7984}
7985
7986#[no_mangle]
7987pub unsafe extern "C" fn sprintf(buf: *mut c_char, fmt: *const c_char, mut args: ...) -> c_int {
7988    format_to_buf(buf as *mut u8, usize::MAX, fmt, &mut args)
7989}
7990
7991#[no_mangle]
7992pub unsafe extern "C" fn snprintf(buf: *mut c_char, size: usize, fmt: *const c_char, mut args: ...) -> c_int {
7993    format_to_buf(buf as *mut u8, size, fmt, &mut args)
7994}
7995
7996#[no_mangle]
7997pub unsafe extern "C" fn vasprintf(strp: *mut *mut c_char, fmt: *const c_char, ap: VaList) -> c_int {
7998    let len = vsnprintf(core::ptr::null_mut(), 0, fmt, ap.clone());
7999    if len < 0 {
8000        *strp = core::ptr::null_mut();
8001        return -1;
8002    }
8003    let p = malloc((len as usize) + 1) as *mut c_char;
8004    if p.is_null() {
8005        *strp = core::ptr::null_mut();
8006        return -1;
8007    }
8008    let ret = vsnprintf(p, (len as usize) + 1, fmt, ap.clone());
8009    if ret < 0 {
8010        free(p as *mut c_void);
8011        *strp = core::ptr::null_mut();
8012        return -1;
8013    }
8014    *strp = p;
8015    ret
8016}
8017
8018#[no_mangle]
8019pub unsafe extern "C" fn asprintf(strp: *mut *mut c_char, fmt: *const c_char, args: ...) -> c_int {
8020    vasprintf(strp, fmt, args)
8021}
8022
8023// ============================================================
8024// scanf / vscanf / fscanf / vfscanf / sscanf / vsscanf
8025// ============================================================
8026
8027unsafe fn skip_ws(p: *const u8) -> *const u8 {
8028    let mut q = p;
8029    while *q == b' ' || *q == b'\t' || *q == b'\n' || *q == b'\r' { q = q.add(1); }
8030    q
8031}
8032
8033#[inline]
8034fn is_ws_byte(c: u8) -> bool {
8035    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == 0x0b || c == 0x0c
8036}
8037
8038// Scan integer with position tracking. Returns (value, is_negative, success).
8039// base: 0=auto, 8=octal, 10=decimal, 16=hex
8040unsafe fn scan_int_val(
8041    buf: *const u8, pos: &mut usize, buf_len: usize, base: u32, width: usize,
8042) -> (u64, bool, bool) {
8043    let start = *pos;
8044    let max = if width > 0 { (start + width).min(buf_len) } else { buf_len };
8045    let neg = if *pos < max && *buf.add(*pos) == b'-' { *pos += 1; true }
8046    else if *pos < max && *buf.add(*pos) == b'+' { *pos += 1; false }
8047    else { false };
8048    if *pos >= max { *pos = start; return (0, false, false); }
8049    let mut base = base;
8050    let mut val: u64 = 0;
8051    // Auto-detect base / handle 0x prefix
8052    if (base == 0 || base == 16) && *pos < max && *buf.add(*pos) == b'0' {
8053        *pos += 1;
8054        if *pos < max && (*buf.add(*pos) == b'x' || *buf.add(*pos) == b'X') {
8055            *pos += 1;
8056            if *pos < max {
8057                if let Some(d) = hex_val(*buf.add(*pos)) {
8058                    val = d as u64; *pos += 1;
8059                    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; } }
8060                    return (val, neg, true);
8061                }
8062            }
8063            return (0, neg, false);
8064        } else if base == 0 {
8065            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; } }
8066            return (val, neg, true);
8067        } else {
8068            // base 16 with a leading zero ("00000000"): the zero is part of
8069            // the number, not a prefix that ends the conversion.
8070            while *pos < max {
8071                if let Some(d) = hex_val(*buf.add(*pos)) {
8072                    val = val.wrapping_mul(16).wrapping_add(d as u64);
8073                    *pos += 1;
8074                } else {
8075                    break;
8076                }
8077            }
8078            return (val, neg, true);
8079        }
8080    }
8081    if base == 0 { base = 10; }
8082    let mut found = false;
8083    while *pos < max {
8084        let c = *buf.add(*pos);
8085        let d: Option<u64> = match base {
8086            8 => if c >= b'0' && c <= b'7' { Some((c - b'0') as u64) } else { None },
8087            10 => if c >= b'0' && c <= b'9' { Some((c - b'0') as u64) } else { None },
8088            16 => hex_val(c).map(|v| v as u64),
8089            _ => None,
8090        };
8091        match d { Some(digit) => { val = val.wrapping_mul(base as u64).wrapping_add(digit); *pos += 1; found = true; } None => break }
8092    }
8093    if !found { *pos = start; return (0, false, false); }
8094    (val, neg, true)
8095}
8096
8097// Scan float with position tracking. Returns (value, success).
8098unsafe fn scan_float_val(
8099    buf: *const u8, pos: &mut usize, buf_len: usize, width: usize,
8100) -> (f64, bool) {
8101    let start = *pos;
8102    let max = if width > 0 { (start + width).min(buf_len) } else { buf_len };
8103    let neg = if *pos < max && *buf.add(*pos) == b'-' { *pos += 1; true }
8104    else if *pos < max && *buf.add(*pos) == b'+' { *pos += 1; false }
8105    else { false };
8106    // inf/nan
8107    if *pos + 2 < max {
8108        let (c0,c1,c2) = (*buf.add(*pos), *buf.add(*pos+1), *buf.add(*pos+2));
8109        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); }
8110        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); }
8111    }
8112    // hex float
8113    if *pos+1 < max && *buf.add(*pos)==b'0' && (*buf.add(*pos+1)==b'x'||*buf.add(*pos+1)==b'X') {
8114        *pos += 2;
8115        let mut val: f64 = 0.0; let mut found = false; let mut frac_scale = 1.0f64; let mut in_frac = false;
8116        while *pos < max {
8117            if let Some(d) = hex_val(*buf.add(*pos)) {
8118                if in_frac { frac_scale /= 16.0; val += d as f64 * frac_scale; } else { val = val * 16.0 + d as f64; }
8119                *pos += 1; found = true;
8120            } else if *buf.add(*pos)==b'.' && !in_frac { in_frac = true; *pos += 1; } else { break; }
8121        }
8122        if !found { *pos = start; return (0.0, false); }
8123        // p exponent
8124        if *pos < max && (*buf.add(*pos)==b'p'||*buf.add(*pos)==b'P') {
8125            *pos += 1;
8126            let mut eneg = false;
8127            if *pos<max && *buf.add(*pos)==b'-' { eneg=true; *pos+=1; }
8128            else if *pos<max && *buf.add(*pos)==b'+' { *pos+=1; }
8129            let mut ev: i32 = 0; let mut ef = false;
8130            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; }
8131            if !ef { return (0.0, false); }
8132            if eneg { ev = -ev; }
8133            val *= libm::pow(2.0, ev as f64);
8134        }
8135        return (if neg{-val}else{val}, true);
8136    }
8137    let token_start = start;
8138    let mut i = start;
8139    let mut saw_digit = false;
8140    let mut saw_dot = false;
8141    let mut saw_exp = false;
8142    let mut first = true;
8143    while i < max {
8144        let c = *buf.add(i);
8145        if (c == b'+' || c == b'-') && first {
8146            i += 1; first = false; continue;
8147        }
8148        if c >= b'0' && c <= b'9' {
8149            saw_digit = true; i += 1; first = false; continue;
8150        }
8151        if c == b'.' && !saw_dot && !saw_exp {
8152            saw_dot = true; i += 1; first = false; continue;
8153        }
8154        if (c == b'e' || c == b'E') && !saw_exp && saw_digit {
8155            saw_exp = true; i += 1; first = true; continue;
8156        }
8157        break;
8158    }
8159    if !saw_digit { return (0.0, false); }
8160    let s = core::str::from_utf8_unchecked(core::slice::from_raw_parts(buf.add(token_start), i - token_start));
8161    match <f64 as core::str::FromStr>::from_str(s) {
8162        Ok(v) => { *pos = i; return (v, true); }
8163        Err(_) => { return (0.0, false); }
8164    }
8165}
8166
8167// Comprehensive scanf parser with position tracking.
8168// consumed: if non-null, stores number of bytes consumed from buf.
8169/// Store a scanned integer with the width selected by the length modifier.
8170/// Without this, `%ld`/`%lu` silently truncate to 32 bits.
8171unsafe fn store_scan_int(dest: *mut c_void, len_mod: u8, val: u64, neg: bool) {
8172    let sv: i64 = if neg { (val as i64).wrapping_neg() } else { val as i64 };
8173    match len_mod {
8174        2 => *(dest as *mut i8) = sv as i8,
8175        1 => *(dest as *mut i16) = sv as i16,
8176        3 | 4 => *(dest as *mut i64) = sv,
8177        _ => *(dest as *mut i32) = sv as i32,
8178    }
8179}
8180
8181unsafe fn do_vsscanf(
8182    buf: *const u8, buf_len: usize, fmt: *const c_char, args: &mut VaList<'_>, consumed: *mut usize,
8183) -> c_int {
8184    let mut p = 0usize;
8185    let mut fi = 0usize;
8186    let mut assigned = 0i32;
8187    let mut input_eof = false;
8188    loop {
8189        let fc = *fmt.add(fi) as u8;
8190        if fc == 0 { break; }
8191        if is_ws_byte(fc) {
8192            while is_ws_byte(*fmt.add(fi) as u8) { fi += 1; }
8193            while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8194            continue;
8195        }
8196        if fc != b'%' {
8197            if p >= buf_len { input_eof = true; break; }
8198            if *buf.add(p) != fc { break; }
8199            p += 1; fi += 1; continue;
8200        }
8201        fi += 1;
8202        // %%
8203        if *fmt.add(fi) as u8 == b'%' {
8204            if p >= buf_len { input_eof = true; break; }
8205            if *buf.add(p) != b'%' { break; }
8206            p += 1; fi += 1; continue;
8207        }
8208        let suppress = if *fmt.add(fi) as u8 == b'*' { fi += 1; true } else { false };
8209        let mut width: usize = 0;
8210        while (*fmt.add(fi) as u8) >= b'0' && (*fmt.add(fi) as u8) <= b'9' {
8211            width = width * 10 + ((*fmt.add(fi) as u8) - b'0') as usize; fi += 1;
8212        }
8213        if *fmt.add(fi) as u8 == b'm' { fi += 1; }
8214        let mut len_mod = 0u8;
8215        match *fmt.add(fi) as u8 {
8216            b'h' => { fi += 1; if *fmt.add(fi) as u8 == b'h' { fi += 1; len_mod = 2; } else { len_mod = 1; } }
8217            b'l' => { fi += 1; if *fmt.add(fi) as u8 == b'l' { fi += 1; len_mod = 4; } else { len_mod = 3; } }
8218            b'j' => { fi += 1; len_mod = 4; }
8219            b'z' | b't' => { fi += 1; len_mod = 3; }
8220            b'L' => { fi += 1; len_mod = 5; }
8221            _ => {}
8222        }
8223        let spec = *fmt.add(fi) as u8;
8224        let (real_spec, _real_len) = if spec==b'C' {(b'c',3u8)} else if spec==b'S' {(b's',3u8)} else {(spec,len_mod)};
8225        match real_spec {
8226            b'n' => {
8227                if !suppress {
8228                    let out = args.next_arg::<*mut c_void>();
8229                    if !out.is_null() {
8230                        match len_mod {
8231                            1 => *(out as *mut i16) = p as i16,
8232                            2 => *(out as *mut i8) = p as i8,
8233                            3 | 4 => *(out as *mut i64) = p as i64,
8234                            _ => *(out as *mut c_int) = p as c_int,
8235                        }
8236                    }
8237                }
8238            }
8239            b'd' | b'u' => {
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 = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8243                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 10, width);
8244                if !ok { break; }
8245                if let Some(out) = dest { if !out.is_null() {
8246                    store_scan_int(out, len_mod, val, neg);
8247                }}
8248                if !suppress { assigned += 1; }
8249            }
8250            b'i' => {
8251                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8252                if p >= buf_len { input_eof = true; break; }
8253                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8254                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 0, width);
8255                if !ok { break; }
8256                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8257                if !suppress { assigned += 1; }
8258            }
8259            b'o' => {
8260                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8261                if p >= buf_len { input_eof = true; break; }
8262                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8263                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 8, width);
8264                if !ok { break; }
8265                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8266                if !suppress { assigned += 1; }
8267            }
8268            b'x' | b'X' => {
8269                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8270                if p >= buf_len { input_eof = true; break; }
8271                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8272                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 16, width);
8273                if !ok { break; }
8274                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8275                if !suppress { assigned += 1; }
8276            }
8277            b'p' => {
8278                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8279                if p >= buf_len { input_eof = true; break; }
8280                let dest = if !suppress { Some(args.next_arg::<*mut *mut c_void>()) } else { None };
8281                let (val, _, ok) = scan_int_val(buf, &mut p, buf_len, 16, width);
8282                if !ok { break; }
8283                if let Some(out) = dest { if !out.is_null() { *out = val as usize as *mut c_void; } }
8284                if !suppress { assigned += 1; }
8285            }
8286            b'a' | b'e' | b'f' | b'g' | b'A' | b'E' | b'F' | b'G' => {
8287                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8288                if p >= buf_len { input_eof = true; break; }
8289                let (val, ok) = scan_float_val(buf, &mut p, buf_len, width);
8290                if !ok { break; }
8291                if !suppress {
8292                    if _real_len == 3 {
8293                        let out = args.next_arg::<*mut f64>(); if !out.is_null() { *out = val; }
8294                    } else if _real_len == 5 {
8295                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
8296                        { let out = args.next_arg::<*mut f128>(); if !out.is_null() { *out = val as f128; } }
8297                        #[cfg(target_arch = "x86_64")]
8298                        { let out = args.next_arg::<*mut f64>(); if !out.is_null() { *out = val; } }
8299                    } else {
8300                        let out = args.next_arg::<*mut f32>(); if !out.is_null() { *out = val as f32; }
8301                    }
8302                }
8303                if !suppress { assigned += 1; }
8304            }
8305            b'c' => {
8306                let w = if width > 0 { width } else { 1 };
8307                if p >= buf_len { input_eof = true; break; }
8308                let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8309                let start_p = p;
8310                let mut j = 0usize;
8311                while j < w && p < buf_len {
8312                    if !dest_ptr.is_null() { *dest_ptr.add(j) = *buf.add(p) as c_char; }
8313                    p += 1; j += 1;
8314                }
8315                if j != w { p = start_p; input_eof = true; break; }
8316                if !suppress { assigned += 1; }
8317            }
8318            b's' => {
8319                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8320                if p >= buf_len { input_eof = true; break; }
8321                let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8322                let w = if width > 0 { width } else { usize::MAX };
8323                let mut j = 0usize;
8324                while p < buf_len && *buf.add(p) != 0 && !is_ws_byte(*buf.add(p)) && j < w {
8325                    if !dest_ptr.is_null() { *dest_ptr.add(j) = *buf.add(p) as c_char; }
8326                    p += 1; j += 1;
8327                }
8328                if j == 0 { break; }
8329                if !dest_ptr.is_null() { *dest_ptr.add(j) = 0; }
8330                if !suppress { assigned += 1; }
8331            }
8332            b'[' => {
8333                fi += 1;
8334                let negate = if *fmt.add(fi) as u8 == b'^' { fi += 1; true } else { false };
8335                let mut charset = [0u8; 256];
8336                let mut prev: Option<u8> = None;
8337                if *fmt.add(fi) as u8 == b']' {
8338                    charset[b']' as usize] = 1;
8339                    prev = Some(b']');
8340                    fi += 1;
8341                }
8342                loop {
8343                    let c = *fmt.add(fi) as u8;
8344                    if c == b']' || c == 0 { break; }
8345                    // "a-z" is a range; a '-' next to ']' or at the start/end
8346                    // of the set is a literal.
8347                    if c == b'-' && prev.is_some() {
8348                        let hi = *fmt.add(fi + 1) as u8;
8349                        if hi != b']' && hi != 0 {
8350                            let lo = prev.unwrap();
8351                            let mut k = lo;
8352                            while k <= hi {
8353                                charset[k as usize] = 1;
8354                                if k == 255 { break; }
8355                                k += 1;
8356                            }
8357                            prev = None;
8358                            fi += 2;
8359                            continue;
8360                        }
8361                    }
8362                    charset[c as usize] = 1;
8363                    prev = Some(c);
8364                    fi += 1;
8365                }
8366                if *fmt.add(fi) as u8 == b']' { fi += 1; }
8367                fi -= 1; // common fi += 1 will advance past the closing ]
8368                if p >= buf_len { input_eof = true; break; }
8369                let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8370                let w = if width > 0 { width } else { usize::MAX };
8371                let mut j = 0usize;
8372                while p < buf_len && *buf.add(p) != 0 && j < w {
8373                    let c = *buf.add(p);
8374                    let in_set = charset[c as usize] != 0;
8375                    if negate { if in_set { break; } } else { if !in_set { break; } }
8376                    if !dest_ptr.is_null() { *dest_ptr.add(j) = c as c_char; }
8377                    p += 1; j += 1;
8378                }
8379                if j == 0 { break; }
8380                if !dest_ptr.is_null() { *dest_ptr.add(j) = 0; }
8381                if !suppress { assigned += 1; }
8382            }
8383            _ => break,
8384        }
8385        fi += 1;
8386    }
8387    if !consumed.is_null() { *consumed = p; }
8388    if assigned == 0 && input_eof { -1 } else { assigned }
8389}
8390
8391unsafe fn vsscanf_inner(buf: *const u8, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
8392    let len = strlen(buf as *const c_char);
8393    do_vsscanf(buf, len, fmt, args, core::ptr::null_mut())
8394}
8395
8396#[no_mangle]
8397pub unsafe extern "C" fn vsscanf(buf: *const c_char, fmt: *const c_char, mut args: VaList) -> c_int {
8398    vsscanf_inner(buf as *const u8, fmt, &mut args)
8399}
8400
8401#[no_mangle]
8402pub unsafe extern "C" fn vfscanf(stream: *mut FILE, fmt: *const c_char, mut args: VaList) -> c_int {
8403    let f = &mut *stream;
8404    let start_ungotten_count = f.ungotten_count as usize;
8405    let ungotten_saved = f.ungotten;
8406    let sfunc = f.seek_fn;
8407    // Logical position, not the raw fd offset: fgetc may have read ahead.
8408    let start_pos = if sfunc.is_some() { ftello(stream) } else { -1 };
8409
8410    let mut line = [0u8; 4096];
8411    let mut pos = 0usize;
8412
8413    if start_pos >= 0 {
8414        // Seekable: read via fgetc until \n or EOF (existing behavior)
8415        while pos < line.len() - 1 {
8416            let c = fgetc(stream);
8417            if c == -1 { break; }
8418            line[pos] = c as u8;
8419            pos += 1;
8420            if c == b'\n' as c_int { break; }
8421        }
8422    } else {
8423        // Non-seekable (pipe/socket): drain pushback, then read all available
8424        // data non-blocking so we don't stop at \n boundaries.
8425
8426        // 1. Drain ungotten bytes (LIFO order)
8427        while f.ungotten_count > 0 && pos < line.len() - 1 {
8428            f.ungotten_count -= 1;
8429            line[pos] = f.ungotten[f.ungotten_count as usize] as u8;
8430            pos += 1;
8431        }
8432        // 2. Drain rpos/rend pushback buffer
8433        while !f.rpos.is_null() && f.rpos < f.rend && pos < line.len() - 1 {
8434            line[pos] = *f.rpos;
8435            f.rpos = f.rpos.add(1);
8436            pos += 1;
8437        }
8438        // 3. Wait for the first byte (blocking), then drain whatever else is
8439        // available without waiting. A pure non-blocking read would race with
8440        // a producer such as popen() that has not written yet.
8441        let fd = f.fd;
8442        if pos == 0 {
8443            let n = sys_read(fd as i64, line.as_mut_ptr(), 1);
8444            if n == 1 { pos = 1; }
8445        }
8446        let old_flags = sys_fcntl(fd, F_GETFL, 0);
8447        if old_flags >= 0 {
8448            let _ = sys_fcntl(fd, F_SETFL, old_flags | O_NONBLOCK as i64);
8449        }
8450        while pos < line.len() - 1 {
8451            let n = sys_read(fd as i64, line.as_mut_ptr().add(pos), line.len() - 1 - pos);
8452            if n <= 0 { break; }
8453            pos += n as usize;
8454        }
8455        if old_flags >= 0 {
8456            let _ = sys_fcntl(fd, F_SETFL, old_flags);
8457        }
8458        // Clear flags that the failed non-blocking read may have set
8459        f._eof = 0;
8460        f._err = 0;
8461        f.flags &= !(F_EOF | F_ERR);
8462    }
8463
8464    line[pos] = 0;
8465    if pos == 0 { return 0; }
8466
8467    let mut consumed = 0usize;
8468    let assigned = do_vsscanf(line.as_ptr(), pos, fmt, &mut args, &mut consumed);
8469
8470    if start_pos >= 0 {
8471        // Seek back to the logical position just past the consumed bytes and
8472        // restore any ungetc pushback the scan did not consume.
8473        let remaining = start_ungotten_count.saturating_sub(consumed);
8474        // The restored ungetc bytes will be subtracted by ftello(), so the
8475        // raw fd offset must include them.
8476        let target = start_pos + consumed as i64 + remaining as i64;
8477        if let Some(sfunc) = sfunc {
8478            sfunc(stream, target, SEEK_SET);
8479        }
8480        f.rpos = core::ptr::null_mut();
8481        f.rend = core::ptr::null_mut();
8482        if consumed < pos { f._eof = 0; }
8483        f.ungotten_count = 0;
8484        for i in 0..remaining {
8485            f.ungotten[f.ungotten_count as usize] = ungotten_saved[i];
8486            f.ungotten_count += 1;
8487        }
8488    } else {
8489        // Non-seekable: push back unconsumed bytes into FILE read buffer
8490        let unconsumed = pos.saturating_sub(consumed);
8491        if unconsumed > 0 && !f.buf.is_null() {
8492            let copy_count = core::cmp::min(unconsumed, f.buf_size);
8493            core::ptr::copy(
8494                line.as_ptr().add(consumed),
8495                f.buf,
8496                copy_count,
8497            );
8498            f.rpos = f.buf;
8499            f.rend = f.buf.add(copy_count);
8500        }
8501        f.ungotten_count = 0;
8502        f._eof = 0;
8503        f.flags &= !F_EOF;
8504    }
8505    assigned
8506}
8507
8508#[no_mangle]
8509pub unsafe extern "C" fn vscanf(fmt: *const c_char, args: VaList) -> c_int {
8510    vfscanf(stdin, fmt, args)
8511}
8512
8513#[no_mangle]
8514pub unsafe extern "C" fn sscanf(buf: *const c_char, fmt: *const c_char, mut args: ...) -> c_int {
8515    vsscanf_inner(buf as *const u8, fmt, &mut args)
8516}
8517
8518#[no_mangle]
8519pub unsafe extern "C" fn fscanf(stream: *mut FILE, fmt: *const c_char, args: ...) -> c_int {
8520    vfscanf(stream, fmt, args)
8521}
8522
8523#[no_mangle]
8524pub unsafe extern "C" fn scanf(fmt: *const c_char, args: ...) -> c_int {
8525    vfscanf(stdin, fmt, args)
8526}
8527
8528// ============================================================
8529// getdelim / getline
8530// ============================================================
8531
8532#[no_mangle]
8533pub unsafe extern "C" fn getdelim(
8534    lineptr: *mut *mut c_char, n: *mut usize, delim: c_int, stream: *mut FILE,
8535) -> isize {
8536    if lineptr.is_null() || n.is_null() { return -1; }
8537    let mut cap = *n;
8538    let mut buf = *lineptr;
8539    if buf.is_null() || cap == 0 {
8540        cap = 128;
8541        buf = realloc(buf as *mut c_void, cap) as *mut c_char;
8542        if buf.is_null() { return -1; }
8543        *lineptr = buf;
8544        *n = cap;
8545    }
8546    let mut len = 0usize;
8547    loop {
8548        let c = fgetc(stream);
8549        if c == -1 { if len == 0 { return -1; } break; }
8550        if len + 1 >= cap {
8551            let new_cap = cap.wrapping_mul(2);
8552            let new_buf = realloc(buf as *mut c_void, new_cap) as *mut c_char;
8553            if new_buf.is_null() { return -1; }
8554            buf = new_buf; cap = new_cap;
8555            *lineptr = buf; *n = cap;
8556        }
8557        *buf.add(len) = c as c_char;
8558        len += 1;
8559        if c == delim { break; }
8560    }
8561    *buf.add(len) = 0;
8562    len as isize
8563}
8564
8565#[no_mangle]
8566pub unsafe extern "C" fn getline(lineptr: *mut *mut c_char, n: *mut usize, stream: *mut FILE) -> isize {
8567    getdelim(lineptr, n, b'\n' as c_int, stream)
8568}
8569
8570// ============================================================
8571// popen / pclose
8572// ============================================================
8573
8574#[no_mangle]
8575pub unsafe extern "C" fn popen(cmd: *const c_char, mode: *const c_char) -> *mut FILE {
8576    if cmd.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
8577    let m = *mode;
8578    if m != b'r' as c_char && m != b'w' as c_char { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
8579    let mut p: [c_int; 2] = [0; 2];
8580    if sys_pipe2(p.as_mut_ptr(), O_CLOEXEC) < 0 { return core::ptr::null_mut(); }
8581    let op = if m == b'r' as c_char { 0 } else { 1 };
8582    let child_fd = p[1 - op];
8583    let f = fdopen(p[op], mode);
8584    if f.is_null() { sys_close(p[0] as i64); sys_close(p[1] as i64); return core::ptr::null_mut(); }
8585    let pid = sys_fork();
8586    if pid < 0 { fclose(f); sys_close(child_fd as i64); return core::ptr::null_mut(); }
8587    if pid == 0 {
8588        sys_close(p[op] as i64);
8589        if child_fd != (1 - op) as c_int { sys_dup3(child_fd, (1 - op) as c_int, 0); sys_close(child_fd as i64); }
8590        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
8591        let argv = [b"sh\0".as_ptr() as *const c_char, b"-c\0".as_ptr() as *const c_char, cmd, core::ptr::null()];
8592        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
8593        _exit(127);
8594    }
8595    sys_close(child_fd as i64);
8596    (*f).pipe_pid = pid as c_int;
8597    f
8598}
8599
8600#[no_mangle]
8601pub unsafe extern "C" fn pclose(f: *mut FILE) -> c_int {
8602    let pid = (*f).pipe_pid;
8603    let r = fclose(f);
8604    if pid <= 0 { return -1; }
8605    let mut status: c_int = 0;
8606    let mut w: c_int;
8607    loop {
8608        w = waitpid(pid, &mut status, 0);
8609        if w >= 0 || ERRNO!() != EINTR_VAL { break; }
8610    }
8611    if w < 0 || r != 0 { return -1; }
8612    status
8613}
8614
8615// ============================================================
8616// tmpfile / tmpnam / remove / rename
8617// ============================================================
8618
8619const L_TMPNAM: usize = 20;
8620static mut TMPNAM_COUNTER: c_uint = 0;
8621
8622unsafe fn fill_tmpname(out: *mut c_char, seed: c_uint) {
8623    let prefix = b"/tmp/tmp\0";
8624    let mut k = 0;
8625    while k < prefix.len() - 1 { *out.add(k) = prefix[k] as c_char; k += 1; }
8626    let (buf, len) = format_hex(seed as u64, false);
8627    for j in 0..len.min(L_TMPNAM - k - 1) { *out.add(k + j) = buf[j] as c_char; k += 1; }
8628    *out.add(k) = 0;
8629}
8630
8631#[no_mangle]
8632pub unsafe extern "C" fn tmpfile() -> *mut FILE {
8633    let mut name = [0u8; L_TMPNAM];
8634    let mut ctr: c_uint = 0;
8635    loop {
8636        ctr = ctr.wrapping_add(1);
8637        let mut ts: timespec = core::mem::zeroed();
8638        let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
8639        let seed = (ts.tv_nsec as c_uint).wrapping_add(ctr);
8640        fill_tmpname(name.as_mut_ptr() as *mut c_char, seed);
8641        let fd = sys_open(name.as_ptr(), (O_RDWR | O_CREAT | O_EXCL) as i64, 0o600);
8642        if fd >= 0 {
8643            sys_unlinkat(AT_FDCWD, name.as_ptr(), 0);
8644            let f = fdopen(fd as c_int, b"w+\0".as_ptr() as *const c_char);
8645            if f.is_null() { sys_close(fd); }
8646            return f;
8647        }
8648        if ctr > 100 { return core::ptr::null_mut(); }
8649    }
8650}
8651
8652#[no_mangle]
8653pub unsafe extern "C" fn tmpnam(s: *mut c_char) -> *mut c_char {
8654    static mut BUF: [c_char; L_TMPNAM] = [0; L_TMPNAM];
8655    let out = if s.is_null() { core::ptr::addr_of_mut!(BUF) as *mut c_char } else { s };
8656    TMPNAM_COUNTER = TMPNAM_COUNTER.wrapping_add(1);
8657    let mut ts: timespec = core::mem::zeroed();
8658    let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
8659    let seed = (ts.tv_nsec as c_uint).wrapping_add(TMPNAM_COUNTER);
8660    fill_tmpname(out, seed);
8661    out
8662}
8663
8664#[no_mangle]
8665pub unsafe extern "C" fn remove(path: *const c_char) -> c_int {
8666    if path.is_null() { ERRNO!() = EINVAL; return -1; }
8667    let r = sys_unlinkat(AT_FDCWD, path as *const u8, 0);
8668    if r == 0 {
8669        return 0;
8670    }
8671    // POSIX remove() also removes directories; musl falls back to rmdir only
8672    // when unlink reports EISDIR.
8673    if (-r) as c_int == 21 {
8674        return rmdir(path);
8675    }
8676    ERRNO!() = (-r) as c_int;
8677    -1
8678}
8679
8680#[no_mangle]
8681pub unsafe extern "C" fn rename(old: *const c_char, new_: *const c_char) -> c_int {
8682    if old.is_null() || new_.is_null() { ERRNO!() = EINVAL; return -1; }
8683    let r = sys_renameat2(AT_FDCWD, old as *const u8, AT_FDCWD, new_ as *const u8, 0);
8684    if r == 0 { 0 } else { ERRNO!() = (-r) as c_int; -1 }
8685}
8686
8687// ============================================================
8688// Allocator basics
8689// ============================================================
8690
8691const MMAP_FAILED: *mut u8 = !0usize as *mut u8;
8692const PAGE: usize = 4096;
8693
8694// ============================================================
8695// Process: exit / _exit / _Exit
8696// ============================================================
8697
8698#[no_mangle]
8699pub unsafe extern "C" fn _exit(code: c_int) -> ! {
8700    sys_exit_group(code)
8701}
8702
8703#[inline]
8704unsafe fn sys_exit_group(code: c_int) -> ! {
8705    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT_GROUP, code as i64)
8706}
8707
8708#[inline]
8709unsafe fn sys_exit_thread(code: c_int) -> ! {
8710    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT, code as i64)
8711}
8712
8713#[no_mangle]
8714pub unsafe extern "C" fn _Exit(code: c_int) -> ! {
8715    _exit(code);
8716}
8717
8718#[no_mangle]
8719pub unsafe extern "C" fn exit(code: c_int) -> ! {
8720    fflush(core::ptr::null_mut());
8721    __funcs_on_exit();
8722    _exit(code);
8723}
8724
8725#[no_mangle]
8726pub unsafe extern "C" fn abort() -> ! {
8727    raise(6); // SIGABRT
8728    _exit(128 + 6);
8729}
8730
8731// aarch64 GCC accesses the stack canary via the global __stack_chk_guard
8732// symbol (GOT-based for PIE). Export it so the dynamic linker can resolve it.
8733#[no_mangle]
8734pub static mut __stack_chk_guard: usize = 0;
8735
8736#[no_mangle]
8737pub unsafe extern "C" fn __stack_chk_fail() -> ! {
8738    const MSG: &[u8] = b"*** stack smashing detected ***: terminated\n";
8739    let _ = sys_write(2, MSG.as_ptr(), MSG.len());
8740    abort();
8741}
8742
8743#[no_mangle]
8744pub unsafe extern "C" fn __stack_chk_fail_local() -> ! {
8745    __stack_chk_fail()
8746}
8747
8748// ============================================================
8749// qsort / qsort_r (smoothsort, O(1) aux, adaptive)
8750// ============================================================
8751
8752type CmpRfn = unsafe extern "C" fn(*const c_void, *const c_void, *mut c_void) -> c_int;
8753
8754const AR_LEN: usize = 16 * core::mem::size_of::<usize>();
8755const AR_MASK: usize = AR_LEN - 1;
8756
8757unsafe fn qsort_pntz(p: &[usize; 2]) -> i32 {
8758    if p[0] != 1 {
8759        p[0].wrapping_sub(1).trailing_zeros() as i32
8760    } else if p[1] != 0 {
8761        (8 * core::mem::size_of::<usize>()) as i32 + p[1].trailing_zeros() as i32
8762    } else {
8763        0
8764    }
8765}
8766
8767unsafe fn qsort_cycle(width: usize, ar: &mut [*mut u8; AR_LEN], n: usize) {
8768    if n < 2 { return; }
8769    let mut tmp = [0u8; 256];
8770    ar[n] = tmp.as_mut_ptr();
8771    let mut w = width;
8772    while w > 0 {
8773        let l = if 256 < w { 256 } else { w };
8774        core::ptr::copy_nonoverlapping(ar[0], ar[n], l);
8775        for i in 0..n {
8776            core::ptr::copy_nonoverlapping(ar[i + 1], ar[i], l);
8777            ar[i] = ar[i].add(l);
8778        }
8779        w -= l;
8780    }
8781}
8782
8783unsafe fn qsort_shl(p: &mut [usize; 2], n: i32) {
8784    let bits = (8 * core::mem::size_of::<usize>()) as i32;
8785    if n >= bits {
8786        p[1] = p[0];
8787        p[0] = 0;
8788        let n = n - bits;
8789        if n == 0 { return; }
8790    }
8791    p[1] = (p[1] << n) | (p[0] >> (bits - n));
8792    p[0] <<= n;
8793}
8794
8795unsafe fn qsort_shr(p: &mut [usize; 2], n: i32) {
8796    let bits = (8 * core::mem::size_of::<usize>()) as i32;
8797    if n >= bits {
8798        p[0] = p[1];
8799        p[1] = 0;
8800        let n = n - bits;
8801        if n == 0 { return; }
8802    }
8803    p[0] = (p[0] >> n) | (p[1] << (bits - n));
8804    p[1] >>= n;
8805}
8806
8807unsafe fn qsort_sift(
8808    head: *mut u8, width: usize,
8809    cmp: CmpRfn, arg: *mut c_void,
8810    pshift: i32, lp: &[usize],
8811) {
8812    let mut ar: [*mut u8; AR_LEN] = [core::ptr::null_mut(); AR_LEN];
8813    ar[0] = head;
8814    let mut i = 1usize;
8815    let mut h = head;
8816    let mut ps = pshift;
8817
8818    while ps > 1 {
8819        let rt = h.sub(width);
8820        let lf = h.sub(width + lp[(ps - 2) as usize]);
8821
8822        if cmp(ar[0] as *const c_void, lf as *const c_void, arg) >= 0
8823            && cmp(ar[0] as *const c_void, rt as *const c_void, arg) >= 0
8824        {
8825            break;
8826        }
8827        if cmp(lf as *const c_void, rt as *const c_void, arg) >= 0 {
8828            ar[i & AR_MASK] = lf;
8829            i += 1;
8830            h = lf;
8831            ps -= 1;
8832        } else {
8833            ar[i & AR_MASK] = rt;
8834            i += 1;
8835            h = rt;
8836            ps -= 2;
8837        }
8838    }
8839    qsort_cycle(width, &mut ar, i & AR_MASK);
8840}
8841
8842unsafe fn qsort_trinkle(
8843    head: *mut u8, width: usize,
8844    cmp: CmpRfn, arg: *mut c_void,
8845    pp: &[usize; 2], pshift: i32, trusty: i32,
8846    lp: &[usize],
8847) {
8848    let mut ar: [*mut u8; AR_LEN] = [core::ptr::null_mut(); AR_LEN];
8849    let mut p = *pp;
8850    ar[0] = head;
8851    let mut i = 1usize;
8852    let mut h = head;
8853    let mut ps = pshift;
8854    let mut t = trusty;
8855
8856    while p[0] != 1 || p[1] != 0 {
8857        let stepson = h.sub(lp[ps as usize]);
8858        if cmp(stepson as *const c_void, ar[0] as *const c_void, arg) <= 0 {
8859            break;
8860        }
8861        if t == 0 && ps > 1 {
8862            let rt = h.sub(width);
8863            let lf = h.sub(width + lp[(ps - 2) as usize]);
8864            if cmp(rt as *const c_void, stepson as *const c_void, arg) >= 0
8865                || cmp(lf as *const c_void, stepson as *const c_void, arg) >= 0
8866            {
8867                break;
8868            }
8869        }
8870
8871        ar[i & AR_MASK] = stepson;
8872        i += 1;
8873        h = stepson;
8874        let trail = qsort_pntz(&p);
8875        qsort_shr(&mut p, trail);
8876        ps += trail;
8877        t = 0;
8878    }
8879    if t == 0 {
8880        qsort_cycle(width, &mut ar, i & AR_MASK);
8881        qsort_sift(h, width, cmp, arg, ps, lp);
8882    }
8883}
8884
8885#[no_mangle]
8886pub unsafe extern "C" fn __qsort_r(
8887    base: *mut c_void,
8888    nel: usize,
8889    width: usize,
8890    cmp: CmpRfn,
8891    arg: *mut c_void,
8892) {
8893    let size = width * nel;
8894    if size == 0 { return; }
8895
8896    let mut lp = [0usize; 96];
8897    lp[0] = width;
8898    lp[1] = width;
8899    let mut li = 2;
8900    while {
8901        lp[li] = lp[li - 2] + lp[li - 1] + width;
8902        lp[li] < size
8903    } {
8904        li += 1;
8905    }
8906
8907    let mut head = base as *mut u8;
8908    let high = head.add(size - width);
8909    let mut p: [usize; 2] = [1, 0];
8910    let mut pshift: i32 = 1;
8911
8912    while head < high {
8913        if (p[0] & 3) == 3 {
8914            qsort_sift(head, width, cmp, arg, pshift, &lp);
8915            qsort_shr(&mut p, 2);
8916            pshift += 2;
8917        } else {
8918            if lp[(pshift - 1) as usize] >= (high as usize) - (head as usize) {
8919                qsort_trinkle(head, width, cmp, arg, &p, pshift, 0, &lp);
8920            } else {
8921                qsort_sift(head, width, cmp, arg, pshift, &lp);
8922            }
8923
8924            if pshift == 1 {
8925                qsort_shl(&mut p, 1);
8926                pshift = 0;
8927            } else {
8928                qsort_shl(&mut p, pshift - 1);
8929                pshift = 1;
8930            }
8931        }
8932
8933        p[0] |= 1;
8934        head = head.add(width);
8935    }
8936
8937    qsort_trinkle(head, width, cmp, arg, &p, pshift, 0, &lp);
8938
8939    while pshift != 1 || p[0] != 1 || p[1] != 0 {
8940        if pshift <= 1 {
8941            let trail = qsort_pntz(&p);
8942            qsort_shr(&mut p, trail);
8943            pshift += trail;
8944        } else {
8945            qsort_shl(&mut p, 2);
8946            pshift -= 2;
8947            p[0] ^= 7;
8948            qsort_shr(&mut p, 1);
8949            qsort_trinkle(
8950                head.sub(lp[pshift as usize] + width),
8951                width, cmp, arg, &p, pshift + 1, 1, &lp,
8952            );
8953            qsort_shl(&mut p, 1);
8954            p[0] |= 1;
8955            qsort_trinkle(head.sub(width), width, cmp, arg, &p, pshift, 1, &lp);
8956        }
8957        head = head.sub(width);
8958    }
8959}
8960
8961#[no_mangle]
8962pub unsafe extern "C" fn qsort_r(
8963    base: *mut c_void,
8964    nel: usize,
8965    width: usize,
8966    cmp: CmpRfn,
8967    arg: *mut c_void,
8968) {
8969    __qsort_r(base, nel, width, cmp, arg);
8970}
8971
8972unsafe extern "C" fn qsort_wrap_cmp(
8973    a: *const c_void,
8974    b: *const c_void,
8975    cmp_ctx: *mut c_void,
8976) -> c_int {
8977    let cmp: CmpFn = core::mem::transmute(cmp_ctx);
8978    cmp(a, b)
8979}
8980
8981#[no_mangle]
8982pub unsafe extern "C" fn qsort(
8983    base: *mut c_void,
8984    nel: usize,
8985    width: usize,
8986    cmp: CmpFn,
8987) {
8988    __qsort_r(base, nel, width, qsort_wrap_cmp, cmp as *mut c_void);
8989}
8990
8991// ============================================================
8992// atexit / __cxa_atexit / __funcs_on_exit
8993// ============================================================
8994
8995const ATEXIT_COUNT: usize = 32;
8996
8997#[repr(C)]
8998struct AtExitBlock {
8999    next: *mut AtExitBlock,
9000    f: [Option<unsafe extern "C" fn(*mut c_void)>; ATEXIT_COUNT],
9001    a: [*mut c_void; ATEXIT_COUNT],
9002}
9003
9004static mut ATEXIT_BUILTIN: AtExitBlock = AtExitBlock {
9005    next: core::ptr::null_mut(),
9006    f: [None; ATEXIT_COUNT],
9007    a: [core::ptr::null_mut(); ATEXIT_COUNT],
9008};
9009static mut ATEXIT_HEAD: *mut AtExitBlock = core::ptr::null_mut();
9010static mut ATEXIT_SLOT: usize = 0;
9011static mut ATEXIT_FINISHED: bool = false;
9012
9013#[no_mangle]
9014pub unsafe extern "C" fn __funcs_on_exit() {
9015    while !ATEXIT_HEAD.is_null() {
9016        let head = ATEXIT_HEAD;
9017        while ATEXIT_SLOT > 0 {
9018            ATEXIT_SLOT -= 1;
9019            if let Some(f) = (*head).f[ATEXIT_SLOT] {
9020                let a = (*head).a[ATEXIT_SLOT];
9021                f(a);
9022            }
9023        }
9024        ATEXIT_HEAD = (*head).next;
9025        ATEXIT_SLOT = ATEXIT_COUNT;
9026    }
9027    ATEXIT_FINISHED = true;
9028}
9029
9030#[no_mangle]
9031pub unsafe extern "C" fn __cxa_atexit(
9032    func: unsafe extern "C" fn(*mut c_void),
9033    arg: *mut c_void,
9034    _dso: *mut c_void,
9035) -> c_int {
9036    if ATEXIT_FINISHED {
9037        return -1;
9038    }
9039    if ATEXIT_HEAD.is_null() {
9040        ATEXIT_HEAD = core::ptr::addr_of_mut!(ATEXIT_BUILTIN);
9041    }
9042    if ATEXIT_SLOT == ATEXIT_COUNT {
9043        let new = calloc(1, core::mem::size_of::<AtExitBlock>()) as *mut AtExitBlock;
9044        if new.is_null() {
9045            return -1;
9046        }
9047        (*new).next = ATEXIT_HEAD;
9048        ATEXIT_HEAD = new;
9049        ATEXIT_SLOT = 0;
9050    }
9051    (*ATEXIT_HEAD).f[ATEXIT_SLOT] = Some(func);
9052    (*ATEXIT_HEAD).a[ATEXIT_SLOT] = arg;
9053    ATEXIT_SLOT += 1;
9054    0
9055}
9056
9057unsafe extern "C" fn atexit_caller(arg: *mut c_void) {
9058    let func: unsafe extern "C" fn() = core::mem::transmute(arg);
9059    func();
9060}
9061
9062#[no_mangle]
9063pub unsafe extern "C" fn atexit(func: unsafe extern "C" fn()) -> c_int {
9064    __cxa_atexit(atexit_caller, func as *mut c_void, core::ptr::null_mut())
9065}
9066
9067#[no_mangle]
9068pub unsafe extern "C" fn __cxa_finalize(_dso: *mut c_void) {}
9069
9070// ============================================================
9071// getenv / setenv / putenv / unsetenv / clearenv
9072// ============================================================
9073
9074#[no_mangle]
9075pub static mut __environ: *mut *mut c_char = core::ptr::null_mut();
9076
9077// Growable tracking of strings allocated by setenv/putenv.  Realloc keeps
9078// this unbounded; if it fails the new string is simply left untracked.
9079static mut ENV_ALLOCED: *mut *mut c_char = core::ptr::null_mut();
9080static mut ENV_ALLOCED_N: usize = 0;
9081static mut ENV_ALLOCED_CAP: usize = 0;
9082
9083unsafe fn env_rm_add(old: *mut c_char, mut new: *mut c_char) {
9084    for i in 0..ENV_ALLOCED_N {
9085        if (*ENV_ALLOCED.add(i)) == old {
9086            *ENV_ALLOCED.add(i) = new;
9087            if !old.is_null() {
9088                free(old as *mut c_void);
9089            }
9090            return;
9091        } else if (*ENV_ALLOCED.add(i)).is_null() && !new.is_null() {
9092            *ENV_ALLOCED.add(i) = new;
9093            new = core::ptr::null_mut();
9094        }
9095    }
9096    if !new.is_null() {
9097        if ENV_ALLOCED_N == ENV_ALLOCED_CAP {
9098            let new_cap = if ENV_ALLOCED_CAP == 0 { 16 } else { ENV_ALLOCED_CAP * 2 };
9099            let grown = realloc(
9100                ENV_ALLOCED as *mut c_void,
9101                new_cap * core::mem::size_of::<*mut c_char>(),
9102            ) as *mut *mut c_char;
9103            if grown.is_null() {
9104                return;
9105            }
9106            ENV_ALLOCED = grown;
9107            ENV_ALLOCED_CAP = new_cap;
9108        }
9109        *ENV_ALLOCED.add(ENV_ALLOCED_N) = new;
9110        ENV_ALLOCED_N += 1;
9111    }
9112}
9113
9114unsafe fn strchrnul_u8(s: *const u8, c: u8) -> *const u8 {
9115    let mut p = s;
9116    while *p != 0 && *p != c {
9117        p = p.add(1);
9118    }
9119    p
9120}
9121
9122#[no_mangle]
9123pub unsafe extern "C" fn getenv(name: *const c_char) -> *mut c_char {
9124    if __environ.is_null() || name.is_null() {
9125        return core::ptr::null_mut();
9126    }
9127    let name = name as *const u8;
9128    let l = strchrnul_u8(name, b'=') as usize - name as usize;
9129    if l == 0 || *name.add(l) != 0 {
9130        return core::ptr::null_mut();
9131    }
9132    let mut e = __environ;
9133    while !(*e).is_null() {
9134        let entry = *e as *const u8;
9135        if strncmp(entry, name, l) == 0 && *entry.add(l) == b'=' {
9136            return entry.add(l + 1) as *mut c_char;
9137        }
9138        e = e.add(1);
9139    }
9140    core::ptr::null_mut()
9141}
9142
9143#[no_mangle]
9144pub unsafe extern "C" fn setenv(
9145    var: *const c_char,
9146    value: *const c_char,
9147    overwrite: c_int,
9148) -> c_int {
9149    if var.is_null() || value.is_null() {
9150        ERRNO!() = EINVAL;
9151        return -1;
9152    }
9153    let var = var as *const u8;
9154    let l1 = strchrnul_u8(var, b'=') as usize - var as usize;
9155    if l1 == 0 || *var.add(l1) != 0 {
9156        ERRNO!() = EINVAL;
9157        return -1;
9158    }
9159    if overwrite == 0 && !getenv(var as *const c_char).is_null() {
9160        return 0;
9161    }
9162    let l2 = strlen(value as *const c_char);
9163    let s = malloc(l1 + l2 + 2) as *mut u8;
9164    if s.is_null() {
9165        return -1;
9166    }
9167    core::ptr::copy_nonoverlapping(var, s, l1);
9168    *s.add(l1) = b'=';
9169    core::ptr::copy_nonoverlapping(value as *const u8, s.add(l1 + 1), l2 + 1);
9170    putenv_internal(s as *mut c_char, l1, s as *mut c_char)
9171}
9172
9173unsafe fn putenv_internal(s: *mut c_char, l: usize, r: *mut c_char) -> c_int {
9174    let mut i = 0;
9175    if !__environ.is_null() {
9176        let mut e = __environ;
9177        while !(*e).is_null() {
9178            if strncmp(s as *const u8, *e as *const u8, l + 1) == 0 {
9179                let tmp = *e;
9180                *e = s;
9181                env_rm_add(tmp, r);
9182                return 0;
9183            }
9184            e = e.add(1);
9185            i += 1;
9186        }
9187    }
9188    let newenv = malloc(core::mem::size_of::<*mut c_char>() * (i + 2)) as *mut *mut c_char;
9189    if newenv.is_null() {
9190        if !r.is_null() { free(r as *mut c_void); }
9191        return -1;
9192    }
9193    if i > 0 && !__environ.is_null() {
9194        core::ptr::copy_nonoverlapping(__environ, newenv, i);
9195    }
9196    *newenv.add(i) = s;
9197    *newenv.add(i + 1) = core::ptr::null_mut();
9198    // ponytail: don't free old __environ (may not be from our malloc)
9199    __environ = newenv;
9200    environ = __environ;
9201    if !r.is_null() {
9202        env_rm_add(core::ptr::null_mut(), r);
9203    }
9204    0
9205}
9206
9207#[no_mangle]
9208pub unsafe extern "C" fn putenv(s: *mut c_char) -> c_int {
9209    if s.is_null() { return -1; }
9210    let l = strchrnul_u8(s as *const u8, b'=') as usize - s as *const u8 as usize;
9211    if l == 0 || *s.add(l) as u8 == 0 {
9212        return unsetenv(s);
9213    }
9214    putenv_internal(s, l, core::ptr::null_mut())
9215}
9216
9217#[no_mangle]
9218pub unsafe extern "C" fn unsetenv(name: *const c_char) -> c_int {
9219    if name.is_null() {
9220        ERRNO!() = EINVAL;
9221        return -1;
9222    }
9223    let name = name as *const u8;
9224    let l = strchrnul_u8(name, b'=') as usize - name as usize;
9225    if l == 0 || *name.add(l) != 0 {
9226        ERRNO!() = EINVAL;
9227        return -1;
9228    }
9229    if __environ.is_null() {
9230        return 0;
9231    }
9232    let mut e = __environ;
9233    let mut eo = e;
9234    while !(*e).is_null() {
9235        if strncmp(name, *e as *const u8, l) == 0 && *(*e as *const u8).add(l) == b'=' {
9236            env_rm_add(*e, core::ptr::null_mut());
9237        } else {
9238            if eo != e {
9239                *eo = *e;
9240            }
9241            eo = eo.add(1);
9242        }
9243        e = e.add(1);
9244    }
9245    if eo != e {
9246        *eo = core::ptr::null_mut();
9247    }
9248    environ = __environ;
9249    0
9250}
9251
9252#[no_mangle]
9253pub unsafe extern "C" fn clearenv() -> c_int {
9254    let e = __environ;
9255    __environ = core::ptr::null_mut();
9256    environ = core::ptr::null_mut();
9257    if !e.is_null() {
9258        let mut p = e;
9259        while !(*p).is_null() {
9260            env_rm_add(*p, core::ptr::null_mut());
9261            p = p.add(1);
9262        }
9263    }
9264    0
9265}
9266
9267// ============================================================
9268// random / srandom / initstate / setstate (BSD lagged fibonacci)
9269// ponytail: single-threaded, no locking; add lock if concurrency matters
9270// ============================================================
9271
9272static mut RANDOM_INIT: [u32; 32] = [
9273    0x00000000,0x5851f42d,0xc0b18ccf,0xcbb5f646,
9274    0xc7033129,0x30705b04,0x20fd5db4,0x9a8b7f78,
9275    0x502959d8,0xab894868,0x6c0356a7,0x88cdb7ff,
9276    0xb477d43f,0x70a3a52b,0xa8e4baf1,0xfd8341fc,
9277    0x8ae16fd9,0x742d2f7a,0x0d1f0796,0x76035e09,
9278    0x40f7702c,0x6fa72ca5,0xaaa84157,0x58a0df74,
9279    0xc74a0364,0xae533cc4,0x04185faf,0x6de3b115,
9280    0x0cab8628,0xf043bfa4,0x398150e9,0x37521657,
9281];
9282
9283static mut RANDOM_N: i32 = 31;
9284static mut RANDOM_I: i32 = 3;
9285static mut RANDOM_J: i32 = 0;
9286static mut RANDOM_X: *mut u32 = unsafe { core::ptr::addr_of_mut!(RANDOM_INIT).cast::<u32>().add(1) };
9287
9288unsafe fn random_lcg31(x: u32) -> u32 {
9289    (1103515245u32.wrapping_mul(x).wrapping_add(12345)) & 0x7fffffff
9290}
9291
9292unsafe fn random_lcg64(x: u64) -> u64 {
9293    6364136223846793005u64.wrapping_mul(x).wrapping_add(1)
9294}
9295
9296unsafe fn random_savestate() -> *mut u8 {
9297    (*RANDOM_X.offset(-1)) = ((RANDOM_N as u32) << 16) | ((RANDOM_I as u32) << 8) | (RANDOM_J as u32);
9298    RANDOM_X.offset(-1) as *mut u8
9299}
9300
9301unsafe fn random_loadstate(state: *mut u32) {
9302    RANDOM_X = state.add(1);
9303    RANDOM_N = ((*RANDOM_X.offset(-1)) >> 16) as i32;
9304    RANDOM_I = (((*RANDOM_X.offset(-1)) >> 8) & 0xff) as i32;
9305    RANDOM_J = ((*RANDOM_X.offset(-1)) & 0xff) as i32;
9306}
9307
9308unsafe fn random_srandom_inner(seed: u32) {
9309    let mut s = seed as u64;
9310    if RANDOM_N == 0 {
9311        *RANDOM_X = s as u32;
9312        return;
9313    }
9314    RANDOM_I = if RANDOM_N == 31 || RANDOM_N == 7 { 3 } else { 1 };
9315    RANDOM_J = 0;
9316    for k in 0..RANDOM_N as usize {
9317        s = random_lcg64(s);
9318        *RANDOM_X.add(k) = (s >> 32) as u32;
9319    }
9320    *RANDOM_X |= 1;
9321}
9322
9323#[no_mangle]
9324pub unsafe extern "C" fn srandom(seed: c_uint) {
9325    random_srandom_inner(seed);
9326}
9327
9328#[no_mangle]
9329pub unsafe extern "C" fn initstate(seed: c_uint, state: *mut c_char, size: usize) -> *mut c_char {
9330    if size < 8 { return core::ptr::null_mut(); }
9331    let old = random_savestate();
9332    RANDOM_N = if size < 32 { 0 }
9333        else if size < 64 { 7 }
9334        else if size < 128 { 15 }
9335        else if size < 256 { 31 }
9336        else { 63 };
9337    RANDOM_X = (state as *mut u32).add(1);
9338    random_srandom_inner(seed);
9339    random_savestate();
9340    old as *mut c_char
9341}
9342
9343#[no_mangle]
9344pub unsafe extern "C" fn setstate(state: *mut c_char) -> *mut c_char {
9345    let old = random_savestate();
9346    random_loadstate(state as *mut u32);
9347    old as *mut c_char
9348}
9349
9350#[no_mangle]
9351pub unsafe extern "C" fn random() -> c_long {
9352    let k: c_long;
9353    if RANDOM_N == 0 {
9354        *RANDOM_X = random_lcg31(*RANDOM_X);
9355        k = *RANDOM_X as c_long;
9356    } else {
9357        *RANDOM_X.add(RANDOM_I as usize) = (*RANDOM_X.add(RANDOM_I as usize)).wrapping_add(*RANDOM_X.add(RANDOM_J as usize));
9358        k = (*RANDOM_X.add(RANDOM_I as usize) >> 1) as c_long;
9359        RANDOM_I += 1;
9360        if RANDOM_I == RANDOM_N { RANDOM_I = 0; }
9361        RANDOM_J += 1;
9362        if RANDOM_J == RANDOM_N { RANDOM_J = 0; }
9363    }
9364    k
9365}
9366
9367// ============================================================
9368// multibyte (UTF-8, musl state machine)
9369// ============================================================
9370
9371const SA: u8 = 0xC2;
9372const SB: u8 = 0xF4;
9373
9374const BITTAB: [u32; 51] = [
9375    0xC000_0002, 0xC000_0003, 0xC000_0004, 0xC000_0005, 0xC000_0006, 0xC000_0007,
9376    0xC000_0008, 0xC000_0009, 0xC000_000A, 0xC000_000B, 0xC000_000C, 0xC000_000D,
9377    0xC000_000E, 0xC000_000F, 0xC000_0010, 0xC000_0011, 0xC000_0012, 0xC000_0013,
9378    0xC000_0014, 0xC000_0015, 0xC000_0016, 0xC000_0017, 0xC000_0018, 0xC000_0019,
9379    0xC000_001A, 0xC000_001B, 0xC000_001C, 0xC000_001D, 0xC000_001E, 0xC000_001F,
9380    0xB300_0000, 0xC300_0001, 0xC300_0002, 0xC300_0003, 0xC300_0004, 0xC300_0005,
9381    0xC300_0006, 0xC300_0007, 0xC300_0008, 0xC300_0009, 0xC300_000A, 0xC300_000B,
9382    0xC300_000C, 0xD300_000D, 0xC300_000E, 0xC300_000F, 0xBB0C_0000, 0xC30C_0001,
9383    0xC30C_0002, 0xC30C_0003, 0xDB0C_0004,
9384];
9385
9386#[inline]
9387fn mb_oob(c: u32, b: u8) -> u32 {
9388    let b3 = (b >> 3) as u32;
9389    ((b3.wrapping_sub(0x10)) | (b3.wrapping_add((c as i32 >> 26) as u32))) & !7
9390}
9391
9392static mut MB_STATE: c_uint = 0;
9393
9394const MB_CUR_MAX_VAL_UTF8: usize = 4;
9395const MB_CUR_MAX_VAL_C: usize = 1;
9396
9397#[no_mangle]
9398pub extern "C" fn __ctype_get_mb_cur_max() -> usize {
9399    unsafe { if LOCALE_CTYPE_UTF8 { MB_CUR_MAX_VAL_UTF8 } else { MB_CUR_MAX_VAL_C } }
9400}
9401
9402#[no_mangle]
9403pub unsafe extern "C" fn mbrtowc(
9404    wc: *mut c_int,
9405    src: *const c_char,
9406    n: usize,
9407    st: *mut c_uint,
9408) -> usize {
9409    let s = src as *const u8;
9410    let n0 = n;
9411    let mut dummy: c_int = 0;
9412    let wc = if wc.is_null() { &mut dummy } else { &mut *wc };
9413    let st: &mut c_uint = if st.is_null() { &mut *(&raw mut MB_STATE) } else { &mut *st };
9414
9415    let mut c: u32 = *st;
9416    let mut s = s;
9417    let mut n = n;
9418
9419    if s.is_null() {
9420        if c != 0 { *st = 0; ERRNO!() = EILSEQ; return !0usize; }
9421        return 0;
9422    }
9423
9424    if n == 0 { return !1usize; }
9425
9426    if unsafe { !LOCALE_CTYPE_UTF8 } {
9427        let b = *s;
9428        *wc = b as c_int;
9429        return if b == 0 { 0 } else { 1 };
9430    }
9431
9432    if c == 0 {
9433        if *s < 0x80 {
9434            let r = if *s == 0 { 0 } else { 1 };
9435            *wc = *s as c_int;
9436            return r;
9437        }
9438        if (*s).wrapping_sub(SA) as u32 > (SB - SA) as u32 {
9439            *st = 0; ERRNO!() = EILSEQ; return !0usize;
9440        }
9441        c = BITTAB[*s as usize - SA as usize];
9442        s = s.add(1);
9443        n -= 1;
9444    }
9445
9446    if n > 0 {
9447        if mb_oob(c, *s) != 0 {
9448            *st = 0; ERRNO!() = EILSEQ; return !0usize;
9449        }
9450        loop {
9451            c = (c << 6) | (*s as u32).wrapping_sub(0x80);
9452            s = s.add(1);
9453            n -= 1;
9454            if c & (1u32 << 31) == 0 {
9455                *st = 0;
9456                *wc = c as c_int;
9457                return n0 - n;
9458            }
9459            if n == 0 { break; }
9460            if (*s).wrapping_sub(0x80) >= 0x40 {
9461                *st = 0; ERRNO!() = EILSEQ; return !0usize;
9462            }
9463        }
9464    }
9465
9466    *st = c;
9467    !1usize
9468}
9469
9470#[no_mangle]
9471pub unsafe extern "C" fn wcrtomb(
9472    s: *mut c_char,
9473    wc: c_int,
9474    _st: *mut c_uint,
9475) -> usize {
9476    if s.is_null() { return 1; }
9477    let wc_u = wc as u32;
9478    if unsafe { !LOCALE_CTYPE_UTF8 } {
9479        if wc_u > 0xFF {
9480            ERRNO!() = EILSEQ;
9481            return !0usize;
9482        }
9483        *s = wc as c_char;
9484        return 1;
9485    }
9486    if wc_u < 0x80 {
9487        *s = wc as c_char;
9488        return 1;
9489    }
9490    if wc_u < 0x800 {
9491        *s = (0xC0 | (wc_u >> 6)) as c_char;
9492        *s.add(1) = (0x80 | (wc_u & 0x3F)) as c_char;
9493        return 2;
9494    }
9495    if wc_u < 0xD800 || wc_u.wrapping_sub(0xE000) < 0x2000 {
9496        *s = (0xE0 | (wc_u >> 12)) as c_char;
9497        *s.add(1) = (0x80 | ((wc_u >> 6) & 0x3F)) as c_char;
9498        *s.add(2) = (0x80 | (wc_u & 0x3F)) as c_char;
9499        return 3;
9500    }
9501    if wc_u.wrapping_sub(0x10000) < 0x100000 {
9502        *s = (0xF0 | (wc_u >> 18)) as c_char;
9503        *s.add(1) = (0x80 | ((wc_u >> 12) & 0x3F)) as c_char;
9504        *s.add(2) = (0x80 | ((wc_u >> 6) & 0x3F)) as c_char;
9505        *s.add(3) = (0x80 | (wc_u & 0x3F)) as c_char;
9506        return 4;
9507    }
9508    ERRNO!() = EILSEQ;
9509    !0usize
9510}
9511
9512#[no_mangle]
9513pub unsafe extern "C" fn mblen(s: *const c_char, n: usize) -> c_int {
9514    if s.is_null() { return 0; }
9515    mbtowc(core::ptr::null_mut(), s, n)
9516}
9517
9518#[no_mangle]
9519pub unsafe extern "C" fn mbtowc(
9520    wc: *mut c_int,
9521    src: *const c_char,
9522    n: usize,
9523) -> c_int {
9524    if src.is_null() { return 0; }
9525    if n == 0 { ERRNO!() = EILSEQ; return -1; }
9526    let mut state: c_uint = 0;
9527    let mut w: c_int = 0;
9528    let r = mbrtowc(&mut w, src, n, &mut state);
9529    if r == !0usize { return -1; }
9530    if !wc.is_null() { *wc = w; }
9531    r as c_int
9532}
9533
9534#[no_mangle]
9535pub unsafe extern "C" fn wctomb(s: *mut c_char, wc: c_int) -> c_int {
9536    if s.is_null() { return 0; }
9537    wcrtomb(s, wc, core::ptr::null_mut()) as c_int
9538}
9539
9540#[no_mangle]
9541pub unsafe extern "C" fn mbsrtowcs(
9542    ws: *mut c_int,
9543    src: *mut *const c_char,
9544    wn: usize,
9545    st: *mut c_uint,
9546) -> usize {
9547    let st: &mut c_uint = if st.is_null() { &mut *(&raw mut MB_STATE) } else { &mut *st };
9548    let mut s = *src as *const u8;
9549    let wn0 = wn;
9550    let mut wn = wn;
9551
9552    if ws.is_null() {
9553        while *s != 0 {
9554            if *s < 0x80 {
9555                s = s.add(1);
9556                wn = wn.wrapping_sub(1);
9557                continue;
9558            }
9559            let mut wc: c_int = 0;
9560            let r = mbrtowc(&mut wc, s as *const c_char, 4, st);
9561            if r == !0usize { return !0usize; }
9562            if r == !1usize { return wn0 - wn; }
9563            s = s.add(r);
9564            wn = wn.wrapping_sub(1);
9565        }
9566        wn0 - wn
9567    } else {
9568        let mut w = ws;
9569        while wn > 0 {
9570            if *s < 0x80 {
9571                let c = *s as c_int;
9572                *w = c;
9573                if c == 0 {
9574                    *src = core::ptr::null();
9575                    return wn0 - wn;
9576                }
9577                w = w.add(1);
9578                s = s.add(1);
9579                wn -= 1;
9580                continue;
9581            }
9582            let mut wc: c_int = 0;
9583            let r = mbrtowc(&mut wc, s as *const c_char, 4, st);
9584            if r == !0usize {
9585                *src = s as *const c_char;
9586                return !0usize;
9587            }
9588            if r == !1usize {
9589                *src = s as *const c_char;
9590                return wn0 - wn;
9591            }
9592            *w = wc;
9593            w = w.add(1);
9594            s = s.add(r);
9595            wn -= 1;
9596        }
9597        *src = s as *const c_char;
9598        wn0 - wn
9599    }
9600}
9601
9602#[no_mangle]
9603pub unsafe extern "C" fn wcsrtombs(
9604    s: *mut c_char,
9605    ws: *mut *const c_int,
9606    n: usize,
9607    _st: *mut c_uint,
9608) -> usize {
9609    let mut w = *ws;
9610    let n0 = n;
9611    let mut n = n;
9612
9613    if s.is_null() {
9614        let mut count = 0usize;
9615        while *w != 0 {
9616            if (*w as u32) < 0x80 {
9617                count += 1;
9618            } else {
9619                let mut buf = [0u8; 4];
9620                let r = wcrtomb(buf.as_mut_ptr() as *mut c_char, *w, core::ptr::null_mut());
9621                if r == !0usize { return !0usize; }
9622                count += r;
9623            }
9624            w = w.add(1);
9625        }
9626        return count;
9627    }
9628
9629    let mut dst = s;
9630    while n > 0 {
9631        if (*w as u32) < 0x80 {
9632            *dst = *w as c_char;
9633            if *w == 0 {
9634                *ws = core::ptr::null();
9635                return n0 - n;
9636            }
9637            dst = dst.add(1);
9638            n -= 1;
9639        } else {
9640            let r = wcrtomb(dst, *w, core::ptr::null_mut());
9641            if r == !0usize {
9642                *ws = w;
9643                return !0usize;
9644            }
9645            if r > n {
9646                *ws = w;
9647                return n0 - n;
9648            }
9649            dst = dst.add(r);
9650            n -= r;
9651        }
9652        w = w.add(1);
9653    }
9654    *ws = w;
9655    n0
9656}
9657
9658#[no_mangle]
9659pub unsafe extern "C" fn mbstowcs(
9660    ws: *mut c_int,
9661    src: *const c_char,
9662    wn: usize,
9663) -> usize {
9664    let mut src_ptr = src;
9665    mbsrtowcs(ws, &mut src_ptr, wn, core::ptr::null_mut())
9666}
9667
9668#[no_mangle]
9669pub unsafe extern "C" fn wcstombs(
9670    s: *mut c_char,
9671    ws: *const c_int,
9672    n: usize,
9673) -> usize {
9674    let mut ws_ptr = ws;
9675    wcsrtombs(s, &mut ws_ptr, n, core::ptr::null_mut())
9676}
9677
9678// ============================================================
9679// wchar: btowc / wctob / mbsinit / mbrlen
9680// ============================================================
9681
9682#[no_mangle]
9683pub extern "C" fn btowc(c: c_int) -> wint_t {
9684    if c == -1 { return WEOF; }
9685    unsafe {
9686        if LOCALE_CTYPE_UTF8 {
9687            if (c as u32) < 128 { c as wint_t } else { WEOF }
9688        } else {
9689            (c as u8) as wint_t
9690        }
9691    }
9692}
9693
9694#[no_mangle]
9695pub extern "C" fn wctob(c: wint_t) -> c_int {
9696    unsafe {
9697        if LOCALE_CTYPE_UTF8 {
9698            if c < 128 { c as c_int } else { -1 }
9699        } else {
9700            if c <= 0xFF { c as c_int } else { -1 }
9701        }
9702    }
9703}
9704
9705#[no_mangle]
9706pub unsafe extern "C" fn mbsinit(s: *const c_uint) -> c_int {
9707    if s.is_null() || *s == 0 { 1 } else { 0 }
9708}
9709
9710#[no_mangle]
9711pub unsafe extern "C" fn mbrlen(s: *const c_char, n: usize, ps: *mut c_uint) -> usize {
9712    mbrtowc(core::ptr::null_mut(), s, n, ps)
9713}
9714
9715// ============================================================
9716// wchar: wide string functions
9717// ============================================================
9718
9719#[no_mangle]
9720pub unsafe extern "C" fn wcslen(s: *const wchar_t) -> usize {
9721    let mut len = 0;
9722    while *s.add(len) != 0 { len += 1; }
9723    len
9724}
9725
9726#[no_mangle]
9727pub unsafe extern "C" fn wcschr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
9728    let mut i = 0;
9729    loop {
9730        let ch = *s.add(i);
9731        if ch == c { return s.add(i) as *mut wchar_t; }
9732        if ch == 0 { return null_mut(); }
9733        i += 1;
9734    }
9735}
9736
9737#[no_mangle]
9738pub unsafe extern "C" fn wcsrchr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
9739    let mut i = 0;
9740    let mut last: *mut wchar_t = null_mut();
9741    loop {
9742        let ch = *s.add(i);
9743        if ch == c { last = s.add(i) as *mut wchar_t; }
9744        if ch == 0 { return last; }
9745        i += 1;
9746    }
9747}
9748
9749#[no_mangle]
9750pub unsafe extern "C" fn wcsstr(haystack: *const wchar_t, needle: *const wchar_t) -> *mut wchar_t {
9751    if *needle == 0 { return haystack as *mut wchar_t; }
9752    let mut i = 0;
9753    loop {
9754        let h = *haystack.add(i);
9755        if h == 0 { return null_mut(); }
9756        if h == *needle {
9757            let mut j = 0;
9758            loop {
9759                let n = *needle.add(j);
9760                if n == 0 { return haystack.add(i) as *mut wchar_t; }
9761                if *haystack.add(i + j) != n { break; }
9762                j += 1;
9763            }
9764        }
9765        i += 1;
9766    }
9767}
9768
9769#[no_mangle]
9770pub unsafe extern "C" fn wcscmp(s1: *const wchar_t, s2: *const wchar_t) -> c_int {
9771    let mut i = 0;
9772    loop {
9773        let a = *s1.add(i);
9774        let b = *s2.add(i);
9775        if a != b { return a - b; }
9776        if a == 0 { return 0; }
9777        i += 1;
9778    }
9779}
9780
9781#[no_mangle]
9782pub unsafe extern "C" fn wcsncmp(s1: *const wchar_t, s2: *const wchar_t, n: usize) -> c_int {
9783    let mut i = 0;
9784    while i < n {
9785        let a = *s1.add(i);
9786        let b = *s2.add(i);
9787        if a != b { return a - b; }
9788        if a == 0 { return 0; }
9789        i += 1;
9790    }
9791    0
9792}
9793
9794#[no_mangle]
9795pub unsafe extern "C" fn wcscpy(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
9796    let mut i = 0;
9797    loop {
9798        let c = *src.add(i);
9799        *dst.add(i) = c;
9800        if c == 0 { break; }
9801        i += 1;
9802    }
9803    dst
9804}
9805
9806#[no_mangle]
9807pub unsafe extern "C" fn wcsncpy(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
9808    let mut i = 0;
9809    while i < n && *src.add(i) != 0 { *dst.add(i) = *src.add(i); i += 1; }
9810    while i < n { *dst.add(i) = 0; i += 1; }
9811    dst
9812}
9813
9814#[no_mangle]
9815pub unsafe extern "C" fn wcscat(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
9816    let mut i = 0;
9817    while *dst.add(i) != 0 { i += 1; }
9818    let mut j = 0;
9819    loop {
9820        let c = *src.add(j);
9821        *dst.add(i + j) = c;
9822        if c == 0 { break; }
9823        j += 1;
9824    }
9825    dst
9826}
9827
9828#[no_mangle]
9829pub unsafe extern "C" fn wcsncat(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
9830    let mut i = 0;
9831    while *dst.add(i) != 0 { i += 1; }
9832    let mut j = 0;
9833    while j < n && *src.add(j) != 0 { *dst.add(i + j) = *src.add(j); j += 1; }
9834    *dst.add(i + j) = 0;
9835    dst
9836}
9837
9838#[no_mangle]
9839pub unsafe extern "C" fn wcsdup(s: *const wchar_t) -> *mut wchar_t {
9840    let len = wcslen(s);
9841    let p = malloc((len + 1) * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
9842    if p.is_null() { return null_mut(); }
9843    core::ptr::copy_nonoverlapping(s, p, len + 1);
9844    p
9845}
9846
9847#[no_mangle]
9848pub unsafe extern "C" fn wcsnlen(s: *const wchar_t, maxlen: usize) -> usize {
9849    let mut i = 0;
9850    while i < maxlen && *s.add(i) != 0 { i += 1; }
9851    i
9852}
9853
9854#[no_mangle]
9855pub unsafe extern "C" fn wcsspn(s: *const wchar_t, accept: *const wchar_t) -> usize {
9856    let mut i = 0;
9857    loop {
9858        let c = *s.add(i);
9859        if c == 0 { return i; }
9860        let mut found = false;
9861        let mut j = 0;
9862        loop {
9863            let a = *accept.add(j);
9864            if a == 0 { break; }
9865            if c == a { found = true; break; }
9866            j += 1;
9867        }
9868        if !found { return i; }
9869        i += 1;
9870    }
9871}
9872
9873#[no_mangle]
9874pub unsafe extern "C" fn wcscspn(s: *const wchar_t, reject: *const wchar_t) -> usize {
9875    let mut i = 0;
9876    loop {
9877        let c = *s.add(i);
9878        if c == 0 { return i; }
9879        let mut j = 0;
9880        loop {
9881            let r = *reject.add(j);
9882            if r == 0 { break; }
9883            if c == r { return i; }
9884            j += 1;
9885        }
9886        i += 1;
9887    }
9888}
9889
9890#[no_mangle]
9891pub unsafe extern "C" fn wcspbrk(s: *const wchar_t, accept: *const wchar_t) -> *mut wchar_t {
9892    let mut i = 0;
9893    loop {
9894        let c = *s.add(i);
9895        if c == 0 { return null_mut(); }
9896        let mut j = 0;
9897        loop {
9898            let a = *accept.add(j);
9899            if a == 0 { break; }
9900            if c == a { return s.add(i) as *mut wchar_t; }
9901            j += 1;
9902        }
9903        i += 1;
9904    }
9905}
9906
9907#[no_mangle]
9908pub unsafe extern "C" fn wcsxfrm(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> usize {
9909    let len = wcslen(src);
9910    if !dst.is_null() {
9911        let copy = if len < n { len } else { if n > 0 { n - 1 } else { 0 } };
9912        for i in 0..copy { *dst.add(i) = *src.add(i); }
9913        if n > 0 { *dst.add(copy) = 0; }
9914    }
9915    len
9916}
9917
9918// ============================================================
9919// wchar: wcsto* number conversions
9920// ============================================================
9921
9922unsafe fn wcs_to_bytes(ws: *const wchar_t, buf: *mut u8, bufsz: usize) -> usize {
9923    let mut i = 0;
9924    while i < bufsz - 1 {
9925        let c = *ws.add(i);
9926        if c == 0 { break; }
9927        if (c as u32) > 127 { break; }
9928        *buf.add(i) = c as u8;
9929        i += 1;
9930    }
9931    *buf.add(i) = 0;
9932    i
9933}
9934
9935#[no_mangle]
9936pub unsafe extern "C" fn wcstol(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_long {
9937    let mut buf = [0u8; 256];
9938    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9939    let mut end: *mut c_char = core::ptr::null_mut();
9940    let r = strtol(buf.as_ptr() as *const c_char, &mut end, base);
9941    if !endptr.is_null() {
9942        let offset = end as usize - buf.as_ptr() as usize;
9943        *endptr = s.add(offset) as *mut wchar_t;
9944    }
9945    r
9946}
9947
9948#[no_mangle]
9949pub unsafe extern "C" fn wcstoul(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulong {
9950    let mut buf = [0u8; 256];
9951    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9952    let mut end: *mut c_char = core::ptr::null_mut();
9953    let r = strtoul(buf.as_ptr() as *const c_char, &mut end, base);
9954    if !endptr.is_null() {
9955        let offset = end as usize - buf.as_ptr() as usize;
9956        *endptr = s.add(offset) as *mut wchar_t;
9957    }
9958    r
9959}
9960
9961#[no_mangle]
9962pub unsafe extern "C" fn wcstoll(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_longlong {
9963    let mut buf = [0u8; 256];
9964    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9965    let mut end: *mut c_char = core::ptr::null_mut();
9966    let r = strtoll(buf.as_ptr() as *const c_char, &mut end, base);
9967    if !endptr.is_null() {
9968        let offset = end as usize - buf.as_ptr() as usize;
9969        *endptr = s.add(offset) as *mut wchar_t;
9970    }
9971    r
9972}
9973
9974#[no_mangle]
9975pub unsafe extern "C" fn wcstoull(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulonglong {
9976    let mut buf = [0u8; 256];
9977    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9978    let mut end: *mut c_char = core::ptr::null_mut();
9979    let r = strtoull(buf.as_ptr() as *const c_char, &mut end, base);
9980    if !endptr.is_null() {
9981        let offset = end as usize - buf.as_ptr() as usize;
9982        *endptr = s.add(offset) as *mut wchar_t;
9983    }
9984    r
9985}
9986
9987#[no_mangle]
9988pub unsafe extern "C" fn wcstod(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 {
9989    let mut buf = [0u8; 256];
9990    wcs_to_bytes(s, buf.as_mut_ptr(), 256);
9991    let mut end: *mut c_char = core::ptr::null_mut();
9992    let r = strtod(buf.as_ptr() as *const c_char, &mut end);
9993    if !endptr.is_null() {
9994        let offset = end as usize - buf.as_ptr() as usize;
9995        *endptr = s.add(offset) as *mut wchar_t;
9996    }
9997    r
9998}
9999
10000#[no_mangle]
10001pub unsafe extern "C" fn wcstof(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f32 { wcstod(s, endptr) as f32 }
10002
10003#[no_mangle]
10004#[cfg(target_arch = "x86_64")]
10005pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 { wcstod(s, endptr) }
10006
10007#[no_mangle]
10008#[cfg(target_arch = "aarch64")]
10009pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { wcstod(s, endptr) as f128 }
10010
10011#[no_mangle]
10012#[cfg(target_arch = "riscv64")]
10013pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { wcstod(s, endptr) as f128 }
10014
10015#[no_mangle]
10016pub unsafe extern "C" fn wcstoimax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_longlong { wcstoll(s, endptr, base) }
10017
10018#[no_mangle]
10019pub unsafe extern "C" fn wcstoumax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulonglong { wcstoull(s, endptr, base) }
10020
10021// ============================================================
10022// wctype: classification functions
10023// ============================================================
10024
10025const WC_ALPHA: c_int = 1;
10026const WC_DIGIT: c_int = 2;
10027const WC_SPACE: c_int = 4;
10028const WC_UPPER: c_int = 8;
10029const WC_LOWER: c_int = 16;
10030const WC_ALNUM: c_int = WC_ALPHA | WC_DIGIT;
10031const WC_BLANK: c_int = 32;
10032const WC_CNTRL: c_int = 64;
10033const WC_PUNCT: c_int = 128;
10034const WC_GRAPH: c_int = WC_ALNUM | WC_PUNCT;
10035const WC_PRINT: c_int = WC_GRAPH | WC_BLANK;
10036const WC_XDIGIT: c_int = 256;
10037
10038fn wc_flags(c: wint_t) -> c_int {
10039    if c < 128 {
10040        let f = CT_TABLE[c as usize];
10041        let mut r = 0;
10042        if f & (CT_UPPER | CT_LOWER) != 0 { r |= WC_ALPHA; }
10043        if f & CT_DIGIT != 0 { r |= WC_DIGIT; }
10044        if f & CT_SPACE != 0 { r |= WC_SPACE; }
10045        if f & CT_UPPER != 0 { r |= WC_UPPER; }
10046        if f & CT_LOWER != 0 { r |= WC_LOWER; }
10047        if f & CT_BLANK != 0 { r |= WC_BLANK; }
10048        if f & CT_CNTRL != 0 { r |= WC_CNTRL; }
10049        if f & CT_PUNCT != 0 { r |= WC_PUNCT; }
10050        if f & CT_XDIGIT != 0 { r |= WC_XDIGIT; }
10051        r
10052    } else {
10053        if c < 0x100 { 0 }
10054        else { WC_PRINT | WC_ALPHA }
10055    }
10056}
10057
10058#[no_mangle]
10059pub extern "C" fn iswalnum(c: wint_t) -> c_int { (wc_flags(c) & WC_ALNUM != 0) as c_int }
10060#[no_mangle]
10061pub extern "C" fn iswalpha(c: wint_t) -> c_int { (wc_flags(c) & WC_ALPHA != 0) as c_int }
10062#[no_mangle]
10063pub extern "C" fn iswblank(c: wint_t) -> c_int { (wc_flags(c) & WC_BLANK != 0) as c_int }
10064#[no_mangle]
10065pub extern "C" fn iswcntrl(c: wint_t) -> c_int { (wc_flags(c) & WC_CNTRL != 0) as c_int }
10066#[no_mangle]
10067pub extern "C" fn iswdigit(c: wint_t) -> c_int { ((c >= b'0' as wint_t) && (c <= b'9' as wint_t)) as c_int }
10068#[no_mangle]
10069pub extern "C" fn iswgraph(c: wint_t) -> c_int { (wc_flags(c) & WC_GRAPH != 0) as c_int }
10070#[no_mangle]
10071pub extern "C" fn iswlower(c: wint_t) -> c_int { (wc_flags(c) & WC_LOWER != 0) as c_int }
10072#[no_mangle]
10073pub extern "C" fn iswprint(c: wint_t) -> c_int {
10074    if c < 128 { (wc_flags(c) & WC_PRINT != 0) as c_int }
10075    else if c >= 0x100 && c < 0x110000 { 1 }
10076    else { 0 }
10077}
10078#[no_mangle]
10079pub extern "C" fn iswpunct(c: wint_t) -> c_int { (wc_flags(c) & WC_PUNCT != 0) as c_int }
10080#[no_mangle]
10081pub extern "C" fn iswspace(c: wint_t) -> c_int {
10082    if c < 128 { (wc_flags(c) & WC_SPACE != 0) as c_int }
10083    else {
10084        match c {
10085            0x1680 | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000 => 1,
10086            _ => 0,
10087        }
10088    }
10089}
10090#[no_mangle]
10091pub extern "C" fn iswupper(c: wint_t) -> c_int { (wc_flags(c) & WC_UPPER != 0) as c_int }
10092#[no_mangle]
10093pub extern "C" fn iswxdigit(c: wint_t) -> c_int { (wc_flags(c) & WC_XDIGIT != 0) as c_int }
10094
10095static WCTYPE_ALNUM: c_int = WC_ALNUM;
10096static WCTYPE_ALPHA: c_int = WC_ALPHA;
10097static WCTYPE_BLANK: c_int = WC_BLANK;
10098static WCTYPE_CNTRL: c_int = WC_CNTRL;
10099static WCTYPE_DIGIT: c_int = WC_DIGIT;
10100static WCTYPE_GRAPH: c_int = WC_GRAPH;
10101static WCTYPE_LOWER: c_int = WC_LOWER;
10102static WCTYPE_PRINT: c_int = WC_PRINT;
10103static WCTYPE_PUNCT: c_int = WC_PUNCT;
10104static WCTYPE_SPACE: c_int = WC_SPACE;
10105static WCTYPE_UPPER: c_int = WC_UPPER;
10106static WCTYPE_XDIGIT: c_int = WC_XDIGIT;
10107
10108#[no_mangle]
10109pub unsafe extern "C" fn wctype(name: *const c_char) -> wctype_t {
10110    if name.is_null() { return core::ptr::null(); }
10111    let n = name as *const u8;
10112    if strcmp(n, b"alnum\0".as_ptr()) == 0 { return &WCTYPE_ALNUM; }
10113    if strcmp(n, b"alpha\0".as_ptr()) == 0 { return &WCTYPE_ALPHA; }
10114    if strcmp(n, b"blank\0".as_ptr()) == 0 { return &WCTYPE_BLANK; }
10115    if strcmp(n, b"cntrl\0".as_ptr()) == 0 { return &WCTYPE_CNTRL; }
10116    if strcmp(n, b"digit\0".as_ptr()) == 0 { return &WCTYPE_DIGIT; }
10117    if strcmp(n, b"graph\0".as_ptr()) == 0 { return &WCTYPE_GRAPH; }
10118    if strcmp(n, b"lower\0".as_ptr()) == 0 { return &WCTYPE_LOWER; }
10119    if strcmp(n, b"print\0".as_ptr()) == 0 { return &WCTYPE_PRINT; }
10120    if strcmp(n, b"punct\0".as_ptr()) == 0 { return &WCTYPE_PUNCT; }
10121    if strcmp(n, b"space\0".as_ptr()) == 0 { return &WCTYPE_SPACE; }
10122    if strcmp(n, b"upper\0".as_ptr()) == 0 { return &WCTYPE_UPPER; }
10123    if strcmp(n, b"xdigit\0".as_ptr()) == 0 { return &WCTYPE_XDIGIT; }
10124    core::ptr::null()
10125}
10126
10127#[no_mangle]
10128pub unsafe extern "C" fn iswctype(c: wint_t, desc: wctype_t) -> c_int {
10129    if desc.is_null() { return 0; }
10130    (wc_flags(c) & *desc != 0) as c_int
10131}
10132
10133static WCTRANS_LOWER: c_int = 1;
10134static WCTRANS_UPPER: c_int = 2;
10135
10136#[no_mangle]
10137pub unsafe extern "C" fn towlower(c: wint_t) -> wint_t {
10138    if c < 128 { tolower(c as c_int) as wint_t } else { c }
10139}
10140
10141#[no_mangle]
10142pub unsafe extern "C" fn towupper(c: wint_t) -> wint_t {
10143    if c < 128 { toupper(c as c_int) as wint_t } else { c }
10144}
10145
10146#[no_mangle]
10147pub unsafe extern "C" fn wctrans(name: *const c_char) -> wctrans_t {
10148    if name.is_null() { return core::ptr::null(); }
10149    let n = name as *const u8;
10150    if strcmp(n, b"tolower\0".as_ptr()) == 0 { return &WCTRANS_LOWER; }
10151    if strcmp(n, b"toupper\0".as_ptr()) == 0 { return &WCTRANS_UPPER; }
10152    core::ptr::null()
10153}
10154
10155#[no_mangle]
10156pub unsafe extern "C" fn towctrans(c: wint_t, desc: wctrans_t) -> wint_t {
10157    if desc.is_null() { return c; }
10158    match *desc {
10159        1 => towlower(c),
10160        2 => towupper(c),
10161        _ => c,
10162    }
10163}
10164
10165// ============================================================
10166// wchar: wide stdio
10167// ============================================================
10168
10169#[no_mangle]
10170pub unsafe extern "C" fn fgetwc(f: *mut FILE) -> wint_t {
10171    let mut state: c_uint = 0;
10172    let mut wc: wchar_t = 0;
10173    let mut buf = [0u8; 4];
10174    let c = fgetc(f);
10175    if c == -1 { return WEOF; }
10176    buf[0] = c as u8;
10177    if buf[0] < 0x80 { return buf[0] as wint_t; }
10178    let len = if buf[0] < 0xE0 { 2 } else if buf[0] < 0xF0 { 3 } else { 4 };
10179    let mut n = 1usize;
10180    while n < len {
10181        let c2 = fgetc(f);
10182        if c2 == -1 { return WEOF; }
10183        buf[n] = c2 as u8;
10184        n += 1;
10185    }
10186    let r = mbrtowc(&mut wc, buf.as_ptr() as *const c_char, n, &mut state);
10187    if r == !0usize || r == !1usize { WEOF } else { wc as wint_t }
10188}
10189
10190#[no_mangle]
10191pub unsafe extern "C" fn fputwc(c: wchar_t, f: *mut FILE) -> wint_t {
10192    let mut buf = [0u8; 4];
10193    let n = wcrtomb(buf.as_mut_ptr() as *mut c_char, c, core::ptr::null_mut());
10194    if n == !0usize || n == 0 { return WEOF; }
10195    if fwrite(buf.as_ptr() as *const c_void, 1, n, f) != n { return WEOF; }
10196    c as wint_t
10197}
10198
10199#[no_mangle]
10200pub unsafe extern "C" fn fputws(s: *const wchar_t, f: *mut FILE) -> c_int {
10201    let mut i = 0;
10202    while *s.add(i) != 0 {
10203        if fputwc(*s.add(i), f) == WEOF { return -1; }
10204        i += 1;
10205    }
10206    0
10207}
10208
10209#[no_mangle]
10210pub unsafe extern "C" fn ungetwc(c: wint_t, f: *mut FILE) -> wint_t {
10211    if c == WEOF { return WEOF; }
10212    let mut buf = [0u8; 4];
10213    let n = wcrtomb(buf.as_mut_ptr() as *mut c_char, c as wchar_t, core::ptr::null_mut());
10214    if n == !0usize || n == 0 { return WEOF; }
10215    let mut i = n;
10216    while i > 0 {
10217        i -= 1;
10218        if ungetc(buf[i] as c_int, f) == -1 { return WEOF; }
10219    }
10220    c
10221}
10222
10223#[no_mangle]
10224pub unsafe extern "C" fn getwchar() -> wint_t { fgetwc(stdin) }
10225
10226#[no_mangle]
10227pub unsafe extern "C" fn putwchar(c: wchar_t) -> wint_t { fputwc(c, stdout) }
10228
10229// ============================================================
10230// wchar: swprintf / vswprintf / fwprintf / vfwprintf
10231// ============================================================
10232
10233unsafe fn wfmt_write_str(dst: *mut wchar_t, pos: usize, cap: usize, s: *const u8, len: usize) -> usize {
10234    let mut i = 0;
10235    while i < len {
10236        if pos + i < cap { *dst.add(pos + i) = *s.add(i) as wchar_t; }
10237        i += 1;
10238    }
10239    pos + len
10240}
10241
10242#[no_mangle]
10243pub unsafe extern "C" fn vswprintf(s: *mut wchar_t, n: usize, fmt: *const wchar_t, mut args: VaList) -> c_int {
10244    if n == 0 { return -1; }
10245    let cap = n - 1;
10246    let mut pos = 0usize;
10247    // ponytail: format specifiers are ASCII; narrow buffer suffices for parsing
10248    let mut fmt_narrow = [0u8; 256];
10249    let mut flen = 0usize;
10250    loop {
10251        let ch = *fmt.add(flen) as u32;
10252        if ch == 0 || flen >= 255 { break; }
10253        fmt_narrow[flen] = if ch < 128 { ch as u8 } else { b'?' };
10254        flen += 1;
10255    }
10256    fmt_narrow[flen] = 0;
10257    let mut fi = 0usize;
10258    macro_rules! wc {
10259        ($c:expr) => { if pos < cap { *s.add(pos) = $c as wchar_t; } pos += 1; }
10260    }
10261    loop {
10262        let c = fmt_narrow[fi];
10263        if c == 0 { break; }
10264        if c != b'%' { wc!(c); fi += 1; continue; }
10265        fi += 1;
10266        let mut flags: u8 = 0;
10267        loop {
10268            match fmt_narrow[fi] {
10269                b'-' => { flags |= FLAG_MINUS; fi += 1; }
10270                b'+' => { flags |= FLAG_PLUS; fi += 1; }
10271                b' ' => { flags |= FLAG_SPACE; fi += 1; }
10272                b'0' => { flags |= FLAG_ZERO; fi += 1; }
10273                b'#' => { flags |= FLAG_HASH; fi += 1; }
10274                _ => break,
10275            }
10276        }
10277        let mut width: usize = 0;
10278        if fmt_narrow[fi] == b'*' {
10279            let w = args.next_arg::<c_int>();
10280            if w < 0 { flags |= FLAG_MINUS; width = (-w) as usize; } else { width = w as usize; }
10281            fi += 1;
10282        } else {
10283            while fmt_narrow[fi] >= b'0' && fmt_narrow[fi] <= b'9' {
10284                width = width * 10 + (fmt_narrow[fi] - b'0') as usize; fi += 1;
10285            }
10286        }
10287        let mut precision: i32 = -1;
10288        if fmt_narrow[fi] == b'.' {
10289            fi += 1;
10290            if fmt_narrow[fi] == b'*' {
10291                let p = args.next_arg::<c_int>();
10292                precision = if p < 0 { -1 } else { p }; fi += 1;
10293            } else {
10294                precision = 0;
10295                while fmt_narrow[fi] >= b'0' && fmt_narrow[fi] <= b'9' {
10296                    precision = precision * 10 + (fmt_narrow[fi] - b'0') as i32; fi += 1;
10297                }
10298            }
10299        }
10300        let len_mod = fmt_narrow[fi];
10301        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' {
10302            fi += 1;
10303            let spec = fmt_narrow[fi];
10304            if (len_mod == b'h' && spec == b'h') || (len_mod == b'l' && spec == b'l') {
10305                fi += 1;
10306                let spec2 = fmt_narrow[fi];
10307                match (len_mod, spec, spec2) {
10308                    (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; } }
10309                    (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; } }
10310                    (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
10311                        let val = args.next_arg::<c_longlong>();
10312                        let neg = val < 0;
10313                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
10314                        let b = format_u64(abs);
10315                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10316                        let mut fbuf = [0u8; 32];
10317                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10318                        for k in 0..len { wc!(fbuf[k]); }
10319                    }
10320                    (b'l', b'l', b'u') => {
10321                        let val = args.next_arg::<c_ulonglong>();
10322                        let b = format_u64(val as u64);
10323                        let mut fbuf = [0u8; 32];
10324                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10325                        for k in 0..len { wc!(fbuf[k]); }
10326                    }
10327                    (b'l', b'l', b'x') => {
10328                        let val = args.next_arg::<c_ulonglong>();
10329                        let b = format_hex(val as u64, false);
10330                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10331                        let mut fbuf = [0u8; 32];
10332                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10333                        for k in 0..len { wc!(fbuf[k]); }
10334                    }
10335                    (b'l', b'l', b'X') => {
10336                        let val = args.next_arg::<c_ulonglong>();
10337                        let b = format_hex(val as u64, true);
10338                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10339                        let mut fbuf = [0u8; 32];
10340                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10341                        for k in 0..len { wc!(fbuf[k]); }
10342                    }
10343                    (b'l', b'l', b'o') => {
10344                        let val = args.next_arg::<c_ulonglong>();
10345                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
10346                        let mut fbuf = [0u8; 32];
10347                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10348                        for k in 0..len { wc!(fbuf[k]); }
10349                    }
10350                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); wc!(spec2); }
10351                }
10352            } else {
10353                let lm = if (len_mod == b'z' || len_mod == b't') && spec != b'n' { b'l' } else { len_mod };
10354                match (lm, spec) {
10355                    (b'h', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut u16) = pos as u16; } }
10356                    (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; } }
10357                    (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; } }
10358                    (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; } }
10359                    (b'l', b'd') | (b'l', b'i') => {
10360                        let val = args.next_arg::<c_long>();
10361                        let neg = val < 0;
10362                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
10363                        let b = format_u64(abs);
10364                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10365                        let mut fbuf = [0u8; 32];
10366                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10367                        for k in 0..len { wc!(fbuf[k]); }
10368                    }
10369                    (b'l', b'u') => {
10370                        let val = args.next_arg::<c_ulong>();
10371                        let b = format_u64(val as u64);
10372                        let mut fbuf = [0u8; 32];
10373                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10374                        for k in 0..len { wc!(fbuf[k]); }
10375                    }
10376                    (b'l', b'x') => {
10377                        let val = args.next_arg::<c_ulong>();
10378                        let b = format_hex(val as u64, false);
10379                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10380                        let mut fbuf = [0u8; 32];
10381                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10382                        for k in 0..len { wc!(fbuf[k]); }
10383                    }
10384                    (b'l', b'X') => {
10385                        let val = args.next_arg::<c_ulong>();
10386                        let b = format_hex(val as u64, true);
10387                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10388                        let mut fbuf = [0u8; 32];
10389                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10390                        for k in 0..len { wc!(fbuf[k]); }
10391                    }
10392                    (b'l', b'o') => {
10393                        let val = args.next_arg::<c_ulong>();
10394                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
10395                        let mut fbuf = [0u8; 32];
10396                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10397                        for k in 0..len { wc!(fbuf[k]); }
10398                    }
10399                    (b'l', b'c') => {
10400                        let ch = args.next_arg::<wint_t>();
10401                        wc!(ch);
10402                    }
10403                    (b'l', b's') => {
10404                        let ws_arg = args.next_arg::<*const wchar_t>();
10405                        if ws_arg.is_null() {
10406                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
10407                            if flags & FLAG_MINUS != 0 {
10408                                for k in 0..slen { wc!(b"(null)"[k]); }
10409                                for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10410                            } else {
10411                                for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10412                                for k in 0..slen { wc!(b"(null)"[k]); }
10413                            }
10414                        } else {
10415                            let mut wlen = 0usize;
10416                            loop {
10417                                let ch = *ws_arg.add(wlen);
10418                                if ch == 0 { break; }
10419                                if precision >= 0 && wlen >= precision as usize { break; }
10420                                wlen += 1;
10421                            }
10422                            if flags & FLAG_MINUS != 0 {
10423                                for k in 0..wlen { wc!(*ws_arg.add(k)); }
10424                                for _ in 0..width.saturating_sub(wlen) { wc!(b' '); }
10425                            } else {
10426                                for _ in 0..width.saturating_sub(wlen) { wc!(b' '); }
10427                                for k in 0..wlen { wc!(*ws_arg.add(k)); }
10428                            }
10429                        }
10430                    }
10431                    (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
10432                    | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
10433                        let val = args.next_arg::<f64>();
10434                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10435                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10436                        let mut fbuf = [0u8; 4224];
10437                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10438                        let mut wbuf = [0u8; 4224];
10439                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10440                        for k in 0..wlen { wc!(wbuf[k]); }
10441                    }
10442                    (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
10443                    | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
10444                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
10445                        let val = {
10446                            let lo: u64 = args.next_arg::<u64>();
10447                            let hi: u64 = args.next_arg::<u64>();
10448                            let combined: u128 = ((hi as u128) << 64) | (lo as u128);
10449                            f128::from_bits(combined) as f64
10450                        };
10451                        #[cfg(target_arch = "x86_64")]
10452                        let val = args.next_arg::<f64>();
10453                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10454                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10455                        let mut fbuf = [0u8; 4224];
10456                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10457                        let mut wbuf = [0u8; 4224];
10458                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10459                        for k in 0..wlen { wc!(wbuf[k]); }
10460                    }
10461                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); }
10462                }
10463            }
10464        } else {
10465            let spec = fmt_narrow[fi];
10466            match spec {
10467                b'd' | b'i' => {
10468                    let d = args.next_arg::<c_int>();
10469                    let neg = d < 0;
10470                    let abs = if neg { d.wrapping_neg() as u64 } else { d as u64 };
10471                    let b = format_u64(abs);
10472                    let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10473                    let mut fbuf = [0u8; 32];
10474                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10475                    for k in 0..len { wc!(fbuf[k]); }
10476                }
10477                b'u' => {
10478                    let u = args.next_arg::<c_uint>();
10479                    let b = format_u64(u as u64);
10480                    let mut fbuf = [0u8; 32];
10481                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10482                    for k in 0..len { wc!(fbuf[k]); }
10483                }
10484                b'x' => {
10485                    let x = args.next_arg::<c_uint>();
10486                    let b = format_hex(x as u64, false);
10487                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10488                    let mut fbuf = [0u8; 32];
10489                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10490                    for k in 0..len { wc!(fbuf[k]); }
10491                }
10492                b'X' => {
10493                    let x = args.next_arg::<c_uint>();
10494                    let b = format_hex(x as u64, true);
10495                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10496                    let mut fbuf = [0u8; 32];
10497                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10498                    for k in 0..len { wc!(fbuf[k]); }
10499                }
10500                b'o' => {
10501                    let o = args.next_arg::<c_uint>();
10502                    let b = format_octal(o as u64, flags & FLAG_HASH != 0);
10503                    let mut fbuf = [0u8; 32];
10504                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10505                    for k in 0..len { wc!(fbuf[k]); }
10506                }
10507                b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
10508                    let val = args.next_arg::<f64>();
10509                    let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10510                    let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10511                    let mut fbuf = [0u8; 4224];
10512                    let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10513                    let mut wbuf = [0u8; 4224];
10514                    let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10515                    for k in 0..wlen { wc!(wbuf[k]); }
10516                }
10517                b'c' => {
10518                    let ch = args.next_arg::<c_int>();
10519                    wc!(ch as u8);
10520                }
10521                b's' => {
10522                    let p = args.next_arg::<*const c_char>();
10523                    if p.is_null() {
10524                        let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
10525                        if flags & FLAG_MINUS != 0 {
10526                            for k in 0..slen { wc!(b"(null)"[k]); }
10527                            for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10528                        } else {
10529                            for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10530                            for k in 0..slen { wc!(b"(null)"[k]); }
10531                        }
10532                    } else {
10533                        let mut wbuf_local = [0i32; 256];
10534                        let mut wcount = 0usize;
10535                        let mut byte_pos = 0usize;
10536                        let pbytes = p as *const u8;
10537                        loop {
10538                            if precision >= 0 && wcount >= precision as usize { break; }
10539                            if wcount >= 256 { break; }
10540                            let mut wc_val: c_int = 0;
10541                            let consumed = mbrtowc(&mut wc_val as *mut c_int, p.add(byte_pos) as *const c_char, 256, core::ptr::null_mut());
10542                            if consumed == !0usize || consumed == !1usize {
10543                                wbuf_local[wcount] = *pbytes.add(byte_pos) as c_int;
10544                                byte_pos += 1;
10545                                wcount += 1;
10546                            } else if consumed == 0 {
10547                                break;
10548                            } else {
10549                                wbuf_local[wcount] = wc_val;
10550                                byte_pos += consumed;
10551                                wcount += 1;
10552                            }
10553                        }
10554                        if flags & FLAG_MINUS != 0 {
10555                            for k in 0..wcount { wc!(wbuf_local[k]); }
10556                            for _ in 0..width.saturating_sub(wcount) { wc!(b' '); }
10557                        } else {
10558                            for _ in 0..width.saturating_sub(wcount) { wc!(b' '); }
10559                            for k in 0..wcount { wc!(wbuf_local[k]); }
10560                        }
10561                    }
10562                }
10563                b'p' => {
10564                    wc!(b'0'); wc!(b'x');
10565                    let p = args.next_arg::<*const c_void>();
10566                    let b = format_hex(p as u64, false);
10567                    for k in 0..b.1 { wc!(b.0[k]); }
10568                }
10569                b'n' => {
10570                    let p = args.next_arg::<*mut c_void>();
10571                    if !p.is_null() { *(p as *mut c_int) = pos as c_int; }
10572                }
10573                b'%' => { wc!(b'%'); }
10574                _ => { wc!(b'%'); wc!(spec); }
10575            }
10576        }
10577        fi += 1;
10578    }
10579    let null_pos = if pos < cap { pos } else { cap };
10580    *s.add(null_pos) = 0;
10581    if pos > cap { -1 } else { pos as c_int }
10582}
10583
10584#[no_mangle]
10585pub unsafe extern "C" fn swprintf(s: *mut wchar_t, n: usize, fmt: *const wchar_t, args: ...) -> c_int {
10586    vswprintf(s, n, fmt, args)
10587}
10588
10589#[no_mangle]
10590pub unsafe extern "C" fn vfwprintf(f: *mut FILE, fmt: *const wchar_t, args: VaList) -> c_int {
10591    let mut buf = [0i32; 4096];
10592    let r = vswprintf(buf.as_mut_ptr(), 4096, fmt, args);
10593    if r < 0 { return r; }
10594    let mut i = 0;
10595    while i < r as usize {
10596        let mut mb = [0u8; 4];
10597        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, buf[i], core::ptr::null_mut());
10598        if n == !0usize { return -1; }
10599        if fwrite(mb.as_ptr() as *const c_void, 1, n, f) != n { return -1; }
10600        i += 1;
10601    }
10602    r
10603}
10604
10605#[no_mangle]
10606pub unsafe extern "C" fn fwprintf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int {
10607    vfwprintf(f, fmt, args)
10608}
10609
10610// ============================================================
10611// wchar: vswscanf / swscanf / vfwscanf / fwscanf / vwscanf / wscanf
10612// ============================================================
10613
10614// Convert wchar_t format to byte format (ASCII cast, format specifiers are ASCII)
10615unsafe fn wcsfmt_to_mbs(dst: *mut u8, dst_len: usize, src: *const wchar_t) {
10616    let mut i = 0usize;
10617    loop {
10618        let ch = *src.add(i) as u32;
10619        if ch == 0 || i >= dst_len - 1 { break; }
10620        *dst.add(i) = if ch < 128 { ch as u8 } else { b'?' };
10621        i += 1;
10622    }
10623    *dst.add(i) = 0;
10624}
10625
10626#[no_mangle]
10627pub unsafe extern "C" fn vswscanf(s: *const wchar_t, fmt: *const wchar_t, mut args: VaList) -> c_int {
10628    let mut mbs_buf = [0u8; 4096];
10629    let mut i = 0usize;
10630    let mut mb_pos = 0usize;
10631    loop {
10632        let wc = *s.add(i) as c_int;
10633        if wc == 0 { break; }
10634        let mut mb = [0u8; 4];
10635        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, wc, core::ptr::null_mut());
10636        if n == !0usize || n == 0 { break; }
10637        if mb_pos + n >= mbs_buf.len() { break; }
10638        let mut k = 0usize;
10639        while k < n { mbs_buf[mb_pos + k] = mb[k]; k += 1; }
10640        mb_pos += n;
10641        i += 1;
10642    }
10643    mbs_buf[mb_pos] = 0;
10644    let mut mbs_fmt = [0u8; 4096];
10645    wcsfmt_to_mbs(mbs_fmt.as_mut_ptr(), mbs_fmt.len(), fmt);
10646    do_vsscanf(mbs_buf.as_ptr(), mb_pos, mbs_fmt.as_ptr() as *const c_char, &mut args, core::ptr::null_mut())
10647}
10648
10649#[no_mangle]
10650pub unsafe extern "C" fn swscanf(s: *const wchar_t, fmt: *const wchar_t, args: ...) -> c_int {
10651    vswscanf(s, fmt, args)
10652}
10653
10654#[no_mangle]
10655pub unsafe extern "C" fn vfwscanf(f: *mut FILE, fmt: *const wchar_t, mut args: VaList) -> c_int {
10656    let start_pos = ftello(f);
10657    if start_pos < 0 { return -1; }
10658    let mut buf = [0u8; 4096];
10659    let mut n = 0usize;
10660    loop {
10661        if n >= buf.len() - 1 { break; }
10662        let c = fgetc(f);
10663        if c == -1 { break; }
10664        buf[n] = c as u8;
10665        n += 1;
10666    }
10667    buf[n] = 0;
10668    let mut mbs_fmt = [0u8; 4096];
10669    wcsfmt_to_mbs(mbs_fmt.as_mut_ptr(), mbs_fmt.len(), fmt);
10670    let mut consumed = 0usize;
10671    let hit_eof = (*f)._eof != 0;
10672    let result = do_vsscanf(buf.as_ptr(), n, mbs_fmt.as_ptr() as *const c_char, &mut args, &mut consumed);
10673    let _ = fseeko(f, start_pos + consumed as i64, SEEK_SET);
10674    if hit_eof && consumed == n {
10675        (*f)._eof = 1;
10676    }
10677    result
10678}
10679
10680#[no_mangle]
10681pub unsafe extern "C" fn fwscanf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int {
10682    vfwscanf(f, fmt, args)
10683}
10684
10685#[no_mangle]
10686pub unsafe extern "C" fn vwscanf(fmt: *const wchar_t, args: VaList) -> c_int {
10687    vfwscanf(stdin, fmt, args)
10688}
10689
10690#[no_mangle]
10691pub unsafe extern "C" fn wscanf(fmt: *const wchar_t, args: ...) -> c_int {
10692    vfwscanf(stdin, fmt, args)
10693}
10694
10695// ============================================================
10696// Time: internal helpers
10697// ============================================================
10698
10699const LEAPOCH: i64 = 946684800 + 86400 * (31 + 29);
10700const DAYS_PER_400Y: i64 = 365 * 400 + 97;
10701const DAYS_PER_100Y: i64 = 365 * 100 + 24;
10702const DAYS_PER_4Y: i64 = 365 * 4 + 1;
10703
10704const SECS_THROUGH_MONTH: [i32; 12] = [
10705    0, 31*86400, 59*86400, 90*86400, 120*86400, 151*86400,
10706    181*86400, 212*86400, 243*86400, 273*86400, 304*86400, 334*86400,
10707];
10708
10709const DAYS_IN_MONTH: [i32; 12] = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29];
10710
10711unsafe fn year_to_secs(year: i64, is_leap: &mut bool) -> i64 {
10712    // musl compares (year-2) as unsigned: the small-year fast path is only
10713    // valid for 1902..2038.  A signed comparison miscomputes negative years.
10714    if (year.wrapping_sub(2) as u64) <= 136 {
10715        let y = year as i32;
10716        let mut leaps = (y - 68) >> 2;
10717        if (y - 68) & 3 == 0 { leaps -= 1; *is_leap = true; } else { *is_leap = false; }
10718        return 31536000 * (y as i64 - 70) + 86400 * leaps as i64;
10719    }
10720    let mut cycles = ((year - 100) / 400) as i32;
10721    let mut rem = ((year - 100) % 400) as i32;
10722    if rem < 0 { cycles -= 1; rem += 400; }
10723    let (centuries, leaps);
10724    if rem == 0 { *is_leap = true; centuries = 0; leaps = 0; }
10725    else {
10726        let c;
10727        if rem >= 200 { if rem >= 300 { c = 3; rem -= 300; } else { c = 2; rem -= 200; } }
10728        else { if rem >= 100 { c = 1; rem -= 100; } else { c = 0; } }
10729        centuries = c;
10730        if rem == 0 { *is_leap = false; leaps = 0; }
10731        else { leaps = rem / 4; rem %= 4; *is_leap = rem == 0; }
10732    }
10733    let total_leaps = leaps + 97 * cycles + 24 * centuries - (*is_leap as i32);
10734    (year - 100) * 31536000 + total_leaps as i64 * 86400 + 946684800 + 86400
10735}
10736
10737fn month_to_secs(month: i32, is_leap: bool) -> i32 {
10738    let mut t = SECS_THROUGH_MONTH[month as usize];
10739    if is_leap && month >= 2 { t += 86400; }
10740    t
10741}
10742
10743unsafe fn secs_to_tm(t: i64, tm: &mut tm) -> bool {
10744    if t < (i32::MIN as i64) * 31622400 || t > (i32::MAX as i64) * 31622400 { return false; }
10745    let secs = t - LEAPOCH;
10746    let mut days = secs / 86400;
10747    let mut remsecs = (secs % 86400) as i32;
10748    if remsecs < 0 { remsecs += 86400; days -= 1; }
10749    let mut wday = ((3 + days) % 7) as i32;
10750    if wday < 0 { wday += 7; }
10751    let mut qc_cycles = (days / DAYS_PER_400Y) as i32;
10752    let mut remdays = (days % DAYS_PER_400Y) as i32;
10753    if remdays < 0 { remdays += DAYS_PER_400Y as i32; qc_cycles -= 1; }
10754    let mut c_cycles = remdays / DAYS_PER_100Y as i32;
10755    if c_cycles == 4 { c_cycles -= 1; }
10756    remdays -= c_cycles * DAYS_PER_100Y as i32;
10757    let mut q_cycles = remdays / DAYS_PER_4Y as i32;
10758    if q_cycles == 25 { q_cycles -= 1; }
10759    remdays -= q_cycles * DAYS_PER_4Y as i32;
10760    let mut remyears = remdays / 365;
10761    if remyears == 4 { remyears -= 1; }
10762    remdays -= remyears * 365;
10763    let leap = remyears == 0 && (q_cycles != 0 || c_cycles == 0);
10764    let mut yday = remdays + 31 + 28 + leap as i32;
10765    if yday >= 365 + leap as i32 { yday -= 365 + leap as i32; }
10766    let years = remyears as i64 + 4 * q_cycles as i64 + 100 * c_cycles as i64 + 400 * qc_cycles as i64;
10767    let mut months = 0i32;
10768    let mut rd = remdays;
10769    for m in 0..12 {
10770        if DAYS_IN_MONTH[m] <= rd { rd -= DAYS_IN_MONTH[m]; } else { months = m as i32; break; }
10771    }
10772    let mut adj_years = years;
10773    if months >= 10 { months -= 12; adj_years += 1; }
10774    if adj_years + 100 > i32::MAX as i64 || adj_years + 100 < i32::MIN as i64 { return false; }
10775    tm.tm_year = (adj_years + 100) as c_int;
10776    tm.tm_mon = months + 2;
10777    tm.tm_mday = rd + 1;
10778    tm.tm_wday = wday;
10779    tm.tm_yday = yday;
10780    tm.tm_hour = remsecs / 3600;
10781    tm.tm_min = remsecs / 60 % 60;
10782    tm.tm_sec = remsecs % 60;
10783    true
10784}
10785
10786unsafe fn tm_to_secs(tm: *const tm) -> i64 {
10787    let mut year = (*tm).tm_year as i64;
10788    let mut month = (*tm).tm_mon;
10789    if month >= 12 || month < 0 {
10790        let adj = month / 12;
10791        month %= 12;
10792        if month < 0 { month += 12; }
10793        year += adj as i64;
10794    }
10795    let mut is_leap = false;
10796    let mut t = year_to_secs(year, &mut is_leap);
10797    t += month_to_secs(month, is_leap) as i64;
10798    t += 86400 * ((*tm).tm_mday - 1) as i64;
10799    t += 3600 * (*tm).tm_hour as i64;
10800    t += 60 * (*tm).tm_min as i64;
10801    t += (*tm).tm_sec as i64;
10802    t
10803}
10804
10805static mut TM_BUF: tm = tm {
10806    tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0,
10807    tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0,
10808    tm_gmtoff: 0, tm_zone: core::ptr::null(),
10809};
10810
10811static mut UTC_STR: [c_char; 4] = [b'U' as c_char, b'T' as c_char, b'C' as c_char, 0];
10812
10813const CLOCK_PROCESS_CPUTIME_ID: c_int = 2;
10814
10815// ============================================================
10816// Time: core functions
10817// ============================================================
10818
10819#[no_mangle]
10820pub unsafe extern "C" fn time(t: *mut TimeT) -> TimeT {
10821    let mut ts: timespec = core::mem::zeroed();
10822    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
10823    if !t.is_null() { *t = ts.tv_sec; }
10824    ts.tv_sec
10825}
10826
10827#[no_mangle]
10828pub unsafe extern "C" fn difftime(t1: TimeT, t0: TimeT) -> f64 {
10829    (t1 as i64 - t0 as i64) as f64
10830}
10831
10832#[no_mangle]
10833pub unsafe extern "C" fn clock() -> ClockT {
10834    let mut ts: timespec = core::mem::zeroed();
10835    let _ = sys_clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut ts);
10836    ts.tv_sec * 1000000 + ts.tv_nsec / 1000
10837}
10838
10839#[no_mangle]
10840pub unsafe extern "C" fn gmtime(t: *const TimeT) -> *mut tm {
10841    gmtime_r(t, &raw mut TM_BUF)
10842}
10843
10844#[no_mangle]
10845pub unsafe extern "C" fn gmtime_r(t: *const TimeT, tm: *mut tm) -> *mut tm {
10846    if !secs_to_tm(*t as i64, &mut *tm) { ERRNO!() = EOVERFLOW; return core::ptr::null_mut(); }
10847    (*tm).tm_isdst = 0;
10848    (*tm).tm_gmtoff = 0;
10849    (*tm).tm_zone = core::ptr::addr_of!(UTC_STR).cast::<c_char>();
10850    tm
10851}
10852
10853#[no_mangle]
10854pub unsafe extern "C" fn localtime(t: *const TimeT) -> *mut tm {
10855    tz_localtime_r(t, &raw mut TM_BUF)
10856}
10857
10858#[no_mangle]
10859pub unsafe extern "C" fn localtime_r(t: *const TimeT, tm: *mut tm) -> *mut tm {
10860    tz_localtime_r(t, tm)
10861}
10862
10863#[no_mangle]
10864pub unsafe extern "C" fn mktime(tm: *mut tm) -> TimeT {
10865    tz_mktime(tm)
10866}
10867
10868#[no_mangle]
10869pub unsafe extern "C" fn timegm(tm: *mut tm) -> TimeT {
10870    let t = tm_to_secs(tm as *const tm);
10871    if !secs_to_tm(t, &mut *tm) { ERRNO!() = EOVERFLOW; return -1; }
10872    (*tm).tm_isdst = 0;
10873    (*tm).tm_gmtoff = 0;
10874    (*tm).tm_zone = core::ptr::addr_of!(UTC_STR).cast::<c_char>();
10875    t as TimeT
10876}
10877
10878static mut ASCTIME_BUF: [c_char; 26] = [0; 26];
10879
10880const 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"];
10881const 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"];
10882
10883#[no_mangle]
10884pub unsafe extern "C" fn asctime(tm: *const tm) -> *mut c_char {
10885    asctime_r(tm, core::ptr::addr_of_mut!(ASCTIME_BUF).cast::<c_char>())
10886}
10887
10888#[no_mangle]
10889pub unsafe extern "C" fn asctime_r(tm: *const tm, buf: *mut c_char) -> *mut c_char {
10890    let wday = if (*tm).tm_wday >= 0 && (*tm).tm_wday < 7 { (*tm).tm_wday as usize } else { 0 };
10891    let mon = if (*tm).tm_mon >= 0 && (*tm).tm_mon < 12 { (*tm).tm_mon as usize } else { 0 };
10892    let dn = DAY_NAMES[wday];
10893    let mn = MON_NAMES[mon];
10894    let mut p = 0;
10895    for k in 0..3 { *buf.add(p) = *dn.as_ptr().add(k) as c_char; p += 1; }
10896    *buf.add(p) = b' ' as c_char; p += 1;
10897    for k in 0..3 { *buf.add(p) = *mn.as_ptr().add(k) as c_char; p += 1; }
10898    *buf.add(p) = b' ' as c_char; p += 1;
10899    // %.3s %.3s%3d: the day is right-aligned in a three-column field.
10900    let v = (*tm).tm_mday;
10901    if v < 10 {
10902        *buf.add(p) = b' ' as c_char; p += 1;
10903        *buf.add(p) = b' ' as c_char; p += 1;
10904        *buf.add(p) = (b'0' + v as u8) as c_char; p += 1;
10905    } else if v < 100 {
10906        *buf.add(p) = b' ' as c_char; p += 1;
10907        *buf.add(p) = (b'0' + (v / 10) as u8) as c_char; p += 1;
10908        *buf.add(p) = (b'0' + (v % 10) as u8) as c_char; p += 1;
10909    } else {
10910        *buf.add(p) = (b'0' + (v / 100) as u8) as c_char; p += 1;
10911        *buf.add(p) = (b'0' + ((v / 10) % 10) as u8) as c_char; p += 1;
10912        *buf.add(p) = (b'0' + (v % 10) as u8) as c_char; p += 1;
10913    }
10914    *buf.add(p) = b' ' as c_char; p += 1;
10915    let hh = (*tm).tm_hour;
10916    *buf.add(p) = (b'0' + (hh / 10) as u8) as c_char; p += 1;
10917    *buf.add(p) = (b'0' + (hh % 10) as u8) as c_char; p += 1;
10918    *buf.add(p) = b':' as c_char; p += 1;
10919    let mm = (*tm).tm_min;
10920    *buf.add(p) = (b'0' + (mm / 10) as u8) as c_char; p += 1;
10921    *buf.add(p) = (b'0' + (mm % 10) as u8) as c_char; p += 1;
10922    *buf.add(p) = b':' as c_char; p += 1;
10923    let ss = (*tm).tm_sec;
10924    *buf.add(p) = (b'0' + (ss / 10) as u8) as c_char; p += 1;
10925    *buf.add(p) = (b'0' + (ss % 10) as u8) as c_char; p += 1;
10926    *buf.add(p) = b' ' as c_char; p += 1;
10927    // %d: negative and >4-digit years are valid in musl asctime.
10928    let yr = (*tm).tm_year as i64 + 1900;
10929    let mut tmp = [0u8; 16];
10930    let mut n = 0usize;
10931    let mut v2 = if yr < 0 { -yr } else { yr };
10932    if v2 == 0 {
10933        tmp[n] = b'0';
10934        n += 1;
10935    } else {
10936        while v2 > 0 && n < tmp.len() {
10937            tmp[n] = b'0' + (v2 % 10) as u8;
10938            v2 /= 10;
10939            n += 1;
10940        }
10941    }
10942    if yr < 0 {
10943        *buf.add(p) = b'-' as c_char;
10944        p += 1;
10945    }
10946    for k in (0..n).rev() {
10947        *buf.add(p) = tmp[k] as c_char;
10948        p += 1;
10949    }
10950    *buf.add(p) = b'\n' as c_char; p += 1;
10951    *buf.add(p) = 0;
10952    buf
10953}
10954
10955#[no_mangle]
10956pub unsafe extern "C" fn ctime(t: *const TimeT) -> *mut c_char {
10957    let tm = localtime(t);
10958    if tm.is_null() { core::ptr::null_mut() } else { asctime(tm) }
10959}
10960
10961#[no_mangle]
10962pub unsafe extern "C" fn ctime_r(t: *const TimeT, buf: *mut c_char) -> *mut c_char {
10963    let mut tmp: tm = core::mem::zeroed();
10964    if localtime_r(t, &mut tmp).is_null() { core::ptr::null_mut() } else { asctime_r(&tmp, buf) }
10965}
10966
10967// ============================================================
10968// Time: clock_getres / clock_settime / clock_nanosleep / gettimeofday
10969// ============================================================
10970
10971unsafe fn sys_clock_getres(clockid: c_int, ts: *mut timespec) -> i64 {
10972    <Arch as Syscalls>::syscall2(SYS_CLOCK_GETRES, clockid as i64, ts as i64)
10973}
10974
10975unsafe fn sys_clock_settime(clockid: c_int, ts: *const timespec) -> i64 {
10976    <Arch as Syscalls>::syscall2(SYS_CLOCK_SETTIME, clockid as i64, ts as i64)
10977}
10978
10979unsafe fn sys_clock_nanosleep(clockid: c_int, flags: c_int, req: *const timespec, rem: *mut timespec) -> i64 {
10980    <Arch as Syscalls>::syscall4(SYS_CLOCK_NANOSLEEP, clockid as i64, flags as i64, req as i64, rem as i64)
10981}
10982
10983#[no_mangle]
10984pub unsafe extern "C" fn clock_getres(clockid: c_int, ts: *mut timespec) -> c_int {
10985    let r = sys_clock_getres(clockid, ts);
10986    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
10987}
10988
10989#[no_mangle]
10990pub unsafe extern "C" fn clock_settime(clockid: c_int, ts: *const timespec) -> c_int {
10991    let r = sys_clock_settime(clockid, ts);
10992    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
10993}
10994
10995#[no_mangle]
10996pub unsafe extern "C" fn clock_nanosleep(clockid: c_int, flags: c_int, req: *const timespec, rem: *mut timespec) -> c_int {
10997    let r = sys_clock_nanosleep(clockid, flags, req, rem);
10998    if r < 0 {
10999        let e = (-r) as c_int;
11000        // The kernel returns EOPNOTSUPP for CLOCK_THREAD_CPUTIME_ID;
11001        // POSIX/musl report EINVAL instead.
11002        if clockid == 3 && e == 95 { return 22; }
11003        e
11004    } else {
11005        0
11006    }
11007}
11008
11009#[no_mangle]
11010pub unsafe extern "C" fn gettimeofday(tv: *mut timeval, _tz: *mut c_void) -> c_int {
11011    if tv.is_null() { return 0; }
11012    let mut ts: timespec = core::mem::zeroed();
11013    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
11014    (*tv).tv_sec = ts.tv_sec;
11015    (*tv).tv_usec = ts.tv_nsec / 1000;
11016    0
11017}
11018
11019// ============================================================
11020// Time: strftime
11021// ============================================================
11022
11023fn is_leap_year(y: i32) -> bool {
11024    let yr = if y > i32::MAX - 1900 { y - 2000 } else { y + 1900 };
11025    yr % 4 == 0 && (yr % 100 != 0 || yr % 400 == 0)
11026}
11027
11028fn week_num(tm: &tm) -> i32 {
11029    let mut val = (tm.tm_yday + 7 - ((tm.tm_wday + 6) % 7)) / 7;
11030    if (tm.tm_wday + 371 - tm.tm_yday - 2).rem_euclid(7) <= 2 { val += 1; }
11031    if val == 0 {
11032        val = 52;
11033        let dec31 = (tm.tm_wday + 7 - tm.tm_yday - 1).rem_euclid(7);
11034        if dec31 == 4 || (dec31 == 5 && is_leap_year(tm.tm_year % 400 - 1)) { val += 1; }
11035    } else if val == 53 {
11036        let jan1 = (tm.tm_wday + 371 - tm.tm_yday).rem_euclid(7);
11037        if jan1 != 4 && (jan1 != 3 || !is_leap_year(tm.tm_year)) { val = 1; }
11038    }
11039    val
11040}
11041
11042// Langinfo constants for strftime
11043const ABDAY_1: c_int = 0x20000;
11044const DAY_1: c_int = 0x20007;
11045const ABMON_1: c_int = 0x2000E;
11046const MON_1: c_int = 0x2001A;
11047const AM_STR_LI: c_int = 0x20026;
11048const PM_STR_LI: c_int = 0x20027;
11049const D_T_FMT: c_int = 0x20028;
11050const D_FMT: c_int = 0x20029;
11051const T_FMT: c_int = 0x2002A;
11052const T_FMT_AMPM: c_int = 0x2002B;
11053
11054// Format an i64 into buf as decimal with zero/sign padding. Returns (ptr_to_start, length).
11055// pad: '-' = no pad, '_' = space pad, '0' or 0 = zero pad. width: minimum digits (excluding sign).
11056unsafe fn num_fmt(buf: &mut [u8; 100], val: i64, pad: u8, width: usize) -> (*const u8, usize) {
11057    let negative = val < 0;
11058    let mut v = if negative { -val as u64 } else { val as u64 };
11059    let mut tmp = [0u8; 24];
11060    let mut pos = 24usize;
11061    if v == 0 { pos -= 1; tmp[pos] = b'0'; }
11062    while v > 0 { pos -= 1; tmp[pos] = b'0' + (v % 10) as u8; v /= 10; }
11063    let digits = 24 - pos;
11064    let sign_chars = if negative { 1 } else { 0 };
11065    let needed = sign_chars + digits;
11066    let fill = if width > needed { width - needed } else { 0 };
11067    let total = fill + needed;
11068    let mut p = 0usize;
11069    match pad {
11070        b'-' => { /* no fill */ }
11071        b'_' => {
11072            for _ in 0..fill { buf[p] = b' '; p += 1; }
11073            if negative { buf[p] = b'-'; p += 1; }
11074        }
11075        _ => {
11076            if negative { buf[p] = b'-'; p += 1; }
11077            for _ in 0..fill { buf[p] = b'0'; p += 1; }
11078        }
11079    }
11080    for i in 0..digits { buf[p] = tmp[pos + i]; p += 1; }
11081    (buf.as_ptr(), total)
11082}
11083
11084// Copy a null-terminated C string into buf. Returns (ptr, len).
11085unsafe fn str_to_buf(buf: &mut [u8; 100], s: *const c_char) -> (*const u8, usize) {
11086    let mut k = 0usize;
11087    while *s.add(k) != 0 {
11088        buf[k] = *s.add(k) as u8;
11089        k += 1;
11090    }
11091    (buf.as_ptr(), k)
11092}
11093
11094// Core format dispatcher. Returns (ptr, len) where ptr points into buf or a static string.
11095// pad=0 means use default; returns (null, 0) for unknown specifiers.
11096unsafe fn __strftime_fmt_1(buf: &mut [u8; 100], f: u8, tm: *const tm, pad: u8) -> (*const u8, usize) {
11097    let mut val: i64;
11098    let mut width: usize = 2;
11099    let mut def_pad: u8 = b'0';
11100    let fmt: *const c_char;
11101
11102    match f {
11103        b'a' => {
11104            if (*tm).tm_wday as u32 > 6 { return (b"\0".as_ptr(), 0); }
11105            let p = nl_langinfo(ABDAY_1 + (*tm).tm_wday);
11106            return str_to_buf(buf, p);
11107        }
11108        b'A' => {
11109            if (*tm).tm_wday as u32 > 6 { return (b"\0".as_ptr(), 0); }
11110            let p = nl_langinfo(DAY_1 + (*tm).tm_wday);
11111            return str_to_buf(buf, p);
11112        }
11113        b'h' | b'b' => {
11114            if (*tm).tm_mon as u32 > 11 { return (b"\0".as_ptr(), 0); }
11115            let p = nl_langinfo(ABMON_1 + (*tm).tm_mon);
11116            return str_to_buf(buf, p);
11117        }
11118        b'B' => {
11119            if (*tm).tm_mon as u32 > 11 { return (b"\0".as_ptr(), 0); }
11120            let p = nl_langinfo(MON_1 + (*tm).tm_mon);
11121            return str_to_buf(buf, p);
11122        }
11123        b'c' => {
11124            let p = nl_langinfo(D_T_FMT);
11125            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11126            return (buf.as_ptr(), l);
11127        }
11128        b'C' => {
11129            val = (1900i64 + (*tm).tm_year as i64) / 100;
11130            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11131        }
11132        b'e' => { def_pad = b'_'; }
11133        b'd' => {
11134            val = (*tm).tm_mday as i64;
11135            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11136        }
11137        b'D' => {
11138            fmt = b"%m/%d/%y\0".as_ptr() as *const c_char;
11139            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11140            return (buf.as_ptr(), l);
11141        }
11142        b'F' => {
11143            fmt = b"%Y-%m-%d\0".as_ptr() as *const c_char;
11144            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11145            return (buf.as_ptr(), l);
11146        }
11147        b'g' | b'G' => {
11148            val = (*tm).tm_year as i64 + 1900;
11149            if (*tm).tm_yday < 3 && week_num(&*tm) != 1 { val -= 1; }
11150            else if (*tm).tm_yday > 360 && week_num(&*tm) == 1 { val += 1; }
11151            if f == b'g' { val %= 100; }
11152            else { width = 4; }
11153            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11154        }
11155        b'H' => {
11156            val = (*tm).tm_hour as i64;
11157            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11158        }
11159        b'I' => {
11160            val = (*tm).tm_hour as i64;
11161            if val == 0 { val = 12; }
11162            else if val > 12 { val -= 12; }
11163            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11164        }
11165        b'j' => {
11166            val = (*tm).tm_yday as i64 + 1;
11167            width = 3;
11168            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11169        }
11170        b'm' => {
11171            val = (*tm).tm_mon as i64 + 1;
11172            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11173        }
11174        b'M' => {
11175            val = (*tm).tm_min as i64;
11176            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11177        }
11178        b'n' => { buf[0] = b'\n'; return (buf.as_ptr(), 1); }
11179        b'p' => {
11180            let p = if (*tm).tm_hour >= 12 { nl_langinfo(PM_STR_LI) } else { nl_langinfo(AM_STR_LI) };
11181            return str_to_buf(buf, p);
11182        }
11183        b'r' => {
11184            let p = nl_langinfo(T_FMT_AMPM);
11185            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11186            return (buf.as_ptr(), l);
11187        }
11188        b'R' => {
11189            fmt = b"%H:%M\0".as_ptr() as *const c_char;
11190            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11191            return (buf.as_ptr(), l);
11192        }
11193        b's' => {
11194            val = tm_to_secs(tm) - (*tm).tm_gmtoff as i64;
11195            width = 1;
11196            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11197        }
11198        b'S' => {
11199            val = (*tm).tm_sec as i64;
11200            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11201        }
11202        b't' => { buf[0] = b'\t'; return (buf.as_ptr(), 1); }
11203        b'T' => {
11204            fmt = b"%H:%M:%S\0".as_ptr() as *const c_char;
11205            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11206            return (buf.as_ptr(), l);
11207        }
11208        b'u' => {
11209            val = if (*tm).tm_wday != 0 { (*tm).tm_wday as i64 } else { 7 };
11210            width = 1;
11211            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11212        }
11213        b'U' => {
11214            val = ((*tm).tm_yday as u64 + 7 - (*tm).tm_wday as u64) as i64 / 7;
11215            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11216        }
11217        b'W' => {
11218            val = ((*tm).tm_yday as u64 + 7 - ((*tm).tm_wday as u64 + 6) % 7) as i64 / 7;
11219            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11220        }
11221        b'V' => {
11222            val = week_num(&*tm) as i64;
11223            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11224        }
11225        b'w' => {
11226            val = (*tm).tm_wday as i64;
11227            width = 1;
11228            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11229        }
11230        b'x' => {
11231            let p = nl_langinfo(D_FMT);
11232            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11233            return (buf.as_ptr(), l);
11234        }
11235        b'X' => {
11236            let p = nl_langinfo(T_FMT);
11237            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11238            return (buf.as_ptr(), l);
11239        }
11240        b'y' => {
11241            val = (1900i64 + (*tm).tm_year as i64) % 100;
11242            if val < 0 { val = -val; }
11243            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11244        }
11245        b'Y' => {
11246            val = (*tm).tm_year as i64 + 1900;
11247            if val >= 10000 {
11248                let mut tmp = [0u8; 100];
11249                let (_, k) = num_fmt(&mut tmp, val, b'-', 1);
11250                buf[0] = b'+';
11251                for i in 0..k { buf[1 + i] = tmp[i]; }
11252                return (buf.as_ptr(), 1 + k);
11253            }
11254            width = 4;
11255            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11256        }
11257        b'z' => {
11258            if (*tm).tm_isdst < 0 { return (b"\0".as_ptr(), 0); }
11259            let gmtoff = (*tm).tm_gmtoff as i64;
11260            let sign = if gmtoff >= 0 { b'+' } else { b'-' };
11261            let off = if gmtoff < 0 { -gmtoff } else { gmtoff };
11262            let hh = (off / 3600) as i32;
11263            let mm = ((off % 3600) / 60) as i32;
11264            buf[0] = sign;
11265            buf[1] = b'0' + (hh / 10) as u8;
11266            buf[2] = b'0' + (hh % 10) as u8;
11267            buf[3] = b'0' + (mm / 10) as u8;
11268            buf[4] = b'0' + (mm % 10) as u8;
11269            return (buf.as_ptr(), 5);
11270        }
11271        b'Z' => {
11272            if (*tm).tm_isdst < 0 || (*tm).tm_zone.is_null() { return (b"\0".as_ptr(), 0); }
11273            return str_to_buf(buf, (*tm).tm_zone);
11274        }
11275        b'%' => { buf[0] = b'%'; return (buf.as_ptr(), 1); }
11276        _ => { return (core::ptr::null(), 0); }
11277    }
11278    // fallthrough for 'e' (def_pad='_', same logic as 'd')
11279    val = (*tm).tm_mday as i64;
11280    num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width)
11281}
11282
11283unsafe fn __strftime_l(s: *mut c_char, n: usize, f: *const c_char, tm: *const tm) -> usize {
11284    let mut l: usize = 0;
11285    let mut fi: usize = 0;
11286    while l < n {
11287        let ch = *f.add(fi) as u8;
11288        if ch == 0 {
11289            *s.add(l) = 0;
11290            return l;
11291        }
11292        if ch != b'%' {
11293            *s.add(l) = ch as c_char;
11294            l += 1;
11295            fi += 1;
11296            continue;
11297        }
11298        fi += 1;
11299        // Parse flags
11300        let mut pad: u8 = 0;
11301        let fc = *f.add(fi) as u8;
11302        if fc == b'-' || fc == b'_' || fc == b'0' { pad = fc; fi += 1; }
11303        let plus = *f.add(fi) as u8 == b'+';
11304        if plus { fi += 1; }
11305        // Parse width
11306        let mut width: usize = 0;
11307        let mut p_idx = fi;
11308        {
11309            let fc2 = *f.add(fi) as u8;
11310            if fc2 >= b'0' && fc2 <= b'9' {
11311                let mut w: usize = 0;
11312                while { let c = *f.add(p_idx) as u8; c >= b'0' && c <= b'9' } {
11313                    w = w * 10 + (*f.add(p_idx) as usize - b'0' as usize);
11314                    p_idx += 1;
11315                }
11316                width = w;
11317            }
11318        }
11319        let spec_ch = *f.add(p_idx) as u8;
11320        if spec_ch == b'C' || spec_ch == b'F' || spec_ch == b'G' || spec_ch == b'Y' {
11321            if width == 0 && p_idx != fi { width = 1; }
11322        } else {
11323            width = 0;
11324        }
11325        fi = p_idx;
11326        // Skip E/O modifier
11327        let fc3 = *f.add(fi) as u8;
11328        if fc3 == b'E' || fc3 == b'O' { fi += 1; }
11329        let fch = *f.add(fi) as u8;
11330        // Call formatter
11331        let mut buf = [0u8; 100];
11332        let (t, k) = __strftime_fmt_1(&mut buf, fch, tm, pad);
11333        if t.is_null() { break; }
11334        let mut k = k;
11335        let mut t = t;
11336        if width != 0 {
11337            // Strip sign and leading zeros, count remaining digits
11338            if *t == b'+' || *t == b'-' { t = t.add(1); k -= 1; }
11339            while k > 0 && *t == b'0' && k > 1 && *t.add(1) >= b'0' && *t.add(1) <= b'9' {
11340                t = t.add(1); k -= 1;
11341            }
11342            if width < k { width = k; }
11343            let mut d: usize = 0;
11344            while d < k && *t.add(d) >= b'0' && *t.add(d) <= b'9' { d += 1; }
11345            if (*tm).tm_year < -1900 {
11346                if l < n { *s.add(l) = b'-' as c_char; }
11347                l += 1;
11348                width -= 1;
11349            } else if plus && d + (width - k) >= (if spec_ch == b'C' { 3 } else { 5 }) {
11350                if l < n { *s.add(l) = b'+' as c_char; }
11351                l += 1;
11352                width -= 1;
11353            }
11354            while width > k && l < n {
11355                *s.add(l) = b'0' as c_char;
11356                l += 1;
11357                width -= 1;
11358            }
11359        }
11360        let copy = if k > n - l { n - l } else { k };
11361        core::ptr::copy_nonoverlapping(t, s.add(l) as *mut u8, copy);
11362        l += copy;
11363        fi += 1;
11364    }
11365    if n > 0 {
11366        if l == n { l = n - 1; }
11367        *s.add(l) = 0;
11368    }
11369    0
11370}
11371
11372#[no_mangle]
11373pub unsafe extern "C" fn strftime(s: *mut c_char, maxsize: usize, fmt: *const c_char, tm: *const tm) -> usize {
11374    __strftime_l(s, maxsize, fmt, tm)
11375}
11376
11377// ============================================================
11378// Time: strptime
11379// ============================================================
11380
11381unsafe fn match_prefix(s: *const u8, prefix: &[u8]) -> bool {
11382    for i in 0..prefix.len() {
11383        if *s.add(i) == 0 || *s.add(i) != prefix[i] { return false; }
11384    }
11385    true
11386}
11387
11388unsafe fn match_ci_prefix(s: *const u8, prefix: &[u8]) -> bool {
11389    for i in 0..prefix.len() {
11390        let c = *s.add(i);
11391        if c == 0 { return false; }
11392        if c.to_ascii_lowercase() != prefix[i].to_ascii_lowercase() { return false; }
11393    }
11394    true
11395}
11396
11397unsafe fn parse_int(p: *const u8, max_digits: usize) -> (i32, *const u8) {
11398    let mut val = 0i32;
11399    let mut np = p;
11400    let mut count = 0;
11401    while *np >= b'0' && *np <= b'9' && count < max_digits {
11402        val = val * 10 + (*np - b'0') as i32;
11403        np = np.add(1);
11404        count += 1;
11405    }
11406    if count == 0 { (0, p) } else { (val, np) }
11407}
11408
11409unsafe fn parse_range(p: *const u8, min: i32, max: i32) -> (i32, *const u8) {
11410    let (val, np) = parse_int(p, 4);
11411    if np == p || val < min || val > max { (0, p) } else { (val, np) }
11412}
11413
11414fn is_ascii_space(c: u8) -> bool {
11415    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == 0x0c || c == 0x0b
11416}
11417
11418#[no_mangle]
11419pub unsafe extern "C" fn strptime(s: *const c_char, fmt: *const c_char, tm: *mut tm) -> *mut c_char {
11420    let mut p = s as *const u8;
11421    let mut f = fmt as *const u8;
11422    let mut want_century = 0i32;
11423    let mut century = 0i32;
11424    let mut relyear = 0i32;
11425    while *f != 0 {
11426        if *f != b'%' {
11427            if is_ascii_space(*f) {
11428                while *p != 0 && is_ascii_space(*p) { p = p.add(1); }
11429            } else {
11430                if *p != *f { return core::ptr::null_mut(); }
11431                p = p.add(1);
11432            }
11433            f = f.add(1);
11434            continue;
11435        }
11436        f = f.add(1);
11437        if *f == b'+' { f = f.add(1); }
11438        while *f >= b'0' && *f <= b'9' { f = f.add(1); }
11439        if *f == b'E' || *f == b'O' { f = f.add(1); }
11440        match *f {
11441            b'a' | b'A' => {
11442                let mut found = false;
11443                for i in 0..7 {
11444                    let names: [&[u8]; 7] = [b"Sunday", b"Monday", b"Tuesday", b"Wednesday", b"Thursday", b"Friday", b"Saturday"];
11445                    let snames: [&[u8]; 7] = [b"Sun", b"Mon", b"Tue", b"Wed", b"Thu", b"Fri", b"Sat"];
11446                    if match_prefix(p, names[i]) { (*tm).tm_wday = i as c_int; p = p.add(names[i].len()); found = true; break; }
11447                    if match_prefix(p, snames[i]) { (*tm).tm_wday = i as c_int; p = p.add(snames[i].len()); found = true; break; }
11448                }
11449                if !found { return core::ptr::null_mut(); }
11450            }
11451            b'b' | b'B' | b'h' => {
11452                let mut found = false;
11453                for i in 0..12 {
11454                    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"];
11455                    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"];
11456                    if match_prefix(p, names[i]) { (*tm).tm_mon = i as c_int; p = p.add(names[i].len()); found = true; break; }
11457                    if match_prefix(p, snames[i]) { (*tm).tm_mon = i as c_int; p = p.add(snames[i].len()); found = true; break; }
11458                }
11459                if !found { return core::ptr::null_mut(); }
11460            }
11461            b'C' => {
11462                let (v, np) = parse_int(p, 2);
11463                if np == p { return core::ptr::null_mut(); }
11464                century = v;
11465                want_century |= 2;
11466                p = np;
11467            }
11468            b'd' | b'e' => {
11469                let (v, np) = parse_range(p, 1, 31);
11470                if np == p { return core::ptr::null_mut(); }
11471                (*tm).tm_mday = v;
11472                p = np;
11473            }
11474            b'D' => {
11475                let r = strptime(p as *const c_char, b"%m/%d/%y\0".as_ptr() as *const c_char, tm);
11476                if r.is_null() { return core::ptr::null_mut(); }
11477                p = r as *const u8;
11478            }
11479            b'F' => {
11480                let (yv, ynp) = parse_int(p, 4);
11481                if ynp == p { return core::ptr::null_mut(); }
11482                (*tm).tm_year = yv - 1900;
11483                p = ynp;
11484                if *p != b'-' { return core::ptr::null_mut(); }
11485                p = p.add(1);
11486                let (mv, mnp) = parse_range(p, 1, 12);
11487                if mnp == p { return core::ptr::null_mut(); }
11488                (*tm).tm_mon = mv - 1;
11489                p = mnp;
11490                if *p != b'-' { return core::ptr::null_mut(); }
11491                p = p.add(1);
11492                let (dv, dnp) = parse_range(p, 1, 31);
11493                if dnp == p { return core::ptr::null_mut(); }
11494                (*tm).tm_mday = dv;
11495                p = dnp;
11496            }
11497            b'H' | b'I' => {
11498                let (v, np) = parse_range(p, 0, 23);
11499                if np == p { return core::ptr::null_mut(); }
11500                (*tm).tm_hour = v;
11501                p = np;
11502            }
11503            b'j' => {
11504                let (v, np) = parse_range(p, 1, 366);
11505                if np == p { return core::ptr::null_mut(); }
11506                (*tm).tm_yday = v - 1;
11507                p = np;
11508            }
11509            b'm' => {
11510                let (v, np) = parse_range(p, 1, 12);
11511                if np == p { return core::ptr::null_mut(); }
11512                (*tm).tm_mon = v - 1;
11513                p = np;
11514            }
11515            b'M' => {
11516                let (v, np) = parse_range(p, 0, 59);
11517                if np == p { return core::ptr::null_mut(); }
11518                (*tm).tm_min = v;
11519                p = np;
11520            }
11521            b'n' | b't' => {
11522                while *p != 0 && is_ascii_space(*p) { p = p.add(1); }
11523            }
11524            b'p' => {
11525                if match_ci_prefix(p, b"AM") {
11526                    if (*tm).tm_hour == 12 { (*tm).tm_hour = 0; }
11527                    p = p.add(2);
11528                } else if match_ci_prefix(p, b"PM") {
11529                    if (*tm).tm_hour < 12 { (*tm).tm_hour += 12; }
11530                    p = p.add(2);
11531                } else { return core::ptr::null_mut(); }
11532            }
11533            b'r' => {
11534                let r = strptime(p as *const c_char, b"%I:%M:%S %p\0".as_ptr() as *const c_char, tm);
11535                if r.is_null() { return core::ptr::null_mut(); }
11536                p = r as *const u8;
11537            }
11538            b'R' => {
11539                let r = strptime(p as *const c_char, b"%H:%M\0".as_ptr() as *const c_char, tm);
11540                if r.is_null() { return core::ptr::null_mut(); }
11541                p = r as *const u8;
11542            }
11543            b's' => {
11544                let neg = if *p == b'-' { p = p.add(1); true } else { false };
11545                if *p < b'0' || *p > b'9' { return core::ptr::null_mut(); }
11546                let mut val = 0i64;
11547                while *p >= b'0' && *p <= b'9' {
11548                    val = val * 10 + (*p - b'0') as i64;
11549                    p = p.add(1);
11550                }
11551                if neg { val = -val; }
11552                secs_to_tm(val, &mut *tm);
11553            }
11554            b'S' => {
11555                let (v, np) = parse_range(p, 0, 60);
11556                if np == p { return core::ptr::null_mut(); }
11557                (*tm).tm_sec = v;
11558                p = np;
11559            }
11560            b'T' => {
11561                let r = strptime(p as *const c_char, b"%H:%M:%S\0".as_ptr() as *const c_char, tm);
11562                if r.is_null() { return core::ptr::null_mut(); }
11563                p = r as *const u8;
11564            }
11565            b'U' | b'W' => {
11566                let (_, np) = parse_range(p, 0, 53);
11567                if np == p { return core::ptr::null_mut(); }
11568                p = np;
11569            }
11570            b'V' => {
11571                let (_, np) = parse_range(p, 1, 53);
11572                if np == p { return core::ptr::null_mut(); }
11573                p = np;
11574            }
11575            b'w' => {
11576                let (v, np) = parse_range(p, 0, 6);
11577                if np == p { return core::ptr::null_mut(); }
11578                (*tm).tm_wday = v;
11579                p = np;
11580            }
11581            b'y' => {
11582                let (v, np) = parse_int(p, 2);
11583                if np == p { return core::ptr::null_mut(); }
11584                relyear = v;
11585                want_century |= 1;
11586                p = np;
11587            }
11588            b'Y' => {
11589                let neg = if *p == b'-' { p = p.add(1); true } else { false };
11590                let (v, np) = parse_int(p, 4);
11591                if np == p { return core::ptr::null_mut(); }
11592                (*tm).tm_year = if neg { -(v + 1900) } else { v - 1900 };
11593                want_century = 0;
11594                p = np;
11595            }
11596            b'z' => {
11597                if *p != b'+' && *p != b'-' { return core::ptr::null_mut(); }
11598                let neg = *p == b'-';
11599                p = p.add(1);
11600                let mut off = 0i64;
11601                let mut digits = 0;
11602                while digits < 4 && *p >= b'0' && *p <= b'9' {
11603                    off = off * 10 + (*p - b'0') as i64;
11604                    p = p.add(1);
11605                    digits += 1;
11606                }
11607                if digits == 0 { return core::ptr::null_mut(); }
11608                let (hh, mm) = if digits <= 2 { (off, 0i64) } else { (off / 100, off % 100) };
11609                (*tm).tm_gmtoff = (hh * 3600 + mm * 60) * if neg { -1 } else { 1 };
11610            }
11611            b'%' => {
11612                if *p != b'%' { return core::ptr::null_mut(); }
11613                p = p.add(1);
11614            }
11615            _ => { return core::ptr::null_mut(); }
11616        }
11617        f = f.add(1);
11618    }
11619    if want_century != 0 {
11620        (*tm).tm_year = relyear;
11621        if want_century & 2 != 0 { (*tm).tm_year += century * 100 - 1900; }
11622        else if (*tm).tm_year <= 68 { (*tm).tm_year += 100; }
11623    }
11624    p as *mut c_char
11625}
11626
11627// ============================================================
11628// Time: tzset / daylight / timezone / tzname
11629// ============================================================
11630
11631#[no_mangle]
11632pub static mut daylight: c_int = 0;
11633#[no_mangle]
11634pub static mut timezone: c_long = 0;
11635#[no_mangle]
11636pub 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];
11637
11638#[no_mangle]
11639pub unsafe extern "C" fn tzset() {
11640    tz_set();
11641}
11642
11643// ============================================================
11644// system()
11645// ============================================================
11646
11647#[no_mangle]
11648pub unsafe extern "C" fn system(cmd: *const c_char) -> c_int {
11649    if cmd.is_null() {
11650        // ponytail: test shell availability via fork+exec
11651        let pid = sys_fork();
11652        if pid == 0 {
11653            let sh = b"/bin/sh\0".as_ptr() as *const c_char;
11654            let dash_c = b"-c\0".as_ptr() as *const c_char;
11655            let exit0 = b"exit 0\0".as_ptr() as *const c_char;
11656            let argv = [b"sh\0".as_ptr() as *const c_char, dash_c, exit0, core::ptr::null()];
11657            sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
11658            _exit(127);
11659        }
11660        if pid < 0 { return -1; }
11661        let mut status: c_int = 0;
11662        loop {
11663            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
11664            if r >= 0 { return status; }
11665            if r != -4 { return -1; } // not EINTR
11666        }
11667    }
11668
11669    let sa_ignore = KSigAction {
11670        sa_handler: SIG_IGN,
11671        sa_flags: SA_RESTORER,
11672        sa_restorer: sig_restorer as *const () as usize,
11673        sa_mask: [0],
11674    };
11675    let mut oldint: KSigAction = core::mem::zeroed();
11676    let mut oldquit: KSigAction = core::mem::zeroed();
11677
11678    sys_rt_sigaction(SIGINT, &sa_ignore, &mut oldint, 8);
11679    sys_rt_sigaction(SIGQUIT, &sa_ignore, &mut oldquit, 8);
11680
11681    let mut block_set: SigSetT = 0;
11682    block_set |= 1u64 << (SIGCHLD - 1);
11683    let mut oldmask: SigSetT = 0;
11684    sys_rt_sigprocmask(SIG_BLOCK, &block_set, &mut oldmask, 8);
11685
11686    let pid = sys_fork();
11687
11688    if pid == 0 {
11689        sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
11690        sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
11691        sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
11692
11693        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
11694        let argv = [
11695            b"sh\0".as_ptr() as *const c_char,
11696            b"-c\0".as_ptr() as *const c_char,
11697            cmd,
11698            core::ptr::null(),
11699        ];
11700        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
11701        _exit(127);
11702    }
11703
11704    let mut status: c_int = -1;
11705    if pid > 0 {
11706        loop {
11707            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
11708            if r >= 0 { break; }
11709            if r != -4 { break; } // not EINTR
11710        }
11711    }
11712
11713    sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
11714    sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
11715    sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
11716
11717    status
11718}
11719
11720// ============================================================
11721// errno: strerror / strerror_r / environ alias
11722// ============================================================
11723
11724const EPERM_VAL: c_int = 1;
11725const ENOENT_VAL: c_int = 2;
11726const ESRCH_VAL: c_int = 3;
11727const EINTR_VAL: c_int = 4;
11728const EIO_VAL: c_int = 5;
11729const ENXIO_VAL: c_int = 6;
11730const E2BIG_VAL: c_int = 7;
11731const ENOEXEC_VAL: c_int = 8;
11732const EBADF_VAL: c_int = 9;
11733const ECHILD_VAL: c_int = 10;
11734const EAGAIN_VAL: c_int = 11;
11735const ENOMEM_VAL: c_int = 12;
11736const EACCES_VAL: c_int = 13;
11737const EFAULT_VAL: c_int = 14;
11738const ENOTBLK_VAL: c_int = 15;
11739const EBUSY_VAL: c_int = 16;
11740const EEXIST_VAL: c_int = 17;
11741const EXDEV_VAL: c_int = 18;
11742const ENODEV_VAL: c_int = 19;
11743const ENOTDIR_VAL: c_int = 20;
11744const EISDIR_VAL: c_int = 21;
11745const EINVAL_VAL: c_int = 22;
11746const ENFILE_VAL: c_int = 23;
11747const EMFILE_VAL: c_int = 24;
11748const ENOTTY_VAL: c_int = 25;
11749const ETXTBSY_VAL: c_int = 26;
11750const EFBIG_VAL: c_int = 27;
11751const ENOSPC_VAL: c_int = 28;
11752const ESPIPE_VAL: c_int = 29;
11753const EROFS_VAL: c_int = 30;
11754const EMLINK_VAL: c_int = 31;
11755const EPIPE_VAL: c_int = 32;
11756const EDOM_VAL: c_int = 33;
11757const ERANGE_VAL: c_int = 34;
11758const EDEADLK_VAL: c_int = 35;
11759const ENAMETOOLONG_VAL: c_int = 36;
11760const ENOLCK_VAL: c_int = 37;
11761const ENOSYS_VAL: c_int = 38;
11762const ENOTEMPTY_VAL: c_int = 39;
11763const ELOOP_VAL: c_int = 40;
11764const EWOULDBLOCK_VAL: c_int = 11;
11765const ENOMSG_VAL: c_int = 42;
11766const EIDRM_VAL: c_int = 43;
11767const ECHRNG_VAL: c_int = 44;
11768const EL2NSYNC_VAL: c_int = 45;
11769const EL3HLT_VAL: c_int = 46;
11770const EL3RST_VAL: c_int = 47;
11771const ELNRNG_VAL: c_int = 48;
11772const EUNATCH_VAL: c_int = 49;
11773const ENOCSI_VAL: c_int = 50;
11774const EL2HLT_VAL: c_int = 51;
11775const EBADE_VAL: c_int = 52;
11776const EBADR_VAL: c_int = 53;
11777const EXFULL_VAL: c_int = 54;
11778const ENOANO_VAL: c_int = 55;
11779const EBADRQC_VAL: c_int = 56;
11780const EBADSLT_VAL: c_int = 57;
11781const EBFONT_VAL: c_int = 59;
11782const ENOSTR_VAL: c_int = 60;
11783const ENODATA_VAL: c_int = 61;
11784const ETIME_VAL: c_int = 62;
11785const ENOSR_VAL: c_int = 63;
11786const ENONET_VAL: c_int = 64;
11787const ENOPKG_VAL: c_int = 65;
11788const EREMOTE_VAL: c_int = 66;
11789const ENOLINK_VAL: c_int = 67;
11790const EADV_VAL: c_int = 68;
11791const ESRMNT_VAL: c_int = 69;
11792const ECOMM_VAL: c_int = 70;
11793const EPROTO_VAL: c_int = 71;
11794const EMULTIHOP_VAL: c_int = 72;
11795const EDOTDOT_VAL: c_int = 73;
11796const EBADMSG_VAL: c_int = 74;
11797const EOVERFLOW_VAL: c_int = 75;
11798const ENOTUNIQ_VAL: c_int = 76;
11799const EBADFD_VAL: c_int = 77;
11800const EREMCHG_VAL: c_int = 78;
11801const ELIBACC_VAL: c_int = 79;
11802const ELIBBAD_VAL: c_int = 80;
11803const ELIBSCN_VAL: c_int = 81;
11804const ELIBMAX_VAL: c_int = 82;
11805const ELIBEXEC_VAL: c_int = 83;
11806const EILSEQ_VAL: c_int = 84;
11807const ERESTART_VAL: c_int = 85;
11808const ESTRPIPE_VAL: c_int = 86;
11809const EUSERS_VAL: c_int = 87;
11810const ENOTSOCK_VAL: c_int = 88;
11811const EDESTADDRREQ_VAL: c_int = 89;
11812const EMSGSIZE_VAL: c_int = 90;
11813const EPROTOTYPE_VAL: c_int = 91;
11814const ENOPROTOOPT_VAL: c_int = 92;
11815const EPROTONOSUPPORT_VAL: c_int = 93;
11816const ESOCKTNOSUPPORT_VAL: c_int = 94;
11817const EOPNOTSUPP_VAL: c_int = 95;
11818const ENOTSUP_VAL: c_int = 95;
11819const EPFNOSUPPORT_VAL: c_int = 96;
11820const EAFNOSUPPORT_VAL: c_int = 97;
11821const EADDRINUSE_VAL: c_int = 98;
11822const EADDRNOTAVAIL_VAL: c_int = 99;
11823const ENETDOWN_VAL: c_int = 100;
11824const ENETUNREACH_VAL: c_int = 101;
11825const ENETRESET_VAL: c_int = 102;
11826const ECONNABORTED_VAL: c_int = 103;
11827const ECONNRESET_VAL: c_int = 104;
11828const ENOBUFS_VAL: c_int = 105;
11829const EISCONN_VAL: c_int = 106;
11830const ENOTCONN_VAL: c_int = 107;
11831const ESHUTDOWN_VAL: c_int = 108;
11832const ETOOMANYREFS_VAL: c_int = 109;
11833const ETIMEDOUT_VAL: c_int = 110;
11834const ECONNREFUSED_VAL: c_int = 111;
11835const EHOSTDOWN_VAL: c_int = 112;
11836const EHOSTUNREACH_VAL: c_int = 113;
11837const EALREADY_VAL: c_int = 114;
11838const EINPROGRESS_VAL: c_int = 115;
11839const ESTALE_VAL: c_int = 116;
11840const EUCLEAN_VAL: c_int = 117;
11841const ENOTNAM_VAL: c_int = 118;
11842const ENAVAIL_VAL: c_int = 119;
11843const EISNAM_VAL: c_int = 120;
11844const EREMOTEIO_VAL: c_int = 121;
11845const EDQUOT_VAL: c_int = 122;
11846const ENOMEDIUM_VAL: c_int = 123;
11847const EMEDIUMTYPE_VAL: c_int = 124;
11848const ECANCELED_VAL: c_int = 125;
11849const ENOKEY_VAL: c_int = 126;
11850const EKEYEXPIRED_VAL: c_int = 127;
11851const EKEYREVOKED_VAL: c_int = 128;
11852const EKEYREJECTED_VAL: c_int = 129;
11853const EOWNERDEAD_VAL: c_int = 130;
11854const ENOTRECOVERABLE_VAL: c_int = 131;
11855const ERFKILL_VAL: c_int = 132;
11856const EHWPOISON_VAL: c_int = 133;
11857
11858// ponytail: static error string table indexed by errno
11859static ERR_STRS: [&[u8]; 134] = [
11860    b"Success\0",                     // 0
11861    b"Operation not permitted\0",     // 1
11862    b"No such file or directory\0",   // 2
11863    b"No such process\0",             // 3
11864    b"Interrupted system call\0",     // 4
11865    b"Input/output error\0",          // 5
11866    b"No such device or address\0",   // 6
11867    b"Argument list too long\0",      // 7
11868    b"Exec format error\0",           // 8
11869    b"Bad file descriptor\0",         // 9
11870    b"No child processes\0",          // 10
11871    b"Resource temporarily unavailable\0", // 11
11872    b"Cannot allocate memory\0",      // 12
11873    b"Permission denied\0",           // 13
11874    b"Bad address\0",                 // 14
11875    b"Block device required\0",       // 15
11876    b"Device or resource busy\0",     // 16
11877    b"File exists\0",                 // 17
11878    b"Invalid cross-device link\0",   // 18
11879    b"No such device\0",              // 19
11880    b"Not a directory\0",             // 20
11881    b"Is a directory\0",              // 21
11882    b"Invalid argument\0",            // 22
11883    b"Too many open files in system\0", // 23
11884    b"Too many open files\0",         // 24
11885    b"Inappropriate ioctl for device\0", // 25
11886    b"Text file busy\0",              // 26
11887    b"File too large\0",              // 27
11888    b"No space left on device\0",     // 28
11889    b"Illegal seek\0",                // 29
11890    b"Read-only file system\0",       // 30
11891    b"Too many links\0",              // 31
11892    b"Broken pipe\0",                 // 32
11893    b"Numerical argument out of domain\0", // 33
11894    b"Numerical result out of range\0", // 34
11895    b"Resource deadlock avoided\0",   // 35
11896    b"File name too long\0",          // 36
11897    b"No locks available\0",          // 37
11898    b"Function not implemented\0",    // 38
11899    b"Directory not empty\0",         // 39
11900    b"Too many levels of symbolic links\0", // 40
11901    b"Unknown error 41\0",            // 41
11902    b"No message of desired type\0",  // 42
11903    b"Identifier removed\0",          // 43
11904    b"Channel number out of range\0", // 44
11905    b"Level 2 not synchronized\0",    // 45
11906    b"Level 3 halted\0",              // 46
11907    b"Level 3 reset\0",               // 47
11908    b"Link number out of range\0",    // 48
11909    b"Protocol driver not attached\0", // 49
11910    b"No CSI structure available\0",  // 50
11911    b"Level 2 halted\0",              // 51
11912    b"Invalid exchange\0",            // 52
11913    b"Invalid request descriptor\0",  // 53
11914    b"Exchange full\0",               // 54
11915    b"No anode\0",                    // 55
11916    b"Invalid request code\0",        // 56
11917    b"Invalid slot\0",                // 57
11918    b"Unknown error 58\0",            // 58
11919    b"Bad font file format\0",        // 59
11920    b"Device not a stream\0",         // 60
11921    b"No data available\0",           // 61
11922    b"Timer expired\0",               // 62
11923    b"Out of streams resources\0",    // 63
11924    b"Machine is not on the network\0", // 64
11925    b"Package not installed\0",       // 65
11926    b"Object is remote\0",            // 66
11927    b"Link has been severed\0",       // 67
11928    b"Advertise error\0",             // 68
11929    b"Srmount error\0",               // 69
11930    b"Communication error on send\0", // 70
11931    b"Protocol error\0",              // 71
11932    b"Multihop attempted\0",          // 72
11933    b"RFS specific error\0",          // 73
11934    b"Bad message\0",                 // 74
11935    b"Value too large for defined data type\0", // 75
11936    b"Name not unique on network\0",  // 76
11937    b"File descriptor in bad state\0", // 77
11938    b"Remote address changed\0",      // 78
11939    b"Can not access a needed shared library\0", // 79
11940    b"Accessing a corrupted shared library\0", // 80
11941    b".lib section in a.out corrupted\0", // 81
11942    b"Attempting to link in too many shared libraries\0", // 82
11943    b"Cannot exec a shared library directly\0", // 83
11944    b"Invalid or incomplete multibyte or wide character\0", // 84
11945    b"Interrupted system call should be restarted\0", // 85
11946    b"Streams pipe error\0",          // 86
11947    b"Too many users\0",              // 87
11948    b"Socket operation on non-socket\0", // 88
11949    b"Destination address required\0", // 89
11950    b"Message too long\0",            // 90
11951    b"Protocol wrong type for socket\0", // 91
11952    b"Protocol not available\0",      // 92
11953    b"Protocol not supported\0",      // 93
11954    b"Socket type not supported\0",   // 94
11955    b"Operation not supported\0",     // 95
11956    b"Protocol family not supported\0", // 96
11957    b"Address family not supported by protocol\0", // 97
11958    b"Address already in use\0",      // 98
11959    b"Cannot assign requested address\0", // 99
11960    b"Network is down\0",             // 100
11961    b"Network is unreachable\0",      // 101
11962    b"Network dropped connection on reset\0", // 102
11963    b"Software caused connection abort\0", // 103
11964    b"Connection reset by peer\0",    // 104
11965    b"No buffer space available\0",   // 105
11966    b"Transport endpoint is already connected\0", // 106
11967    b"Transport endpoint is not connected\0", // 107
11968    b"Cannot send after transport endpoint shutdown\0", // 108
11969    b"Too many references: cannot splice\0", // 109
11970    b"Connection timed out\0",        // 110
11971    b"Connection refused\0",          // 111
11972    b"Host is down\0",                // 112
11973    b"No route to host\0",            // 113
11974    b"Operation already in progress\0", // 114
11975    b"Operation now in progress\0",   // 115
11976    b"Stale file handle\0",           // 116
11977    b"Structure needs cleaning\0",    // 117
11978    b"Not a XENIX named type file\0", // 118
11979    b"No XENIX semaphores available\0", // 119
11980    b"Is a named type file\0",        // 120
11981    b"Remote I/O error\0",            // 121
11982    b"Quota exceeded\0",              // 122
11983    b"No medium found\0",             // 123
11984    b"Wrong medium type\0",           // 124
11985    b"Operation canceled\0",          // 125
11986    b"Required key not available\0",  // 126
11987    b"Key has expired\0",             // 127
11988    b"Key has been revoked\0",        // 128
11989    b"Key was rejected by service\0", // 129
11990    b"Owner died\0",                  // 130
11991    b"State not recoverable\0",       // 131
11992    b"Operation not possible due to RF-kill\0", // 132
11993    b"Memory page has hardware error\0", // 133
11994];
11995
11996#[no_mangle]
11997pub unsafe extern "C" fn strerror(errnum: c_int) -> *mut c_char {
11998    if errnum < 0 || errnum as usize >= ERR_STRS.len() {
11999        // ponytail: static buf for unknown errors
12000        static mut UNKNOWN_BUF: [c_char; 64] = [0; 64];
12001        let prefix = b"Unknown error \0";
12002        let mut i = 0;
12003        while prefix[i] != 0 {
12004            UNKNOWN_BUF[i] = prefix[i] as c_char;
12005            i += 1;
12006        }
12007        let (buf, len) = format_u64(errnum as u64);
12008        for j in 0..len {
12009            UNKNOWN_BUF[i] = buf[20 - len + j] as c_char;
12010            i += 1;
12011        }
12012        UNKNOWN_BUF[i] = 0;
12013        return core::ptr::addr_of_mut!(UNKNOWN_BUF).cast::<c_char>();
12014    }
12015    ERR_STRS[errnum as usize].as_ptr() as *mut c_char
12016}
12017
12018#[no_mangle]
12019pub unsafe extern "C" fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: usize) -> c_int {
12020    let s = strerror(errnum);
12021    let slen = strlen(s as *const c_char);
12022    if slen >= buflen {
12023        if buflen > 0 {
12024            core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, buflen - 1);
12025            *buf.add(buflen - 1) = 0;
12026        }
12027        return 34; // ERANGE
12028    }
12029    core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, slen + 1);
12030    0
12031}
12032
12033// ponytail: `environ` alias for tests that use extern char **environ
12034#[no_mangle]
12035pub static mut environ: *mut *mut c_char = core::ptr::null_mut();
12036
12037// keep environ in sync with __environ
12038unsafe fn sync_environ() {
12039    environ = __environ;
12040}
12041
12042// ============================================================
12043// unistd extensions: pipe, dup, dup2, fcntl, access, unlink, etc.
12044// ============================================================
12045
12046#[inline]
12047unsafe fn sys_dup(oldfd: i32) -> i64 {
12048    <Arch as Syscalls>::syscall1(SYS_DUP, oldfd as i64)
12049}
12050
12051#[inline]unsafe fn sys_dup2(oldfd: i32, newfd: i32) -> i64 {
12052    // ponytail: dup3 with flags=0 is equivalent to dup2
12053    sys_dup3(oldfd, newfd, 0)
12054}
12055
12056#[inline]
12057unsafe fn sys_access(path: *const u8, mode: i32) -> i64 {
12058    <Arch as Syscalls>::syscall4(SYS_FACCESSAT, AT_FDCWD as i64, path as i64, mode as i64, 0)
12059}
12060
12061#[inline]unsafe fn sys_unlink(path: *const u8) -> i64 {
12062    sys_unlinkat(AT_FDCWD, path, 0)
12063}
12064
12065#[inline]unsafe fn sys_rmdir(path: *const u8) -> i64 {
12066    sys_unlinkat(AT_FDCWD, path, 512) // AT_REMOVEDIR
12067}
12068
12069#[inline]
12070unsafe fn sys_chdir(path: *const u8) -> i64 {
12071    <Arch as Syscalls>::syscall1(SYS_CHDIR, path as i64)
12072}
12073
12074#[inline]
12075unsafe fn sys_getcwd(buf: *mut u8, size: usize) -> i64 {
12076    <Arch as Syscalls>::syscall2(SYS_GETCWD, buf as i64, size as i64)
12077}
12078
12079#[inline]
12080unsafe fn sys_sethostname(name: *const u8, len: usize) -> i64 {
12081    <Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)
12082}
12083
12084#[inline]
12085unsafe fn sys_gethostname(buf: *mut u8, len: usize) -> i64 {
12086    #[repr(C)]
12087    struct UtsName {
12088        sysname: [u8; 65],
12089        nodename: [u8; 65],
12090        release: [u8; 65],
12091        version: [u8; 65],
12092        machine: [u8; 65],
12093        domainname: [u8; 65],
12094    }
12095    let mut uts: UtsName = core::mem::zeroed();
12096    let result = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
12097    if result < 0 {
12098        return result;
12099    }
12100    let nlen = strlen(uts.nodename.as_ptr() as *const c_char);
12101    let copylen = if nlen < len { nlen } else { if len > 0 { len - 1 } else { 0 } };
12102    core::ptr::copy_nonoverlapping(uts.nodename.as_ptr(), buf, copylen);
12103    if len > 0 { *buf.add(copylen) = 0; }
12104    0
12105}
12106
12107unsafe fn sys_truncate(path: *const u8, length: i64) -> i64 {
12108    <Arch as Syscalls>::syscall2(SYS_TRUNCATE, path as i64, length as i64)
12109}
12110
12111unsafe fn sys_ftruncate(fd: i32, length: i64) -> i64 {
12112    <Arch as Syscalls>::syscall2(SYS_FTRUNCATE, fd as i64, length as i64)
12113}
12114
12115unsafe fn sys_nanosleep(req: *const timespec, rem: *mut timespec) -> i64 {
12116    <Arch as Syscalls>::syscall2(SYS_NANOSLEEP, req as i64, rem as i64)
12117}
12118
12119const ITIMER_REAL: i32 = 0;
12120
12121#[repr(C)]
12122struct itimerval {
12123    it_interval: timeval,
12124    it_value: timeval,
12125}
12126
12127unsafe fn sys_alarm(seconds: c_uint) -> i64 {
12128    let mut new: itimerval = core::mem::zeroed();
12129    new.it_value.tv_sec = seconds as c_long;
12130    let mut old: itimerval = core::mem::zeroed();
12131    let r = <Arch as Syscalls>::syscall3(
12132        SYS_SETITIMER,
12133        ITIMER_REAL as i64,
12134        &new as *const _ as i64,
12135        &mut old as *mut _ as i64,
12136    );
12137    if r < 0 {
12138        return r;
12139    }
12140    old.it_value.tv_sec as i64 + (old.it_value.tv_usec != 0) as i64
12141}
12142
12143unsafe fn sys_pause() -> i64 {
12144    #[cfg(target_arch = "x86_64")]
12145    { <Arch as Syscalls>::syscall0(SYS_PAUSE) }
12146    #[cfg(target_arch = "aarch64")]
12147    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
12148    #[cfg(target_arch = "riscv64")]
12149    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
12150}
12151
12152unsafe fn sys_fsync(fd: i32) -> i64 {
12153    <Arch as Syscalls>::syscall1(SYS_FSYNC, fd as i64)
12154}
12155
12156unsafe fn sys_fdatasync(fd: i32) -> i64 {
12157    <Arch as Syscalls>::syscall1(SYS_FDATASYNC, fd as i64)
12158}
12159
12160unsafe fn sys_sync() {
12161    let _ = <Arch as Syscalls>::syscall0(SYS_SYNC);
12162}
12163
12164unsafe fn sys_symlink(target: *const u8, linkpath: *const u8) -> i64 {
12165    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, AT_FDCWD as i64, linkpath as i64)
12166}
12167
12168unsafe fn sys_symlinkat(target: *const u8, newdirfd: i32, linkpath: *const u8) -> i64 {
12169    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)
12170}
12171
12172unsafe fn sys_readlinkat(dirfd: i32, path: *const u8, buf: *mut u8, bufsiz: usize) -> i64 {
12173    <Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, path as i64, buf as i64, bufsiz as i64)
12174}
12175
12176unsafe fn sys_linkat(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: i32) -> i64 {
12177    <Arch as Syscalls>::syscall5(SYS_LINKAT, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
12178}
12179
12180unsafe fn sys_fchmod(fd: i32, mode: u32) -> i64 {
12181    <Arch as Syscalls>::syscall2(SYS_FCHMOD, fd as i64, mode as i64)
12182}
12183
12184unsafe fn sys_fchmodat(dirfd: i32, path: *const u8, mode: u32, flags: i32) -> i64 {
12185    <Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, path as i64, mode as i64, flags as i64)
12186}
12187
12188unsafe fn sys_umask(mask: u32) -> u32 {
12189    <Arch as Syscalls>::syscall1(SYS_UMASK, mask as i64) as u32
12190}
12191
12192unsafe fn sys_getgroups(size: i32, list: *mut c_uint) -> i64 {
12193    <Arch as Syscalls>::syscall2(SYS_GETGROUPS, size as i64, list as i64)
12194}
12195
12196unsafe fn sys_setuid(uid: c_uint) -> i64 {
12197    <Arch as Syscalls>::syscall1(SYS_SETUID, uid as i64)
12198}
12199
12200unsafe fn sys_setgid(gid: c_uint) -> i64 {
12201    <Arch as Syscalls>::syscall1(SYS_SETGID, gid as i64)
12202}
12203
12204unsafe fn sys_setsid() -> i64 {
12205    <Arch as Syscalls>::syscall0(SYS_SETSID)
12206}
12207
12208unsafe fn sys_setpgid(pid: c_int, pgid: c_int) -> i64 {
12209    <Arch as Syscalls>::syscall2(SYS_SETPGID, pid as i64, pgid as i64)
12210}
12211
12212unsafe fn sys_getpgid(pid: c_int) -> i64 {
12213    <Arch as Syscalls>::syscall1(SYS_GETPGID, pid as i64)
12214}
12215
12216unsafe fn sys_getsid(pid: c_int) -> i64 {
12217    <Arch as Syscalls>::syscall1(SYS_GETSID, pid as i64)
12218}
12219
12220unsafe fn sys_mkdirat(dirfd: i32, path: *const u8, mode: u32) -> i64 {
12221    <Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, path as i64, mode as i64)
12222}
12223
12224// Public C ABI wrappers for unistd
12225
12226#[no_mangle]
12227pub unsafe extern "C" fn pipe(fds: *mut c_int) -> c_int {
12228    let r = sys_pipe2(fds, 0);
12229    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12230    0
12231}
12232
12233#[no_mangle]
12234pub unsafe extern "C" fn pipe2(fds: *mut c_int, flags: c_int) -> c_int {
12235    let r = sys_pipe2(fds, flags);
12236    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12237    0
12238}
12239
12240#[no_mangle]
12241pub unsafe extern "C" fn dup(oldfd: c_int) -> c_int {
12242    let r = sys_dup(oldfd);
12243    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12244    r as c_int
12245}
12246
12247#[no_mangle]
12248pub unsafe extern "C" fn dup2(oldfd: c_int, newfd: c_int) -> c_int {
12249    if oldfd == newfd {
12250        // dup3 rejects equal descriptors with EINVAL; dup2 must validate the
12251        // descriptor and return newfd unchanged.
12252        let r = sys_fcntl(oldfd, 1 /* F_GETFD */, 0);
12253        if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12254        return newfd;
12255    }
12256    let r = sys_dup2(oldfd, newfd);
12257    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12258    r as c_int
12259}
12260
12261#[no_mangle]
12262pub unsafe extern "C" fn dup3(oldfd: c_int, newfd: c_int, flags: c_int) -> c_int {
12263    let r = sys_dup3(oldfd, newfd, flags);
12264    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12265    r as c_int
12266}
12267
12268#[no_mangle]
12269pub unsafe extern "C" fn fcntl(fd: c_int, cmd: c_int, mut args: ...) -> c_int {
12270    // Commands without an argument. Everything else (including seals,
12271    // pipe sizes, ownership and locks) takes the third argument.
12272    let no_arg = matches!(cmd, 1 /* F_GETFD */ | 3 /* F_GETFL */ | 9 /* F_GETOWN */
12273        | 11 /* F_GETSIG */ | 1025 /* F_GETLEASE */ | 1032 /* F_GETPIPE_SZ */
12274        | 1034 /* F_GET_SEALS */);
12275    let r = if no_arg {
12276        sys_fcntl(fd, cmd, 0)
12277    } else {
12278        let arg = args.next_arg::<c_long>();
12279        sys_fcntl(fd, cmd, arg)
12280    };
12281    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12282    r as c_int
12283}
12284
12285#[no_mangle]
12286pub unsafe extern "C" fn access(path: *const c_char, mode: c_int) -> c_int {
12287    let r = sys_access(path as *const u8, mode);
12288    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12289    0
12290}
12291
12292#[no_mangle]
12293pub unsafe extern "C" fn unlink(path: *const c_char) -> c_int {
12294    let r = sys_unlink(path as *const u8);
12295    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12296    0
12297}
12298
12299#[no_mangle]
12300pub unsafe extern "C" fn rmdir(path: *const c_char) -> c_int {
12301    let r = sys_rmdir(path as *const u8);
12302    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12303    0
12304}
12305
12306#[no_mangle]
12307pub unsafe extern "C" fn chdir(path: *const c_char) -> c_int {
12308    let r = sys_chdir(path as *const u8);
12309    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12310    0
12311}
12312
12313#[no_mangle]
12314pub unsafe extern "C" fn getcwd(buf: *mut c_char, size: usize) -> *mut c_char {
12315    if buf.is_null() {
12316        // allocate
12317        let alloc_size = if size == 0 { 256 } else { size };
12318        let p = malloc(alloc_size) as *mut c_char;
12319        if p.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
12320        let r = sys_getcwd(p as *mut u8, alloc_size);
12321        if r < 0 { free(p as *mut c_void); ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
12322        // The kernel returns "(unreachable)..." when cwd is outside the
12323        // current root; POSIX getcwd must fail with ENOENT in that case.
12324        if *p as u8 != b'/' {
12325            free(p as *mut c_void);
12326            ERRNO!() = 2;
12327            return core::ptr::null_mut();
12328        }
12329        return p;
12330    }
12331    if size == 0 { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
12332    let r = sys_getcwd(buf as *mut u8, size);
12333    if r < 0 { ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
12334    if *buf as u8 != b'/' {
12335        ERRNO!() = 2;
12336        return core::ptr::null_mut();
12337    }
12338    buf
12339}
12340
12341#[no_mangle]
12342pub unsafe extern "C" fn gethostname(name: *mut c_char, len: usize) -> c_int {
12343    let r = sys_gethostname(name as *mut u8, len);
12344    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12345    0
12346}
12347
12348// ponytail: getpagesize - hardcoded 4096 for x86_64
12349#[no_mangle]
12350pub extern "C" fn getpagesize() -> c_int {
12351    4096
12352}
12353
12354#[no_mangle]
12355pub unsafe extern "C" fn truncate(path: *const c_char, length: i64) -> c_int {
12356    let r = sys_truncate(path as *const u8, length);
12357    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12358    0
12359}
12360
12361#[no_mangle]
12362pub unsafe extern "C" fn ftruncate(fd: c_int, length: i64) -> c_int {
12363    let r = sys_ftruncate(fd, length);
12364    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12365    0
12366}
12367
12368#[no_mangle]
12369pub unsafe extern "C" fn nanosleep(req: *const timespec, rem: *mut timespec) -> c_int {
12370    pthread_testcancel();
12371    let r = sys_nanosleep(req, rem);
12372    pthread_testcancel();
12373    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12374    0
12375}
12376
12377#[no_mangle]
12378pub unsafe extern "C" fn sleep(seconds: c_uint) -> c_uint {
12379    let req = timespec { tv_sec: seconds as c_long, tv_nsec: 0 };
12380    let mut rem: timespec = core::mem::zeroed();
12381    pthread_testcancel();
12382    let r = sys_nanosleep(&req, &mut rem);
12383    pthread_testcancel();
12384    if r < 0 {
12385        let e = (-r) as c_int;
12386        if e == EINTR { return rem.tv_sec as c_uint; }
12387    }
12388    0
12389}
12390
12391#[no_mangle]
12392pub unsafe extern "C" fn usleep(usec: c_uint) -> c_int {
12393    let req = timespec { tv_sec: (usec / 1000000) as c_long, tv_nsec: ((usec % 1000000) * 1000) as c_long };
12394    pthread_testcancel();
12395    let r = sys_nanosleep(&req, core::ptr::null_mut());
12396    pthread_testcancel();
12397    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12398    0
12399}
12400
12401#[no_mangle]
12402pub unsafe extern "C" fn alarm(seconds: c_uint) -> c_uint {
12403    // POSIX rounds a nonzero fractional remainder up to one second;
12404    // sys_alarm() already performs that rounding.
12405    let r = sys_alarm(seconds);
12406    if r < 0 { 0 } else { r as c_uint }
12407}
12408
12409#[no_mangle]
12410pub unsafe extern "C" fn pause() -> c_int {
12411    pthread_testcancel();
12412    sys_pause();
12413    pthread_testcancel();
12414    ERRNO!() = EINTR;
12415    -1
12416}
12417
12418#[no_mangle]
12419pub unsafe extern "C" fn fsync(fd: c_int) -> c_int {
12420    let r = sys_fsync(fd);
12421    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12422    0
12423}
12424
12425#[no_mangle]
12426pub unsafe extern "C" fn fdatasync(fd: c_int) -> c_int {
12427    let r = sys_fdatasync(fd);
12428    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12429    0
12430}
12431
12432#[no_mangle]
12433pub unsafe extern "C" fn sync() {
12434    sys_sync();
12435}
12436
12437#[no_mangle]
12438pub unsafe extern "C" fn symlink(target: *const c_char, linkpath: *const c_char) -> c_int {
12439    let r = sys_symlinkat(target as *const u8, AT_FDCWD, linkpath as *const u8);
12440    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12441    0
12442}
12443
12444#[no_mangle]
12445pub unsafe extern "C" fn readlink(path: *const c_char, buf: *mut c_char, bufsiz: usize) -> isize {
12446    let r = sys_readlinkat(AT_FDCWD, path as *const u8, buf as *mut u8, bufsiz);
12447    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12448    r as isize
12449}
12450
12451#[no_mangle]
12452pub unsafe extern "C" fn link(oldpath: *const c_char, newpath: *const c_char) -> c_int {
12453    let r = sys_linkat(AT_FDCWD, oldpath as *const u8, AT_FDCWD, newpath as *const u8, 0);
12454    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12455    0
12456}
12457
12458#[no_mangle]
12459pub unsafe extern "C" fn chmod(path: *const c_char, mode: c_uint) -> c_int {
12460    let r = sys_fchmodat(AT_FDCWD, path as *const u8, mode, 0);
12461    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12462    0
12463}
12464
12465#[no_mangle]
12466pub unsafe extern "C" fn fchmod(fd: c_int, mode: c_uint) -> c_int {
12467    let r = sys_fchmod(fd, mode);
12468    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12469    0
12470}
12471
12472#[no_mangle]
12473pub unsafe extern "C" fn umask(mask: c_uint) -> c_uint {
12474    sys_umask(mask) as c_uint
12475}
12476
12477#[no_mangle]
12478pub unsafe extern "C" fn isatty(fd: c_int) -> c_int {
12479    let mut ws: winsize = core::mem::zeroed();
12480    if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 { 1 } else { 0 }
12481}
12482
12483#[no_mangle]
12484pub unsafe extern "C" fn getlogin() -> *mut c_char {
12485    crate::getenv(b"LOGNAME\0".as_ptr() as *const c_char)
12486}
12487
12488#[no_mangle]
12489pub unsafe extern "C" fn getgroups(size: c_int, list: *mut c_uint) -> c_int {
12490    let r = sys_getgroups(size, list);
12491    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12492    r as c_int
12493}
12494
12495#[no_mangle]
12496pub unsafe extern "C" fn setuid(uid: c_uint) -> c_int {
12497    let r = sys_setuid(uid);
12498    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12499    0
12500}
12501
12502#[no_mangle]
12503pub unsafe extern "C" fn setgid(gid: c_uint) -> c_int {
12504    let r = sys_setgid(gid);
12505    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12506    0
12507}
12508
12509#[no_mangle]
12510pub unsafe extern "C" fn seteuid(euid: c_uint) -> c_int {
12511    // Setting only the effective uid must keep the real and saved uids, so a
12512    // process can drop privileges and later restore them (setuid would clear
12513    // the saved uid for root).
12514    setresuid(u32::MAX, euid, u32::MAX)
12515}
12516
12517#[no_mangle]
12518pub unsafe extern "C" fn setegid(egid: c_uint) -> c_int {
12519    setresgid(u32::MAX, egid, u32::MAX)
12520}
12521
12522#[no_mangle]
12523pub unsafe extern "C" fn setreuid(ruid: c_uint, euid: c_uint) -> c_int {
12524    let r = <Arch as Syscalls>::syscall2(sysno(113, 145), ruid as i64, euid as i64);
12525    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
12526}
12527
12528
12529
12530#[no_mangle]
12531pub unsafe extern "C" fn setsid() -> c_int {
12532    let r = sys_setsid();
12533    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12534    r as c_int
12535}
12536
12537#[no_mangle]
12538pub unsafe extern "C" fn setpgid(pid: c_int, pgid: c_int) -> c_int {
12539    let r = sys_setpgid(pid, pgid);
12540    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12541    0
12542}
12543
12544#[no_mangle]
12545pub unsafe extern "C" fn getpgid(pid: c_int) -> c_int {
12546    let r = sys_getpgid(pid);
12547    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12548    r as c_int
12549}
12550
12551#[no_mangle]
12552pub unsafe extern "C" fn getsid(pid: c_int) -> c_int {
12553    let r = sys_getsid(pid);
12554    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12555    r as c_int
12556}
12557
12558#[no_mangle]
12559pub unsafe extern "C" fn getpgrp() -> c_int {
12560    sys_getpgid(0) as c_int
12561}
12562
12563#[no_mangle]
12564pub unsafe extern "C" fn setpgrp() -> c_int {
12565    setpgid(0, 0)
12566}
12567
12568#[no_mangle]
12569unsafe fn mkstemps_impl(template: *mut c_char, suffixlen: i32) -> c_int {
12570    if template.is_null() || suffixlen < 0 {
12571        ERRNO!() = EINVAL;
12572        return -1;
12573    }
12574    let len = strlen(template as *const c_char);
12575    let suffix = suffixlen as usize;
12576    if len < 6 + suffix {
12577        ERRNO!() = EINVAL;
12578        return -1;
12579    }
12580    let x_start = len - suffix - 6;
12581    for i in x_start..x_start + 6 {
12582        if *template.add(i) != b'X' as c_char {
12583            ERRNO!() = EINVAL;
12584            return -1;
12585        }
12586    }
12587    let mut ts: timespec = core::mem::zeroed();
12588    let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
12589    let mut ctr: u32 = ts.tv_nsec as u32;
12590    for _ in 0..100 {
12591        ctr = ctr.wrapping_mul(1103515245).wrapping_add(12345);
12592        let mut seed = ctr;
12593        let hex = b"0123456789abcdef";
12594        for i in x_start..x_start + 6 {
12595            *template.add(i) = hex[(seed & 0xf) as usize] as c_char;
12596            seed >>= 4;
12597        }
12598        let fd = sys_open(template as *const u8, (O_RDWR | O_CREAT | O_EXCL) as i64, 0o600);
12599        if fd >= 0 {
12600            return fd as c_int;
12601        }
12602        let e = (-fd) as c_int;
12603        if e != EEXIST_VAL {
12604            ERRNO!() = e;
12605            return -1;
12606        }
12607    }
12608    ERRNO!() = EEXIST_VAL;
12609    -1
12610}
12611
12612#[no_mangle]
12613pub unsafe extern "C" fn mkstemp(template: *mut c_char) -> c_int {
12614    mkstemps_impl(template, 0)
12615}
12616
12617#[no_mangle]
12618pub unsafe extern "C" fn mkdir(path: *const c_char, mode: c_uint) -> c_int {
12619    let r = sys_mkdirat(AT_FDCWD, path as *const u8, mode);
12620    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12621    0
12622}
12623
12624// ============================================================
12625// libgen: basename / dirname
12626// ============================================================
12627
12628#[no_mangle]
12629pub unsafe extern "C" fn dirname(s: *mut c_char) -> *mut c_char {
12630    if s.is_null() || *s == 0 {
12631        return b".\0".as_ptr() as *mut c_char;
12632    }
12633    let mut i = strlen(s as *const c_char);
12634    i = i.wrapping_sub(1);
12635    // skip trailing slashes
12636    while i > 0 && *s.add(i) == b'/' as c_char {
12637        i = i.wrapping_sub(1);
12638    }
12639    if i == 0 && *s.add(0) == b'/' as c_char {
12640        return b"/\0".as_ptr() as *mut c_char;
12641    }
12642    // skip non-slashes
12643    while i > 0 && *s.add(i) != b'/' as c_char {
12644        i = i.wrapping_sub(1);
12645    }
12646    if i == 0 {
12647        if *s.add(0) == b'/' as c_char {
12648            return b"/\0".as_ptr() as *mut c_char;
12649        }
12650        return b".\0".as_ptr() as *mut c_char;
12651    }
12652    // skip slashes
12653    while i > 0 && *s.add(i - 1) == b'/' as c_char {
12654        i = i.wrapping_sub(1);
12655    }
12656    if i == 0 {
12657        return b"/\0".as_ptr() as *mut c_char;
12658    }
12659    *s.add(i) = 0;
12660    s
12661}
12662
12663#[no_mangle]
12664pub unsafe extern "C" fn basename(s: *mut c_char) -> *mut c_char {
12665    if s.is_null() || *s == 0 {
12666        return b".\0".as_ptr() as *mut c_char;
12667    }
12668    let mut i = strlen(s as *const c_char);
12669    i = i.wrapping_sub(1);
12670    // strip trailing slashes
12671    while i > 0 && *s.add(i) == b'/' as c_char {
12672        *s.add(i) = 0;
12673        i = i.wrapping_sub(1);
12674    }
12675    // find last slash
12676    while i > 0 && *s.add(i - 1) != b'/' as c_char {
12677        i = i.wrapping_sub(1);
12678    }
12679    s.add(i)
12680}
12681
12682// ============================================================
12683// arpa/inet: inet_pton / inet_ntop / inet_addr / inet_ntoa / inet_aton
12684// ============================================================
12685
12686const AF_INET_VAL: c_int = 2;
12687const AF_INET6_VAL: c_int = 10;
12688const EAFNOSUPPORT: c_int = 97;
12689const ENOSPC_VAL2: c_int = 28;
12690
12691unsafe fn inet_pton_v4(s: *const u8, a: *mut u8) -> c_int {
12692    let mut p = s;
12693    let mut i = 0;
12694    while i < 4 {
12695        let oct_start = p;
12696        let mut v: u32 = 0;
12697        let mut j: u32 = 0;
12698        while j < 3 && *p >= b'0' && *p <= b'9' {
12699            v = v * 10 + (*p - b'0') as u32;
12700            p = p.add(1);
12701            j += 1;
12702        }
12703        if j == 0 || (j > 1 && *oct_start == b'0') || v > 255 { return 0; }
12704        *a.add(i) = v as u8;
12705        if *p == 0 && i == 3 { return 1; }
12706        if *p != b'.' { return 0; }
12707        p = p.add(1);
12708        i += 1;
12709    }
12710    0
12711}
12712
12713unsafe fn inet_pton_v6(s: *const u8, a: *mut u8) -> c_int {
12714    let mut ip = [0u16; 8];
12715    let mut p = s;
12716    let mut i: usize = 0;
12717    let mut brk: isize = -1;
12718    let mut need_v4 = false;
12719    let mut v4_start: *const u8 = core::ptr::null();
12720
12721    if *p == b':' {
12722        p = p.add(1);
12723        if *p != b':' { return 0; }
12724    }
12725
12726    loop {
12727        if *p == b':' && brk < 0 {
12728            brk = i as isize;
12729            ip[i & 7] = 0;
12730            p = p.add(1);
12731            if *p == 0 { break; }
12732            if i == 7 { return 0; }
12733            i += 1;
12734            continue;
12735        }
12736        v4_start = p;
12737        let mut v: u16 = 0;
12738        let mut j = 0;
12739        while j < 4 {
12740            let d = hex_digit(*p);
12741            if d < 0 { break; }
12742            v = v * 16 + d as u16;
12743            p = p.add(1);
12744            j += 1;
12745        }
12746        if j == 0 { return 0; }
12747        ip[i & 7] = v;
12748        if *p == 0 && (brk >= 0 || i == 7) { break; }
12749        if i == 7 { return 0; }
12750        if *p != b':' {
12751            if *p != b'.' || (i < 6 && brk < 0) { return 0; }
12752            need_v4 = true;
12753            i += 1;
12754            ip[i & 7] = 0;
12755            break;
12756        }
12757        p = p.add(1);
12758        i += 1;
12759    }
12760
12761    if brk >= 0 {
12762        // expand :: : move trailing fields to the end and zero the gap
12763        let trail_count = i + 1 - brk as usize;
12764        let dest_start = brk as usize + 7 - i;
12765        // move backwards to avoid overwrite in the overlapping case
12766        for j in (0..trail_count).rev() {
12767            ip[dest_start + j] = ip[brk as usize + j];
12768        }
12769        for j in 0..(7 - i) {
12770            ip[brk as usize + j] = 0;
12771        }
12772    }
12773
12774    for k in 0..8 {
12775        *a.add(k * 2) = (ip[k] >> 8) as u8;
12776        *a.add(k * 2 + 1) = (ip[k] & 0xff) as u8;
12777    }
12778
12779    if need_v4 {
12780        if inet_pton_v4(v4_start, a.add(12)) <= 0 { return 0; }
12781    }
12782    1
12783}
12784
12785unsafe fn hex_digit(c: u8) -> i32 {
12786    if c >= b'0' && c <= b'9' { (c - b'0') as i32 }
12787    else if c >= b'a' && c <= b'f' { (c - b'a' + 10) as i32 }
12788    else if c >= b'A' && c <= b'F' { (c - b'A' + 10) as i32 }
12789    else { -1 }
12790}
12791
12792#[no_mangle]
12793pub unsafe extern "C" fn inet_pton(af: c_int, s: *const c_char, a: *mut c_void) -> c_int {
12794    if af == AF_INET_VAL {
12795        inet_pton_v4(s as *const u8, a as *mut u8)
12796    } else if af == AF_INET6_VAL {
12797        inet_pton_v6(s as *const u8, a as *mut u8)
12798    } else {
12799        ERRNO!() = EAFNOSUPPORT;
12800        -1
12801    }
12802}
12803
12804#[no_mangle]
12805pub unsafe extern "C" fn inet_ntop(af: c_int, a: *const c_void, s: *mut c_char, size: u32) -> *mut c_char {
12806    if af == AF_INET_VAL {
12807        let b = a as *const u8;
12808        let needed = 16; // "255.255.255.255\0"
12809        if size < needed as u32 { ERRNO!() = ENOSPC_VAL2; return core::ptr::null_mut(); }
12810        let mut pos = 0;
12811        for i in 0..4 {
12812            if i > 0 { *s.add(pos) = b'.' as c_char; pos += 1; }
12813            let (buf, len) = format_u64(*b.add(i) as u64);
12814            for j in 0..len { *s.add(pos) = buf[j] as c_char; pos += 1; }
12815        }
12816        *s.add(pos) = 0;
12817        s
12818    } else if af == AF_INET6_VAL {
12819        let b = a as *const u8;
12820        let needed = 46; // max IPv6
12821        if size < needed as u32 { ERRNO!() = ENOSPC_VAL2; return core::ptr::null_mut(); }
12822        let mut words = [0u16; 8];
12823        for i in 0..8 {
12824            words[i] = ((*b.add(i * 2) as u16) << 8) | (*b.add(i * 2 + 1) as u16);
12825        }
12826        // IPv4-mapped: ::ffff:a.b.c.d
12827        let mut pos = 0usize;
12828        if words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0
12829            && words[4] == 0 && words[5] == 0xffff
12830        {
12831            let prefix = b"::ffff:";
12832            for k in 0..prefix.len() { *s.add(pos) = prefix[k] as c_char; pos += 1; }
12833            for idx in 0..4 {
12834                if idx > 0 { *s.add(pos) = b'.' as c_char; pos += 1; }
12835                let octet = *b.add(12 + idx);
12836                if octet >= 100 {
12837                    *s.add(pos) = (b'0' + octet / 100) as c_char; pos += 1;
12838                    *s.add(pos) = (b'0' + (octet / 10) % 10) as c_char; pos += 1;
12839                } else if octet >= 10 {
12840                    *s.add(pos) = (b'0' + octet / 10) as c_char; pos += 1;
12841                }
12842                *s.add(pos) = (b'0' + octet % 10) as c_char; pos += 1;
12843            }
12844            *s.add(pos) = 0;
12845            return s;
12846        }
12847        // find longest run of zeros
12848        let mut best_start: isize = -1;
12849        let mut best_len: usize = 0;
12850        let mut j: usize = 0;
12851        while j < 8 {
12852            if words[j] == 0 {
12853                let mut k = j;
12854                while k < 8 && words[k] == 0 { k += 1; }
12855                let run = k - j;
12856                if run > best_len { best_start = j as isize; best_len = run; }
12857                j = k;
12858            } else {
12859                j += 1;
12860            }
12861        }
12862        let mut i: usize = 0;
12863        let mut prev_in_run = false;
12864        while i < 8 {
12865            let in_run = best_len >= 2 && i >= best_start as usize && i < best_start as usize + best_len;
12866            if in_run {
12867                if i == best_start as usize {
12868                    *s.add(pos) = b':' as c_char; pos += 1;
12869                    *s.add(pos) = b':' as c_char; pos += 1;
12870                }
12871                i += 1;
12872                prev_in_run = true;
12873                continue;
12874            }
12875            if i > 0 && !prev_in_run {
12876                *s.add(pos) = b':' as c_char; pos += 1;
12877            }
12878            let (buf, len) = format_hex(words[i] as u64, false);
12879            for k in 0..len { *s.add(pos) = buf[k] as c_char; pos += 1; }
12880            i += 1;
12881            prev_in_run = false;
12882        }
12883        *s.add(pos) = 0;
12884        s
12885    } else {
12886        ERRNO!() = EAFNOSUPPORT;
12887        core::ptr::null_mut()
12888    }
12889}
12890
12891#[no_mangle]
12892pub unsafe extern "C" fn inet_aton(s: *const c_char, dest: *mut c_void) -> c_int {
12893    let a = dest as *mut u8;
12894    let mut p = s as *const u8;
12895    let mut vals = [0u64; 4];
12896    let mut i = 0usize;
12897    while i < 4 {
12898        if *p < b'0' || *p > b'9' { return 0; }
12899        let mut base = 10u32;
12900        if *p == b'0' {
12901            let c = *p.add(1);
12902            if c == b'x' || c == b'X' {
12903                base = 16;
12904                p = p.add(2);
12905                if !((*p >= b'0' && *p <= b'9')
12906                    || (*p >= b'a' && *p <= b'f')
12907                    || (*p >= b'A' && *p <= b'F')) {
12908                    return 0;
12909                }
12910            } else {
12911                base = 8;
12912            }
12913        }
12914        let mut v: u64 = 0;
12915        let start = p;
12916        loop {
12917            let c = *p;
12918            let d = if c >= b'0' && c <= b'9' {
12919                (c - b'0') as u64
12920            } else if base == 16 && c >= b'a' && c <= b'f' {
12921                (c - b'a' + 10) as u64
12922            } else if base == 16 && c >= b'A' && c <= b'F' {
12923                (c - b'A' + 10) as u64
12924            } else {
12925                break;
12926            };
12927            v = v * (base as u64) + d;
12928            p = p.add(1);
12929        }
12930        if p == start { return 0; }
12931        vals[i] = v;
12932        if *p == 0 {
12933            break;
12934        }
12935        if *p != b'.' || i == 3 { return 0; }
12936        p = p.add(1);
12937        i += 1;
12938    }
12939    if i == 4 { return 0; }
12940    if i < 1 { vals[1] = vals[0] & 0xffffff; vals[0] >>= 24; }
12941    if i < 2 { vals[2] = vals[1] & 0xffff; vals[1] >>= 16; }
12942    if i < 3 { vals[3] = vals[2] & 0xff; vals[2] >>= 8; }
12943    for j in 0..4 {
12944        if vals[j] > 255 { return 0; }
12945        *a.add(j) = vals[j] as u8;
12946    }
12947    1
12948}
12949
12950#[no_mangle]
12951pub unsafe extern "C" fn inet_addr(s: *const c_char) -> u32 {
12952    let mut a = [0u8; 4];
12953    if inet_aton(s, a.as_mut_ptr() as *mut c_void) == 1 {
12954        u32::from_ne_bytes(a)
12955    } else {
12956        !0u32 // INADDR_NONE
12957    }
12958}
12959
12960#[no_mangle]
12961pub unsafe extern "C" fn inet_ntoa(addr: u32) -> *mut c_char {
12962    static mut NTOA_BUF: [c_char; 16] = [0; 16];
12963    let b = addr.to_ne_bytes();
12964    let mut pos = 0;
12965    for i in 0..4 {
12966        if i > 0 { NTOA_BUF[pos] = b'.' as c_char; pos += 1; }
12967        let (buf, len) = format_u64(b[i] as u64);
12968        for j in 0..len { NTOA_BUF[pos] = buf[j] as c_char; pos += 1; }
12969    }
12970    NTOA_BUF[pos] = 0;
12971    core::ptr::addr_of_mut!(NTOA_BUF).cast::<c_char>()
12972}
12973
12974// ponytail: inet_network/inet_makeaddr/inet_lnaof/inet_netof - simple implementations
12975#[no_mangle]
12976pub unsafe extern "C" fn inet_network(s: *const c_char) -> u32 {
12977    inet_addr(s).to_be()
12978}
12979
12980#[no_mangle]
12981pub extern "C" fn inet_makeaddr(net: c_int, host: c_int) -> u32 {
12982    let addr: u32;
12983    if (net as u32) < 128 {
12984        addr = (net as u32) << 24;
12985    } else if (net as u32) < 0x10000 {
12986        addr = (net as u32) << 16;
12987    } else if (net as u32) < 0x1000000 {
12988        addr = (net as u32) << 8;
12989    } else {
12990        addr = net as u32;
12991    }
12992    addr | (host as u32 & 0xffffffff)
12993}
12994
12995#[no_mangle]
12996pub extern "C" fn inet_lnaof(addr: u32) -> c_int {
12997    let h = u32::from_be(addr);
12998    if h < 0x80000000 { (h & 0x00ffffff) as c_int }
12999    else if h < 0xc0000000 { (h & 0x0000ffff) as c_int }
13000    else { (h & 0x000000ff) as c_int }
13001}
13002
13003#[no_mangle]
13004pub extern "C" fn inet_netof(addr: u32) -> c_int {
13005    let h = u32::from_be(addr);
13006    if h < 0x80000000 { (h >> 24) as c_int }
13007    else if h < 0xc0000000 { (h >> 16) as c_int }
13008    else { (h >> 8) as c_int }
13009}
13010
13011// ============================================================
13012// stdlib: strtod / strtof / strtold
13013// ============================================================
13014
13015// ponytail: correctly-rounded float parser.
13016// Decimal: collects digits into buffer, uses core::str::FromStr.
13017// Hex: u128 integer arithmetic with round-to-nearest-even.
13018// is_f32: true for strtof (f32::from_str), false for strtod/strtold (f64::from_str).
13019unsafe fn parse_float(s: *const u8, endptr: *mut *mut u8, is_f32: bool) -> f64 {
13020    let mut p = s;
13021    // skip whitespace
13022    while *p == b' ' || *p == b'\t' || *p == b'\n' || *p == b'\r' { p = p.add(1); }
13023    let mut neg = false;
13024    if *p == b'-' { neg = true; p = p.add(1); }
13025    else if *p == b'+' { p = p.add(1); }
13026
13027    // inf
13028    if (*p | 0x20) == b'i'
13029        && (*p.add(1) | 0x20) == b'n'
13030        && (*p.add(2) | 0x20) == b'f'
13031    {
13032        p = p.add(3);
13033        // optionally consume "inity"
13034        if (*p | 0x20) == b'i'
13035            && (*p.add(1) | 0x20) == b't'
13036            && (*p.add(2) | 0x20) == b'y'
13037        {
13038            p = p.add(3);
13039        }
13040        if !endptr.is_null() { *endptr = p as *mut u8; }
13041        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13042    }
13043    // nan
13044    if (*p | 0x20) == b'n'
13045        && (*p.add(1) | 0x20) == b'a'
13046        && (*p.add(2) | 0x20) == b'n'
13047    {
13048        p = p.add(3);
13049        // optionally consume (n-char-sequence)
13050        if *p == b'(' {
13051            p = p.add(1);
13052            while *p != 0 && *p != b')' { p = p.add(1); }
13053            if *p == b')' { p = p.add(1); }
13054        }
13055        if !endptr.is_null() { *endptr = p as *mut u8; }
13056        return if neg { -f64::NAN } else { f64::NAN };
13057    }
13058
13059    // hex float
13060    if *p == b'0' && (*p.add(1) == b'x' || *p.add(1) == b'X') {
13061        p = p.add(2);
13062        let mut mant: u128 = 0;
13063        let mut frac_hex: u32 = 0;
13064        let mut found = false;
13065        let mut in_frac = false;
13066
13067        loop {
13068            if let Some(d) = hex_val(*p) {
13069                if mant <= u128::MAX / 16 {
13070                    mant = mant * 16 + d as u128;
13071                }
13072                if in_frac { frac_hex += 1; }
13073                p = p.add(1);
13074                found = true;
13075            } else if *p == b'.' && !in_frac {
13076                in_frac = true;
13077                p = p.add(1);
13078            } else {
13079                break;
13080            }
13081        }
13082
13083        if !found {
13084            if !endptr.is_null() { *endptr = s as *mut u8; }
13085            return 0.0;
13086        }
13087
13088        // binary exponent p[+-]N
13089        let mut bin_exp: i32 = 0;
13090        if *p == b'p' || *p == b'P' {
13091            p = p.add(1);
13092            let mut exp_neg = false;
13093            if *p == b'-' { exp_neg = true; p = p.add(1); }
13094            else if *p == b'+' { p = p.add(1); }
13095            while *p >= b'0' && *p <= b'9' {
13096                if bin_exp < 100000 {
13097                    bin_exp = bin_exp * 10 + (*p - b'0') as i32;
13098                }
13099                p = p.add(1);
13100            }
13101            if exp_neg { bin_exp = -bin_exp; }
13102        }
13103
13104        if !endptr.is_null() { *endptr = p as *mut u8; }
13105        if mant == 0 { return if neg { -0.0 } else { 0.0 }; }
13106
13107        let total_exp = bin_exp as i64 - 4 * frac_hex as i64;
13108        return hex_mant_to_f64(mant, total_exp, neg);
13109    }
13110
13111    // decimal: collect into buffer, use from_str for correct rounding
13112    let mut buf = [0u8; 65536];
13113    let mut n = 0usize;
13114    let mut found_digit = false;
13115
13116    while *p >= b'0' && *p <= b'9' {
13117        if n < 65535 { buf[n] = *p; n += 1; }
13118        p = p.add(1);
13119        found_digit = true;
13120    }
13121    if *p == b'.' {
13122        if n < 65535 { buf[n] = b'.'; n += 1; }
13123        p = p.add(1);
13124        while *p >= b'0' && *p <= b'9' {
13125            if n < 65535 { buf[n] = *p; n += 1; }
13126            p = p.add(1);
13127            found_digit = true;
13128        }
13129    }
13130    if !found_digit {
13131        if !endptr.is_null() { *endptr = s as *mut u8; }
13132        return 0.0;
13133    }
13134    if *p == b'e' || *p == b'E' {
13135        if n < 65535 { buf[n] = b'e'; n += 1; }
13136        p = p.add(1);
13137        if *p == b'-' || *p == b'+' {
13138            if n < 65535 { buf[n] = *p; n += 1; }
13139            p = p.add(1);
13140        }
13141        while *p >= b'0' && *p <= b'9' {
13142            if n < 65535 { buf[n] = *p; n += 1; }
13143            p = p.add(1);
13144        }
13145    }
13146
13147    if !endptr.is_null() { *endptr = p as *mut u8; }
13148    let s_str = core::str::from_utf8_unchecked(
13149        core::slice::from_raw_parts(buf.as_ptr(), n),
13150    );
13151    if is_f32 {
13152        match <f32 as core::str::FromStr>::from_str(s_str) {
13153            Ok(v) => { let r = v as f64; if neg { -r } else { r } }
13154            Err(_) => { if !endptr.is_null() { *endptr = s as *mut u8; } 0.0 }
13155        }
13156    } else {
13157        match <f64 as core::str::FromStr>::from_str(s_str) {
13158            Ok(v) => if neg { -v } else { v },
13159            Err(_) => { if !endptr.is_null() { *endptr = s as *mut u8; } 0.0 }
13160        }
13161    }
13162}
13163
13164// Convert hex mantissa integer to f64 with correct rounding.
13165// mant: integer from parsed hex digits. total_exp: bin_exp - 4 * frac_hex_digits.
13166// Value = mant * 2^total_exp.
13167fn hex_mant_to_f64(mant: u128, total_exp: i64, neg: bool) -> f64 {
13168    if mant == 0 { return if neg { -0.0 } else { 0.0 }; }
13169
13170    let msb = (127 - mant.leading_zeros()) as i64;
13171    let unbiased_exp = msb + total_exp;
13172    let biased_exp = unbiased_exp + 1023;
13173
13174    // Overflow → infinity
13175    if biased_exp >= 2047 {
13176        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13177    }
13178
13179    // Subnormal or underflow
13180    if biased_exp <= 0 {
13181        // subnormal: biased_exp=0, effective exponent=-1022
13182        // mantissa = round(mant * 2^(total_exp + 1074))
13183        let shift = total_exp + 1074;
13184        if shift < 0 {
13185            return if neg { -0.0 } else { 0.0 };
13186        }
13187        if shift > 128 {
13188            return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13189        }
13190        let shifted = mant << (shift as u32);
13191        let mantissa52 = (shifted as u64) & 0x000FFFFFFFFFFFFF;
13192        let guard = ((shifted >> 52) & 1) != 0;
13193        let sticky = (shifted >> 53) != 0;
13194        let mut result = mantissa52;
13195        if guard && (sticky || (result & 1) != 0) {
13196            result += 1;
13197            if result > 0x000FFFFFFFFFFFFF {
13198                // carry → smallest normal
13199                return if neg { -f64::from_bits(1u64 << 52) } else { f64::from_bits(1u64 << 52) };
13200            }
13201        }
13202        return if neg { -f64::from_bits(result) } else { f64::from_bits(result) };
13203    }
13204
13205    // Normal: biased_exp in [1, 2046]
13206    let shift = msb - 52;
13207
13208    if shift <= 0 {
13209        // fewer than 53 bits, no rounding needed
13210        let mantissa = ((mant as u64) & ((1u64 << msb as u32) - 1)) << ((-shift) as u32);
13211        let bits = ((biased_exp as u64) << 52) | mantissa;
13212        return if neg { -f64::from_bits(bits) } else { f64::from_bits(bits) };
13213    }
13214
13215    // shift > 0: round to nearest even
13216    let mantissa = ((mant >> shift as u32) as u64) & 0x000FFFFFFFFFFFFF;
13217    let guard = ((mant >> (shift as u32 - 1)) & 1) != 0;
13218    let sticky = if shift > 1 {
13219        (mant & ((1u128 << (shift as u32 - 1)) - 1)) != 0
13220    } else { false };
13221
13222    let mut result_mant = mantissa;
13223    let mut result_exp = biased_exp;
13224    if guard && (sticky || (result_mant & 1) != 0) {
13225        result_mant += 1;
13226        if result_mant > 0x000FFFFFFFFFFFFF {
13227            result_mant = 0;
13228            result_exp += 1;
13229            if result_exp >= 2047 {
13230                return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13231            }
13232        }
13233    }
13234
13235    let bits = ((result_exp as u64) << 52) | result_mant;
13236    if neg { -f64::from_bits(bits) } else { f64::from_bits(bits) }
13237}
13238
13239unsafe fn hex_val(c: u8) -> Option<u8> {
13240    if c >= b'0' && c <= b'9' { Some(c - b'0') }
13241    else if c >= b'a' && c <= b'f' { Some(c - b'a' + 10) }
13242    else if c >= b'A' && c <= b'F' { Some(c - b'A' + 10) }
13243    else { None }
13244}
13245
13246#[no_mangle]
13247pub unsafe extern "C" fn strtod(s: *const c_char, endptr: *mut *mut c_char) -> f64 {
13248    let mut end: *mut u8 = s as *mut u8;
13249    let r = parse_float(s as *const u8, &mut end, false);
13250    if !endptr.is_null() { *endptr = end as *mut c_char; }
13251    r
13252}
13253
13254#[no_mangle]
13255pub unsafe extern "C" fn strtof(s: *const c_char, endptr: *mut *mut c_char) -> f32 {
13256    let mut end: *mut u8 = s as *mut u8;
13257    let r = parse_float(s as *const u8, &mut end, true);
13258    if !endptr.is_null() { *endptr = end as *mut c_char; }
13259    r as f32
13260}
13261
13262#[no_mangle]
13263#[cfg(target_arch = "x86_64")]
13264pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f64 {
13265    strtod(s, endptr)
13266}
13267
13268#[no_mangle]
13269#[cfg(target_arch = "aarch64")]
13270pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f128 {
13271    strtod(s, endptr) as f128
13272}
13273
13274#[no_mangle]
13275#[cfg(target_arch = "riscv64")]
13276pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f128 {
13277    strtod(s, endptr) as f128
13278}
13279
13280#[no_mangle]
13281pub unsafe extern "C" fn atof(s: *const c_char) -> f64 {
13282    strtod(s, core::ptr::null_mut())
13283}
13284
13285// ============================================================
13286// stdio: open_memstream / fmemopen
13287// ============================================================
13288
13289#[repr(C)]
13290struct MsCookie {
13291    bufp: *mut *mut c_char,
13292    sizep: *mut usize,
13293    pos: usize,
13294    len: usize,
13295    buf: *mut u8,
13296    space: usize,
13297}
13298
13299#[repr(C)]
13300struct MfCookie {
13301    pos: usize,
13302    len: usize,
13303    size: usize,
13304    buf: *mut u8,
13305    mode: c_char,
13306}
13307
13308unsafe extern "C" fn ms_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
13309    let c = (*f).cookie as *mut MsCookie;
13310    if whence < 0 || whence > 2 { ERRNO!() = EINVAL; return -1; }
13311    let base: i64 = match whence {
13312        0 => 0,
13313        1 => (*c).pos as i64,
13314        2 => (*c).len as i64,
13315        _ => { ERRNO!() = EINVAL; return -1; }
13316    };
13317    if off < -base || off > isize::MAX as i64 - base { ERRNO!() = EINVAL; return -1; }
13318    (*c).pos = (base + off) as usize;
13319    (*c).pos as i64
13320}
13321
13322unsafe extern "C" fn ms_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
13323    let c = (*f).cookie as *mut MsCookie;
13324    let buffered = (*f).wpos as usize - (*f).wbase as usize;
13325    if buffered > 0 {
13326        (*f).wpos = (*f).wbase;
13327        if ms_write(f, (*f).wbase, buffered) < buffered { return 0; }
13328    }
13329    if len == 0 { return 0; }
13330    if (*c).pos + len >= (*c).space {
13331        let new_space = 2 * (*c).space + 1 | (*c).pos + len + 1;
13332        let newbuf = realloc((*c).buf as *mut c_void, new_space) as *mut u8;
13333        if newbuf.is_null() { return 0; }
13334        *(*c).bufp = newbuf as *mut c_char;
13335        core::ptr::write_bytes(newbuf.add((*c).space), 0, new_space - (*c).space);
13336        (*c).buf = newbuf;
13337        (*c).space = new_space;
13338    }
13339    core::ptr::copy_nonoverlapping(buf, (*c).buf.add((*c).pos), len);
13340    (*c).pos += len;
13341    if (*c).pos >= (*c).len { (*c).len = (*c).pos; }
13342    *(*c).sizep = (*c).pos;
13343    len
13344}
13345
13346unsafe extern "C" fn ms_close(_f: *mut FILE) -> c_int {
13347    0
13348}
13349
13350#[no_mangle]
13351pub unsafe extern "C" fn open_memstream(bufp: *mut *mut c_char, sizep: *mut usize) -> *mut FILE {
13352    if bufp.is_null() || sizep.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
13353    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
13354    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13355    let buf_area = buf_ptr(f);
13356    init_file(f, -1, b"w\0".as_ptr() as *const c_char, Some(ms_close), buf_area, BUFSIZ);
13357    (*f).flags = F_NORD | F_SVB;
13358    (*f).lbf = -1;
13359    let c = calloc(1, core::mem::size_of::<MsCookie>()) as *mut MsCookie;
13360    if c.is_null() { free(f as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13361    (*c).bufp = bufp;
13362    (*c).sizep = sizep;
13363    (*c).pos = 0;
13364    (*c).len = 0;
13365    (*c).buf = core::ptr::null_mut();
13366    (*c).space = 0;
13367    (*f).cookie = c as *mut c_void;
13368    (*f).write_fn = Some(ms_write);
13369    (*f).seek_fn = Some(ms_seek);
13370    *bufp = core::ptr::null_mut();
13371    *sizep = 0;
13372    f
13373}
13374
13375unsafe extern "C" fn mseek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
13376    let c = (*f).cookie as *mut MfCookie;
13377    if whence < 0 || whence > 2 { ERRNO!() = EINVAL; return -1; }
13378    let base: i64 = match whence {
13379        0 => 0,
13380        1 => (*c).pos as i64,
13381        2 => (*c).len as i64,
13382        _ => { ERRNO!() = EINVAL; return -1; }
13383    };
13384    if off < -base || off > (*c).size as i64 - base { ERRNO!() = EINVAL; return -1; }
13385    (*c).pos = (base + off) as usize;
13386    (*c).pos as i64
13387}
13388
13389unsafe extern "C" fn mread(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
13390    let c = (*f).cookie as *mut MfCookie;
13391    let mut rem = if (*c).pos <= (*c).len { (*c).len - (*c).pos } else { 0 };
13392    let mut l = len;
13393    if l > rem {
13394        l = rem;
13395        (*f).flags |= F_EOF;
13396    }
13397    core::ptr::copy_nonoverlapping((*c).buf.add((*c).pos), buf, l);
13398    (*c).pos += l;
13399    rem -= l;
13400    if rem > (*f).buf_size { rem = (*f).buf_size; }
13401    (*f).rpos = (*f).buf;
13402    (*f).rend = (*f).buf.add(rem);
13403    core::ptr::copy_nonoverlapping((*c).buf.add((*c).pos), (*f).rpos, rem);
13404    (*c).pos += rem;
13405    l
13406}
13407
13408unsafe extern "C" fn mwrite(f: *mut FILE, buf: *const u8, len: usize) -> usize {
13409    let c = (*f).cookie as *mut MfCookie;
13410    let buffered = (*f).wpos as usize - (*f).wbase as usize;
13411    if buffered > 0 {
13412        (*f).wpos = (*f).wbase;
13413        if mwrite(f, (*f).wbase, buffered) < buffered { return 0; }
13414    }
13415    if len == 0 { return 0; }
13416    if (*c).mode == b'a' as c_char { (*c).pos = (*c).len; }
13417    let rem = (*c).size - (*c).pos;
13418    let mut l = len;
13419    if l > rem { l = rem; }
13420    core::ptr::copy_nonoverlapping(buf, (*c).buf.add((*c).pos), l);
13421    (*c).pos += l;
13422    if (*c).pos > (*c).len {
13423        (*c).len = (*c).pos;
13424        if (*c).len < (*c).size {
13425            *(*c).buf.add((*c).len) = 0;
13426        } else if ((*f).flags & F_NORD) != 0 && (*c).size > 0 {
13427            *(*c).buf.add((*c).size - 1) = 0;
13428        }
13429    }
13430    l
13431}
13432
13433unsafe extern "C" fn mclose(_f: *mut FILE) -> c_int {
13434    0
13435}
13436
13437#[no_mangle]
13438pub unsafe extern "C" fn fmemopen(buf: *mut c_void, size: usize, mode: *const c_char) -> *mut FILE {
13439    if mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
13440    let m = *mode;
13441    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
13442        ERRNO!() = EINVAL; return core::ptr::null_mut();
13443    }
13444    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
13445    let need_alloc = buf.is_null();
13446    let alloc_size = core::mem::size_of::<FILE>() + UNGET + BUFSIZ + if need_alloc { size } else { 0 };
13447    let f = calloc(1, alloc_size) as *mut FILE;
13448    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13449    let buf_area = buf_ptr(f);
13450    init_file(f, -1, mode, Some(mclose), buf_area, BUFSIZ);
13451    (*f).flags |= F_SVB;
13452    let actual_buf: *mut u8 = if need_alloc {
13453        (f as *mut u8).add(alloc_size - size)
13454    } else {
13455        buf as *mut u8
13456    };
13457    if need_alloc { core::ptr::write_bytes(actual_buf, 0, size); }
13458    let c = calloc(1, core::mem::size_of::<MfCookie>()) as *mut MfCookie;
13459    if c.is_null() { free(f as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13460    (*c).buf = actual_buf;
13461    (*c).size = size;
13462    (*c).mode = m;
13463    (*f).cookie = c as *mut c_void;
13464    (*f).read_fn = Some(mread);
13465    (*f).write_fn = Some(mwrite);
13466    (*f).seek_fn = Some(mseek);
13467    if !has_plus { (*f).flags = if m == b'r' as c_char { F_NOWR } else { F_NORD }; }
13468    if m == b'r' as c_char {
13469        (*c).len = size;
13470    } else if m == b'a' as c_char {
13471        (*c).len = strnlen(actual_buf, size);
13472        (*c).pos = (*c).len;
13473    } else if has_plus {
13474        *actual_buf = 0;
13475    }
13476    f
13477}
13478
13479// ============================================================
13480// Stat (for ftok)
13481// ============================================================
13482
13483#[repr(C)]
13484struct kernel_stat64 {
13485    st_dev: u64,
13486    st_ino: u64,
13487    st_nlink: u64,
13488    st_mode: u32,
13489    st_uid: u32,
13490    st_gid: u32,
13491    __pad0: c_int,
13492    st_rdev: u64,
13493    st_size: i64,
13494    st_blksize: i64,
13495    st_blocks: i64,
13496    st_atime: i64,
13497    st_atime_nsec: i64,
13498    st_mtime: i64,
13499    st_mtime_nsec: i64,
13500    st_ctime: i64,
13501    st_ctime_nsec: i64,
13502    __unused: [i64; 3],
13503}
13504
13505// sys_stat = 4 on x86_64
13506#[inline]
13507unsafe fn sys_stat(path: *const u8, statbuf: *mut kernel_stat64) -> i64 {
13508    <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, statbuf as i64, 0)
13509}
13510
13511// ============================================================
13512// Search: hcreate/hdestroy/hsearch (hash table)
13513// ============================================================
13514
13515const HSEARCH_MINSIZE: usize = 8;
13516
13517#[repr(C)]
13518#[derive(Copy, Clone)]
13519pub struct HSearchEntry {
13520    key: *mut c_char,
13521    data: *mut c_void,
13522}
13523
13524#[repr(C)]
13525struct HTab {
13526    entries: *mut HSearchEntry,
13527    mask: usize,
13528    used: usize,
13529}
13530
13531#[repr(C)]
13532pub struct HSearchData {
13533    tab: *mut HTab,
13534    __unused1: c_uint,
13535    __unused2: c_uint,
13536}
13537
13538// ponytail: single static hash table for non-_r variants
13539static mut HTAB_DATA: HSearchData = HSearchData {
13540    tab: core::ptr::null_mut(),
13541    __unused1: 0,
13542    __unused2: 0,
13543};
13544
13545unsafe fn keyhash(k: *const c_char) -> usize {
13546    let mut h: usize = 0;
13547    let mut p = k;
13548    while *p != 0 {
13549        h = h.wrapping_mul(31).wrapping_add(*p as usize);
13550        p = p.add(1);
13551    }
13552    h
13553}
13554
13555unsafe fn htab_lookup(key: *const c_char, hash: usize, htab: *mut HSearchData) -> *mut HSearchEntry {
13556    let tab = (*htab).tab;
13557    let mask = (*tab).mask;
13558    let entries = (*tab).entries;
13559    let mut i = hash;
13560    let mut j: usize = 1;
13561    loop {
13562        let e = entries.add(i & mask);
13563        if (*e).key.is_null() || strcmp((*e).key as *const u8, key as *const u8) == 0 {
13564            return e;
13565        }
13566        i = i.wrapping_add(j);
13567        j += 1;
13568    }
13569}
13570
13571unsafe fn htab_resize(nel: usize, htab: *mut HSearchData) -> c_int {
13572    let tab = (*htab).tab;
13573    let old_entries = (*tab).entries;
13574    let old_size = (*tab).mask + 1;
13575
13576    let mut newsize: usize = HSEARCH_MINSIZE;
13577    while newsize < nel {
13578        let Some(next) = newsize.checked_mul(2) else {
13579            ERRNO!() = ENOMEM;
13580            return 0;
13581        };
13582        newsize = next;
13583    }
13584
13585    let new_entries = calloc(newsize, core::mem::size_of::<HSearchEntry>()) as *mut HSearchEntry;
13586    if new_entries.is_null() {
13587        ERRNO!() = ENOMEM;
13588        return 0;
13589    }
13590    (*tab).entries = new_entries;
13591    (*tab).mask = newsize - 1;
13592
13593    if !old_entries.is_null() {
13594        for idx in 0..old_size {
13595            let old_e = old_entries.add(idx);
13596            if !(*old_e).key.is_null() {
13597                let h = keyhash((*old_e).key);
13598                let mut i = h;
13599                let mut j: usize = 1;
13600                loop {
13601                    let e = new_entries.add(i & (*tab).mask);
13602                    if (*e).key.is_null() {
13603                        *e = *old_e;
13604                        break;
13605                    }
13606                    i = i.wrapping_add(j);
13607                    j += 1;
13608                }
13609            }
13610        }
13611        free(old_entries as *mut c_void);
13612    }
13613    1
13614}
13615
13616unsafe fn hcreate_r_impl(nel: usize, htab: *mut HSearchData) -> c_int {
13617    if nel == 0 || nel > (1usize << 30) {
13618        ERRNO!() = ENOMEM;
13619        return 0;
13620    }
13621    (*htab).tab = calloc(1, core::mem::size_of::<HTab>()) as *mut HTab;
13622    if (*htab).tab.is_null() {
13623        ERRNO!() = ENOMEM;
13624        return 0;
13625    }
13626    if htab_resize(nel, htab) == 0 {
13627        free((*htab).tab as *mut c_void);
13628        (*htab).tab = core::ptr::null_mut();
13629        return 0;
13630    }
13631    1
13632}
13633
13634unsafe fn hdestroy_r_impl(htab: *mut HSearchData) {
13635    if !(*htab).tab.is_null() {
13636        if !(*(*htab).tab).entries.is_null() {
13637            free((*(*htab).tab).entries as *mut c_void);
13638        }
13639        free((*htab).tab as *mut c_void);
13640        (*htab).tab = core::ptr::null_mut();
13641    }
13642}
13643
13644unsafe fn hsearch_r_impl(item: HSearchEntry, action: c_int, retval: *mut *mut HSearchEntry, htab: *mut HSearchData) -> c_int {
13645    let hash = keyhash(item.key);
13646    let e = htab_lookup(item.key, hash, htab);
13647
13648    if !(*e).key.is_null() {
13649        *retval = e;
13650        return 1;
13651    }
13652    if action == 0 { // FIND
13653        *retval = core::ptr::null_mut();
13654        return 0;
13655    }
13656    // ENTER
13657    let item_key = item.key;
13658    *e = item;
13659    (*(*htab).tab).used += 1;
13660    if (*(*htab).tab).used > (*(*htab).tab).mask - (*(*htab).tab).mask / 4 {
13661        if htab_resize(2 * (*(*htab).tab).used, htab) == 0 {
13662            (*(*htab).tab).used -= 1;
13663            (*e).key = core::ptr::null_mut();
13664            *retval = core::ptr::null_mut();
13665            return 0;
13666        }
13667        let e2 = htab_lookup(item_key, hash, htab);
13668        *retval = e2;
13669        return 1;
13670    }
13671    *retval = e;
13672    1
13673}
13674
13675#[no_mangle]
13676pub unsafe extern "C" fn hcreate(nel: usize) -> c_int {
13677    hcreate_r_impl(nel, core::ptr::addr_of_mut!(HTAB_DATA))
13678}
13679
13680#[no_mangle]
13681pub unsafe extern "C" fn hdestroy() {
13682    hdestroy_r_impl(core::ptr::addr_of_mut!(HTAB_DATA));
13683}
13684
13685#[no_mangle]
13686pub unsafe extern "C" fn hsearch(item: HSearchEntry, action: c_int) -> *mut HSearchEntry {
13687    let mut e: *mut HSearchEntry = core::ptr::null_mut();
13688    hsearch_r_impl(item, action, &mut e, core::ptr::addr_of_mut!(HTAB_DATA));
13689    e
13690}
13691
13692#[no_mangle]
13693pub unsafe extern "C" fn hcreate_r(nel: usize, htab: *mut HSearchData) -> c_int {
13694    hcreate_r_impl(nel, htab)
13695}
13696
13697#[no_mangle]
13698pub unsafe extern "C" fn hdestroy_r(htab: *mut HSearchData) {
13699    hdestroy_r_impl(htab);
13700}
13701
13702#[no_mangle]
13703pub unsafe extern "C" fn hsearch_r(item: HSearchEntry, action: c_int, retval: *mut *mut HSearchEntry, htab: *mut HSearchData) -> c_int {
13704    hsearch_r_impl(item, action, retval, htab)
13705}
13706
13707// ============================================================
13708// Search: insque / remque
13709// ============================================================
13710
13711#[repr(C)]
13712struct QueNode {
13713    next: *mut QueNode,
13714    prev: *mut QueNode,
13715}
13716
13717#[no_mangle]
13718pub unsafe extern "C" fn insque(element: *mut c_void, pred: *mut c_void) {
13719    let e = element as *mut QueNode;
13720    let p = pred as *mut QueNode;
13721    if p.is_null() {
13722        (*e).next = core::ptr::null_mut();
13723        (*e).prev = core::ptr::null_mut();
13724        return;
13725    }
13726    (*e).next = (*p).next;
13727    (*e).prev = p;
13728    (*p).next = e;
13729    if !(*e).next.is_null() {
13730        (*(*e).next).prev = e;
13731    }
13732}
13733
13734#[no_mangle]
13735pub unsafe extern "C" fn remque(element: *mut c_void) {
13736    let e = element as *mut QueNode;
13737    if !(*e).next.is_null() {
13738        (*(*e).next).prev = (*e).prev;
13739    }
13740    if !(*e).prev.is_null() {
13741        (*(*e).prev).next = (*e).next;
13742    }
13743}
13744
13745// ============================================================
13746// Search: lsearch / lfind
13747// ============================================================
13748
13749#[no_mangle]
13750pub unsafe extern "C" fn lsearch(
13751    key: *const c_void,
13752    base: *mut c_void,
13753    nelp: *mut usize,
13754    width: usize,
13755    compar: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
13756) -> *mut c_void {
13757    let n = *nelp;
13758    let p = base as *mut u8;
13759    for i in 0..n {
13760        let elem = p.add(i * width);
13761        if compar.unwrap()(key, elem as *const c_void) == 0 {
13762            return elem as *mut c_void;
13763        }
13764    }
13765    let dest = p.add(n * width);
13766    memcpy(dest as *mut c_void, key as *const c_void, width);
13767    *nelp = n + 1;
13768    dest as *mut c_void
13769}
13770
13771#[no_mangle]
13772pub unsafe extern "C" fn lfind(
13773    key: *const c_void,
13774    base: *const c_void,
13775    nelp: *mut usize,
13776    width: usize,
13777    compar: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
13778) -> *mut c_void {
13779    let n = *nelp;
13780    let p = base as *const u8;
13781    for i in 0..n {
13782        let elem = p.add(i * width);
13783        if compar.unwrap()(key, elem as *const c_void) == 0 {
13784            return elem as *mut c_void;
13785        }
13786    }
13787    core::ptr::null_mut()
13788}
13789
13790// ============================================================
13791// Search: tsearch / tfind / tdelete / twalk / tdestroy (BST, no balancing)
13792// ============================================================
13793
13794// ponytail: simple BST, no balancing; correct for tests, O(n) worst case
13795#[repr(C)]
13796pub struct TreeNode {
13797    key: *const c_void,
13798    left: *mut TreeNode,
13799    right: *mut TreeNode,
13800}
13801
13802type ComparFn = Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>;
13803
13804unsafe fn bst_new(key: *const c_void) -> *mut TreeNode {
13805    let n = calloc(1, core::mem::size_of::<TreeNode>()) as *mut TreeNode;
13806    if !n.is_null() {
13807        (*n).key = key;
13808        (*n).left = core::ptr::null_mut();
13809        (*n).right = core::ptr::null_mut();
13810    }
13811    n
13812}
13813
13814#[no_mangle]
13815pub unsafe extern "C" fn tsearch(
13816    key: *const c_void,
13817    rootp: *mut *mut TreeNode,
13818    compar: ComparFn,
13819) -> *mut c_void {
13820    if rootp.is_null() {
13821        return core::ptr::null_mut();
13822    }
13823    let mut pp = rootp;
13824    loop {
13825        let n = *pp;
13826        if n.is_null() {
13827            let r = bst_new(key);
13828            if r.is_null() {
13829                return core::ptr::null_mut();
13830            }
13831            *pp = r;
13832            return r as *mut c_void;
13833        }
13834        let c = compar.unwrap()(key, (*n).key);
13835        if c == 0 {
13836            return n as *mut c_void;
13837        }
13838        if c < 0 {
13839            pp = &mut (*n).left;
13840        } else {
13841            pp = &mut (*n).right;
13842        }
13843    }
13844}
13845
13846#[no_mangle]
13847pub unsafe extern "C" fn tfind(
13848    key: *const c_void,
13849    rootp: *const *mut TreeNode,
13850    compar: ComparFn,
13851) -> *mut c_void {
13852    if rootp.is_null() {
13853        return core::ptr::null_mut();
13854    }
13855    let mut n = *rootp;
13856    loop {
13857        if n.is_null() {
13858            return core::ptr::null_mut();
13859        }
13860        let c = compar.unwrap()(key, (*n).key);
13861        if c == 0 {
13862            return n as *mut c_void;
13863        }
13864        if c < 0 {
13865            n = (*n).left;
13866        } else {
13867            n = (*n).right;
13868        }
13869    }
13870}
13871
13872#[no_mangle]
13873pub unsafe extern "C" fn tdelete(
13874    key: *const c_void,
13875    rootp: *mut *mut TreeNode,
13876    compar: ComparFn,
13877) -> *mut c_void {
13878    if rootp.is_null() {
13879        return core::ptr::null_mut();
13880    }
13881    let mut pp = rootp;
13882    loop {
13883        let n = *pp;
13884        if n.is_null() {
13885            return core::ptr::null_mut();
13886        }
13887        let c = compar.unwrap()(key, (*n).key);
13888        if c == 0 {
13889            break;
13890        }
13891        if c < 0 {
13892            pp = &mut (*n).left;
13893        } else {
13894            pp = &mut (*n).right;
13895        }
13896    }
13897    let n = *pp;
13898    // parent is *rootp if we went to root, otherwise the node above
13899    let parent = *rootp;
13900    if !(*n).left.is_null() {
13901        // replace with in-order predecessor
13902        let mut q = &mut (*n).left;
13903        while !(*(*q)).right.is_null() {
13904            q = &mut (*(*q)).right;
13905        }
13906        let pred = *q;
13907        // swap keys
13908        (*n).key = (*pred).key;
13909        // remove predecessor
13910        *q = (*pred).left;
13911        free(pred as *mut c_void);
13912    } else {
13913        // replace with right child (may be null)
13914        *pp = (*n).right;
13915        free(n as *mut c_void);
13916    }
13917    parent as *mut c_void
13918}
13919
13920#[no_mangle]
13921pub unsafe extern "C" fn twalk(
13922    root: *const TreeNode,
13923    action: Option<unsafe extern "C" fn(*const c_void, c_int, c_int)>,
13924) {
13925    unsafe fn walk(
13926        node: *const TreeNode,
13927        action: Option<unsafe extern "C" fn(*const c_void, c_int, c_int)>,
13928        depth: c_int,
13929    ) {
13930        if node.is_null() {
13931            return;
13932        }
13933        let is_leaf = (*node).left.is_null() && (*node).right.is_null();
13934        if is_leaf {
13935            action.unwrap()(node as *const c_void, 3, depth); // leaf
13936        } else {
13937            action.unwrap()(node as *const c_void, 0, depth); // preorder
13938            walk((*node).left, action, depth + 1);
13939            action.unwrap()(node as *const c_void, 1, depth); // postorder (left done)
13940            walk((*node).right, action, depth + 1);
13941            action.unwrap()(node as *const c_void, 2, depth); // endorder
13942        }
13943    }
13944    walk(root, action, 0);
13945}
13946
13947#[no_mangle]
13948pub unsafe extern "C" fn tdestroy(root: *mut TreeNode, freekey: Option<unsafe extern "C" fn(*mut c_void)>) {
13949    if root.is_null() {
13950        return;
13951    }
13952    tdestroy((*root).left, freekey);
13953    tdestroy((*root).right, freekey);
13954    if let Some(f) = freekey {
13955        f((*root).key as *mut c_void);
13956    }
13957    free(root as *mut c_void);
13958}
13959
13960// ============================================================
13961// fnmatch: full POSIX pattern matching
13962// ============================================================
13963
13964const FNM_PATHNAME: c_int = 0x1;
13965const FNM_NOESCAPE: c_int = 0x2;
13966const FNM_PERIOD: c_int = 0x4;
13967const FNM_LEADING_DIR: c_int = 0x8;
13968const FNM_CASEFOLD: c_int = 0x10;
13969const FNM_NOMATCH: c_int = 1;
13970
13971const FNM_END: c_int = 0;
13972const FNM_STAR: c_int = -5;
13973const FNM_QUESTION: c_int = -4;
13974const FNM_BRACKET: c_int = -3;
13975const FNM_UNMATCHABLE: c_int = -2;
13976
13977fn ascii_tolower(c: u8) -> u8 {
13978    if c >= b'A' && c <= b'Z' { c + 32 } else { c }
13979}
13980
13981fn ascii_toupper(c: u8) -> u8 {
13982    if c >= b'a' && c <= b'z' { c - 32 } else { c }
13983}
13984
13985fn ascii_casefold(k: u8) -> u8 {
13986    let upper = ascii_toupper(k);
13987    if upper != k { upper } else { ascii_tolower(k) }
13988}
13989
13990/// Get next byte from pattern, classifying it.
13991/// Returns (token_type, bytes_consumed).
13992unsafe fn pat_next(pat: *const u8, m: usize, flags: c_int) -> (c_int, usize) {
13993    if m == 0 || *pat == 0 {
13994        return (FNM_END, 0);
13995    }
13996    let mut p = pat;
13997    let mut step = 1usize;
13998    let mut esc = false;
13999    if *p == b'\\' && !(flags & FNM_NOESCAPE != 0) && *p.add(1) != 0 {
14000        p = p.add(1);
14001        step = 2;
14002        esc = true;
14003    }
14004    if *p == b'[' && !esc {
14005        // scan for matching ]
14006        let mut k = 1usize;
14007        if k < m && (*pat.add(k) == b'^' || *pat.add(k) == b'!') { k += 1; }
14008        if k < m && *pat.add(k) == b']' { k += 1; }
14009        while k < m && *pat.add(k) != 0 && *pat.add(k) != b']' {
14010            if k + 1 < m && *pat.add(k) == b'[' &&
14011               (*pat.add(k+1) == b':' || *pat.add(k+1) == b'.' || *pat.add(k+1) == b'=') {
14012                let z = *pat.add(k+1);
14013                k += 2;
14014                if k < m { k += 1; }
14015                while k < m && *pat.add(k) != 0 && (*pat.add(k-1) != z || *pat.add(k) != b']') { k += 1; }
14016                if k == m || *pat.add(k) == 0 { break; }
14017            }
14018            k += 1;
14019        }
14020        if k == m || *pat.add(k) == 0 {
14021            // unmatched [ is literal
14022            return (b'[' as c_int, 1);
14023        }
14024        return (FNM_BRACKET, k + 1);
14025    }
14026    if *p == b'*' && !esc {
14027        return (FNM_STAR, 1);
14028    }
14029    if *p == b'?' && !esc {
14030        return (FNM_QUESTION, 1);
14031    }
14032    (*p as c_int, step)
14033}
14034
14035unsafe fn match_class(name: &[u8], k: u8, kfold: u8) -> bool {
14036    let eq = |c: u8| k == c || kfold == c;
14037    let in_range = |lo: u8, hi: u8| (k >= lo && k <= hi) || (kfold >= lo && kfold <= hi);
14038    match name {
14039        b"alnum" => in_range(b'0', b'9') || in_range(b'A', b'Z') || in_range(b'a', b'z'),
14040        b"alpha" => in_range(b'A', b'Z') || in_range(b'a', b'z'),
14041        b"blank" => eq(b' ') || eq(b'\t'),
14042        b"cntrl" => k < 0x20 || k == 0x7f,
14043        b"digit" => in_range(b'0', b'9'),
14044        b"graph" => k >= 0x21 && k <= 0x7e,
14045        b"lower" => in_range(b'a', b'z'),
14046        b"print" => k >= 0x20 && k <= 0x7e,
14047        b"punct" =>
14048            (k >= 0x21 && k <= 0x2f) ||
14049            (k >= 0x3a && k <= 0x40) ||
14050            (k >= 0x5b && k <= 0x60) ||
14051            (k >= 0x7b && k <= 0x7e),
14052        b"space" => eq(b' ') || eq(b'\t') || eq(b'\n') || eq(b'\r') || eq(0x0c) || eq(0x0b),
14053        b"upper" => in_range(b'A', b'Z'),
14054        b"xdigit" => in_range(b'0', b'9') || in_range(b'A', b'F') || in_range(b'a', b'f'),
14055        _ => false,
14056    }
14057}
14058
14059/// Match a bracket expression [class] against char k.
14060unsafe fn match_bracket(mut p: *const u8, k: u8, kfold: u8) -> bool {
14061    let mut inv = false;
14062    p = p.add(1); // skip [
14063    if *p == b'^' || *p == b'!' {
14064        inv = true;
14065        p = p.add(1);
14066    }
14067    // handle ] as first char
14068    if *p == b']' {
14069        if k == b']' { return !inv; }
14070        p = p.add(1);
14071    } else if *p == b'-' {
14072        if k == b'-' { return !inv; }
14073        p = p.add(1);
14074    }
14075    while *p != b']' && *p != 0 {
14076        if *p == b'-' && *p.add(1) != b']' && *p.add(1) != 0 {
14077            // range: previous char to next char
14078            let lo = *p.sub(1);
14079            let hi = *p.add(1);
14080            if lo <= hi && (k >= lo && k <= hi || kfold >= lo && kfold <= hi) {
14081                return !inv;
14082            }
14083            p = p.add(2);
14084        } else if *p == b'[' && (*p.add(1) == b':' || *p.add(1) == b'.' || *p.add(1) == b'=') {
14085            let z = *p.add(1);
14086            let start = p.add(2);
14087            let mut q = start;
14088            while *q != 0 && (*q != z || *q.add(1) != b']') { q = q.add(1); }
14089            if *q != 0 {
14090                let len = (q as usize) - (start as usize);
14091                if len > 0 {
14092                    let inner = core::slice::from_raw_parts(start, len);
14093                    let matched =
14094                        if z == b':' { match_class(inner, k, kfold) }
14095                        else { len == 1 && (inner[0] == k || inner[0] == kfold) };
14096                    if matched { return !inv; }
14097                }
14098                p = q.add(2);
14099                continue;
14100            }
14101        } else {
14102            if *p == k || *p == kfold {
14103                return !inv;
14104            }
14105            p = p.add(1);
14106        }
14107    }
14108    inv
14109}
14110
14111/// Core fnmatch for a single path component (no FNM_PATHNAME splitting).
14112unsafe fn fnmatch_internal(pat: *const u8, str: *const u8, flags: c_int) -> c_int {
14113    // Handle leading .
14114    if flags & FNM_PERIOD != 0 && *str == b'.' && *pat != b'.' {
14115        return FNM_NOMATCH;
14116    }
14117
14118    let mut p = pat;
14119    let mut s = str;
14120
14121    // Consume pattern up to first *
14122    loop {
14123        let (tok, step) = pat_next(p, usize::MAX, flags);
14124        match tok {
14125            FNM_END => {
14126                return if *s == 0 { 0 } else { FNM_NOMATCH };
14127            }
14128            FNM_STAR => {
14129                p = p.add(1);
14130                break;
14131            }
14132            FNM_QUESTION => {
14133                if *s == 0 { return FNM_NOMATCH; }
14134                s = s.add(1);
14135                p = p.add(step);
14136            }
14137            FNM_BRACKET => {
14138                if *s == 0 { return FNM_NOMATCH; }
14139                let k = *s;
14140                let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14141                if !match_bracket(p, k, kfold) { return FNM_NOMATCH; }
14142                p = p.add(step);
14143                s = s.add(1);
14144            }
14145            c => {
14146                if *s == 0 { return FNM_NOMATCH; }
14147                let k = *s;
14148                let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14149                if k as c_int != c && kfold as c_int != c { return FNM_NOMATCH; }
14150                p = p.add(step);
14151                s = s.add(1);
14152            }
14153        }
14154    }
14155
14156    // Now p points after first *, rest of pattern is variable
14157    // Factor: find tail after last * and count fixed chars needed
14158    let mut ptail = p;
14159    let mut tailcnt: usize = 0;
14160    let mut pp = p;
14161    loop {
14162        let (tok, step) = pat_next(pp, usize::MAX, flags);
14163        if tok == FNM_END { break; }
14164        if tok == FNM_STAR {
14165            tailcnt = 0;
14166            ptail = pp.add(1);
14167        } else {
14168            tailcnt += 1;
14169        }
14170        pp = pp.add(step);
14171    }
14172
14173    // str must have at least tailcnt chars
14174    let slen = strlen(s as *const c_char);
14175    if slen < tailcnt { return FNM_NOMATCH; }
14176
14177    // Match tail: ptail..end against str[tailcnt from end]
14178    let stail = s.add(slen - tailcnt);
14179    let mut tp = ptail;
14180    let mut ts = stail;
14181    loop {
14182        let (tok, step) = pat_next(tp, usize::MAX, flags);
14183        tp = tp.add(step);
14184        if tok == FNM_END {
14185            break;
14186        }
14187        let k = *ts;
14188        if k == 0 { return FNM_NOMATCH; }
14189        let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14190        match tok {
14191            FNM_QUESTION => { ts = ts.add(1); }
14192            FNM_BRACKET => {
14193                if !match_bracket(tp.sub(step), k, kfold) { return FNM_NOMATCH; }
14194                ts = ts.add(1);
14195            }
14196            c => {
14197                if k as c_int != c && kfold as c_int != c { return FNM_NOMATCH; }
14198                ts = ts.add(1);
14199            }
14200        }
14201    }
14202
14203    let endstr = stail;
14204    let endpat = ptail;
14205
14206    let mut cp = p;
14207    let mut cs = s;
14208    while cp < endpat {
14209        let (tok, step) = pat_next(cp, usize::MAX, flags);
14210        if tok == FNM_STAR {
14211            cp = cp.add(step);
14212            cs = s;
14213            continue;
14214        }
14215        let comp_start = cp;
14216        let mut ok = false;
14217        let mut try_s = cs;
14218        while try_s < endstr {
14219            let mut tmp_p = comp_start;
14220            let mut tmp_s = try_s;
14221            let mut matched = true;
14222            loop {
14223                let (t, st) = pat_next(tmp_p, usize::MAX, flags);
14224                if t == FNM_STAR || t == FNM_END {
14225                    cp = tmp_p;
14226                    cs = tmp_s;
14227                    ok = true;
14228                    break;
14229                }
14230                if *tmp_s == 0 {
14231                    matched = false;
14232                    break;
14233                }
14234                let k = *tmp_s;
14235                let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14236                match t {
14237                    FNM_QUESTION => {
14238                        tmp_s = tmp_s.add(1);
14239                    }
14240                    FNM_BRACKET => {
14241                        if !match_bracket(tmp_p, k, kfold) {
14242                            matched = false;
14243                            break;
14244                        }
14245                        tmp_s = tmp_s.add(1);
14246                    }
14247                    c => {
14248                        if k as c_int != c && kfold as c_int != c {
14249                            matched = false;
14250                            break;
14251                        }
14252                        tmp_s = tmp_s.add(1);
14253                    }
14254                }
14255                tmp_p = tmp_p.add(st);
14256            }
14257            if ok { break; }
14258            if !matched {
14259                try_s = try_s.add(1);
14260            }
14261        }
14262        if !ok {
14263            return FNM_NOMATCH;
14264        }
14265    }
14266    0
14267}
14268
14269#[no_mangle]
14270pub unsafe extern "C" fn fnmatch(pat: *const c_char, str: *const c_char, flags: c_int) -> c_int {
14271    let pat = pat as *const u8;
14272    let str = str as *const u8;
14273
14274    if flags & FNM_PATHNAME != 0 {
14275        // Split on /
14276        let mut s = str;
14277        let mut p = pat;
14278        loop {
14279            // find next / in str
14280            let mut send = s;
14281            while *send != 0 && *send != b'/' { send = send.add(1); }
14282            // find next / in pat
14283            let mut pend = p;
14284            loop {
14285                let (tok, step) = pat_next(pend, usize::MAX, flags);
14286                if tok == FNM_END || (tok >= 0 && tok as u8 == b'/') {
14287                    break;
14288                }
14289                pend = pend.add(step);
14290            }
14291            let (ptok, pstep) = pat_next(pend, usize::MAX, flags);
14292            let pat_is_slash = ptok >= 0 && ptok as u8 == b'/';
14293            let str_is_slash = *send == b'/';
14294            if pat_is_slash != str_is_slash && (*send != 0 || !(flags & FNM_LEADING_DIR != 0)) {
14295                return FNM_NOMATCH;
14296            }
14297            // match component
14298            // We need a null-terminated copy of the component
14299            let plen = (pend as usize) - (p as usize);
14300            let slen = (send as usize) - (s as usize);
14301            // Use stack buffers for components
14302            // ponytail: max component 1024 bytes
14303            if plen > 1024 || slen > 1024 { return FNM_NOMATCH; }
14304            let mut pbuf = [0u8; 1025];
14305            let mut sbuf = [0u8; 1025];
14306            core::ptr::copy_nonoverlapping(p, pbuf.as_mut_ptr(), plen);
14307            pbuf[plen] = 0;
14308            core::ptr::copy_nonoverlapping(s, sbuf.as_mut_ptr(), slen);
14309            sbuf[slen] = 0;
14310            if fnmatch_internal(pbuf.as_ptr(), sbuf.as_ptr(), flags & !FNM_LEADING_DIR) != 0 {
14311                return FNM_NOMATCH;
14312            }
14313            if !pat_is_slash {
14314                return 0;
14315            }
14316            s = send.add(1);
14317            p = pend.add(pstep);
14318        }
14319    }
14320
14321    if flags & FNM_LEADING_DIR != 0 {
14322        // Try matching at each /
14323        let mut s = str;
14324        while *s != 0 {
14325            if *s == b'/' {
14326                // temporarily null-terminate
14327                // ponytail: we need to copy. Use a simple approach.
14328                let len = (s as usize) - (str as usize);
14329                // Just call fnmatch_internal with a temp buffer
14330                if len < 4096 {
14331                    let mut buf = [0u8; 4096];
14332                    core::ptr::copy_nonoverlapping(str, buf.as_mut_ptr(), len);
14333                    buf[len] = 0;
14334                    if fnmatch_internal(pat, buf.as_ptr(), flags) == 0 {
14335                        return 0;
14336                    }
14337                }
14338            }
14339            s = s.add(1);
14340        }
14341    }
14342
14343    fnmatch_internal(pat, str, flags)
14344}
14345
14346// ============================================================
14347// mntent: setmntent/endmntent/getmntent/getmntent_r/addmntent/hasmntopt
14348// ============================================================
14349
14350#[no_mangle]
14351pub unsafe extern "C" fn setmntent(name: *const c_char, mode: *const c_char) -> *mut FILE {
14352    fopen(name, mode)
14353}
14354
14355#[no_mangle]
14356pub unsafe extern "C" fn endmntent(f: *mut FILE) -> c_int {
14357    if !f.is_null() {
14358        fclose(f);
14359    }
14360    1
14361}
14362
14363// ponytail: static buffers for getmntent (non-_r variant)
14364static mut MNTENT_MNT: MntEnt = MntEnt {
14365    mnt_fsname: core::ptr::null_mut(),
14366    mnt_dir: core::ptr::null_mut(),
14367    mnt_type: core::ptr::null_mut(),
14368    mnt_opts: core::ptr::null_mut(),
14369    mnt_freq: 0,
14370    mnt_passno: 0,
14371};
14372
14373#[repr(C)]
14374pub struct MntEnt {
14375    mnt_fsname: *mut c_char,
14376    mnt_dir: *mut c_char,
14377    mnt_type: *mut c_char,
14378    mnt_opts: *mut c_char,
14379    mnt_freq: c_int,
14380    mnt_passno: c_int,
14381}
14382
14383unsafe fn unescape_ent(beg: *mut c_char) -> *mut c_char {
14384    let mut dest = beg;
14385    let mut src = beg;
14386    while *src != 0 {
14387        if *src != b'\\' as c_char {
14388            *dest = *src;
14389            dest = dest.add(1);
14390            src = src.add(1);
14391            continue;
14392        }
14393        // backslash
14394        if *src.add(1) == b'\\' as c_char {
14395            src = src.add(1);
14396            *dest = *src;
14397            dest = dest.add(1);
14398            src = src.add(1);
14399            continue;
14400        }
14401        // octal escape
14402        let mut val: u8 = 0;
14403        let mut cnt = 0;
14404        let mut sp = src.add(1);
14405        while cnt < 3 && *sp >= b'0' as c_char && *sp <= b'7' as c_char {
14406            val = val * 8 + (*sp as u8 - b'0');
14407            sp = sp.add(1);
14408            cnt += 1;
14409        }
14410        if cnt > 0 {
14411            *dest = val as c_char;
14412            dest = dest.add(1);
14413            src = sp;
14414        } else {
14415            *dest = *src;
14416            dest = dest.add(1);
14417            src = src.add(1);
14418        }
14419    }
14420    *dest = 0;
14421    beg
14422}
14423
14424unsafe fn parse_mntent_line(
14425    linebuf: *mut c_char,
14426    mnt: *mut MntEnt,
14427) -> *mut MntEnt {
14428    let _len = strlen(linebuf as *const c_char);
14429    // skip comments and empty lines
14430    // parse: fsname dir type opts freq passno
14431    let mut p = linebuf;
14432    // skip leading whitespace
14433    while *p == b' ' as c_char || *p == b'\t' as c_char || *p == b'\n' as c_char || *p == b'\r' as c_char {
14434        p = p.add(1);
14435    }
14436    if *p == 0 || *p == b'#' as c_char {
14437        return core::ptr::null_mut();
14438    }
14439
14440    // fsname
14441    (*mnt).mnt_fsname = p;
14442    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14443        p = p.add(1);
14444    }
14445    if *p == 0 { return core::ptr::null_mut(); }
14446    *p = 0;
14447    p = p.add(1);
14448    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14449
14450    // dir
14451    (*mnt).mnt_dir = p;
14452    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14453        p = p.add(1);
14454    }
14455    if *p == 0 { return core::ptr::null_mut(); }
14456    *p = 0;
14457    p = p.add(1);
14458    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14459
14460    // type
14461    (*mnt).mnt_type = p;
14462    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14463        p = p.add(1);
14464    }
14465    if *p == 0 { return core::ptr::null_mut(); }
14466    *p = 0;
14467    p = p.add(1);
14468    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14469
14470    // opts
14471    (*mnt).mnt_opts = p;
14472    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14473        p = p.add(1);
14474    }
14475    if *p != 0 {
14476        *p = 0;
14477        p = p.add(1);
14478    }
14479    if *(*mnt).mnt_opts == 0 {
14480        (*mnt).mnt_opts = b"defaults\0".as_ptr() as *mut c_char;
14481    }
14482
14483    // freq and passno
14484    (*mnt).mnt_freq = 0;
14485    (*mnt).mnt_passno = 0;
14486    // skip whitespace
14487    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14488    if *p >= b'0' as c_char && *p <= b'9' as c_char {
14489        (*mnt).mnt_freq = (*p - b'0' as c_char) as c_int;
14490        p = p.add(1);
14491        while *p >= b'0' as c_char && *p <= b'9' as c_char {
14492            (*mnt).mnt_freq = (*mnt).mnt_freq * 10 + (*p - b'0' as c_char) as c_int;
14493            p = p.add(1);
14494        }
14495    }
14496    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14497    if *p >= b'0' as c_char && *p <= b'9' as c_char {
14498        (*mnt).mnt_passno = (*p - b'0' as c_char) as c_int;
14499        p = p.add(1);
14500        while *p >= b'0' as c_char && *p <= b'9' as c_char {
14501            (*mnt).mnt_passno = (*mnt).mnt_passno * 10 + (*p - b'0' as c_char) as c_int;
14502            p = p.add(1);
14503        }
14504    }
14505
14506    // unescape
14507    unescape_ent((*mnt).mnt_fsname);
14508    unescape_ent((*mnt).mnt_dir);
14509    unescape_ent((*mnt).mnt_type);
14510    unescape_ent((*mnt).mnt_opts);
14511
14512    mnt
14513}
14514
14515// Use a sentinel pointer to detect internal buffer usage
14516// ponytail: cast integer to pointer for sentinel
14517static SENTINEL_PTR: usize = 1;
14518
14519// Read one char from FILE buffer directly (avoids musl's static fgets ABI mismatch)
14520unsafe fn mntent_fgetc(f: *mut FILE) -> c_int {
14521    fgetc(f)
14522}
14523
14524unsafe fn mntent_fgets(buf: *mut c_char, n: usize, f: *mut FILE) -> *mut c_char {
14525    if n == 0 { return core::ptr::null_mut(); }
14526    let max = n - 1;
14527    let mut i = 0usize;
14528    while i < max {
14529        let c = mntent_fgetc(f);
14530        if c == -1 { if i == 0 { return core::ptr::null_mut(); } break; }
14531        *buf.add(i) = c as c_char;
14532        i += 1;
14533        if c == b'\n' as c_int { break; }
14534    }
14535    *buf.add(i) = 0;
14536    buf
14537}
14538
14539#[no_mangle]
14540pub unsafe extern "C" fn getmntent_r(
14541    f: *mut FILE,
14542    mnt: *mut MntEnt,
14543    mut linebuf: *mut c_char,
14544    buflen: c_int,
14545) -> *mut MntEnt {
14546    let use_internal = linebuf as usize == SENTINEL_PTR;
14547
14548    (*mnt).mnt_freq = 0;
14549    (*mnt).mnt_passno = 0;
14550
14551    static mut MNT_LINE: *mut c_char = core::ptr::null_mut();
14552    static mut MNT_LINE_CAP: usize = 0;
14553
14554    loop {
14555        let res = if use_internal {
14556            let n = getline(&raw mut MNT_LINE, &raw mut MNT_LINE_CAP, f);
14557            if n < 0 {
14558                return core::ptr::null_mut();
14559            }
14560            linebuf = MNT_LINE;
14561            MNT_LINE
14562        } else {
14563            if buflen <= 0 {
14564                ERRNO!() = EINVAL;
14565                return core::ptr::null_mut();
14566            }
14567            mntent_fgets(linebuf, buflen as usize, f)
14568        };
14569        if res.is_null() {
14570            return core::ptr::null_mut();
14571        }
14572        let mut has_newline = false;
14573        let mut p = linebuf;
14574        while *p != 0 { if *p == b'\n' as c_char { has_newline = true; break; } p = p.add(1); }
14575        if !has_newline {
14576            ERRNO!() = 34;
14577            return core::ptr::null_mut();
14578        }
14579        let result = parse_mntent_line(linebuf, mnt);
14580        if !result.is_null() {
14581            return result;
14582        }
14583    }
14584}
14585
14586#[no_mangle]
14587pub unsafe extern "C" fn getmntent(f: *mut FILE) -> *mut MntEnt {
14588    getmntent_r(f, core::ptr::addr_of_mut!(MNTENT_MNT), SENTINEL_PTR as *mut c_char, 0)
14589}
14590
14591#[no_mangle]
14592pub unsafe extern "C" fn addmntent(f: *mut FILE, mnt: *const MntEnt) -> c_int {
14593    fseek(f, 0, 2); // SEEK_END
14594    let written = fprintf(
14595        f,
14596        b"%s\t%s\t%s\t%s\t%d\t%d\n\0".as_ptr() as *const c_char,
14597        (*mnt).mnt_fsname,
14598        (*mnt).mnt_dir,
14599        (*mnt).mnt_type,
14600        (*mnt).mnt_opts,
14601        (*mnt).mnt_freq,
14602        (*mnt).mnt_passno,
14603    );
14604    if written < 0 { 1 } else { 0 }
14605}
14606
14607#[no_mangle]
14608pub unsafe extern "C" fn hasmntopt(mnt: *const MntEnt, opt: *const c_char) -> *mut c_char {
14609    let l = strlen(opt as *const c_char);
14610    let mut p = (*mnt).mnt_opts;
14611    loop {
14612        if strncmp(p as *const u8, opt as *const u8, l) == 0 {
14613            let after = *p.add(l);
14614            if after == 0 || after == b',' as c_char || after == b'=' as c_char {
14615                return p;
14616            }
14617        }
14618        let comma = strchr(p as *const u8, b',' as c_int);
14619        if comma.is_null() {
14620            return core::ptr::null_mut();
14621        }
14622        p = comma.add(1) as *mut c_char;
14623    }
14624}
14625
14626// ============================================================
14627// SysV IPC: ftok, msg*, sem*, shm*
14628// x86_64 direct syscalls: msgget=68, msgsnd=69, msgrcv=70, msgctl=71
14629//   semget=64, semop=65, semctl=66, semtimedop=220
14630//   shmget=29, shmat=30, shmctl=31, shmdt=67
14631// ============================================================
14632
14633const EEXIST: c_int = 17;
14634const ENAMETOOLONG: c_int = 36;
14635const EMFILE: c_int = 24;
14636const EIDRM: c_int = 43;
14637
14638#[inline]
14639unsafe fn sys_msgget(key: c_int, msgflg: c_int) -> i64 {
14640    <Arch as Syscalls>::syscall2(SYS_MSGGET, key as i64, msgflg as i64)
14641}
14642
14643#[inline]
14644unsafe fn sys_msgsnd(msqid: c_int, msgp: *const c_void, msgsz: usize, msgflg: c_int) -> i64 {
14645    <Arch as Syscalls>::syscall4(SYS_MSGSND, msqid as i64, msgp as i64, msgsz as i64, msgflg as i64)
14646}
14647
14648#[inline]
14649unsafe fn sys_msgrcv(msqid: c_int, msgp: *mut c_void, msgsz: usize, msgtyp: c_long, msgflg: c_int) -> i64 {
14650    <Arch as Syscalls>::syscall5(SYS_MSGRCV, msqid as i64, msgp as i64, msgsz as i64, msgtyp as i64, msgflg as i64)
14651}
14652
14653#[inline]
14654unsafe fn sys_msgctl(msqid: c_int, cmd: c_int, buf: *mut c_void) -> i64 {
14655    <Arch as Syscalls>::syscall3(SYS_MSGCTL, msqid as i64, cmd as i64, buf as i64)
14656}
14657
14658#[inline]
14659unsafe fn sys_semget(key: c_int, nsems: c_int, semflg: c_int) -> i64 {
14660    <Arch as Syscalls>::syscall3(SYS_SEMGET, key as i64, nsems as i64, semflg as i64)
14661}
14662
14663#[inline]
14664unsafe fn sys_semop(semid: c_int, sops: *const c_void, nsops: usize) -> i64 {
14665    <Arch as Syscalls>::syscall3(SYS_SEMOP, semid as i64, sops as i64, nsops as i64)
14666}
14667
14668#[inline]
14669unsafe fn sys_semctl(semid: c_int, semnum: c_int, cmd: c_int, arg: *mut c_void) -> i64 {
14670    <Arch as Syscalls>::syscall4(SYS_SEMCTL, semid as i64, semnum as i64, cmd as i64, arg as i64)
14671}
14672
14673#[inline]
14674unsafe fn sys_shmget(key: c_int, size: usize, shmflg: c_int) -> i64 {
14675    <Arch as Syscalls>::syscall3(SYS_SHMGET, key as i64, size as i64, shmflg as i64)
14676}
14677
14678#[inline]
14679unsafe fn sys_shmat(shmid: c_int, shmaddr: *const c_void, shmflg: c_int) -> i64 {
14680    <Arch as Syscalls>::syscall3(SYS_SHMAT, shmid as i64, shmaddr as i64, shmflg as i64)
14681}
14682
14683#[inline]
14684unsafe fn sys_shmdt(shmaddr: *const c_void) -> i64 {
14685    <Arch as Syscalls>::syscall1(SYS_SHMDT, shmaddr as i64)
14686}
14687
14688#[inline]
14689unsafe fn sys_shmctl(shmid: c_int, cmd: c_int, buf: *mut c_void) -> i64 {
14690    <Arch as Syscalls>::syscall3(SYS_SHMCTL, shmid as i64, cmd as i64, buf as i64)
14691}
14692
14693// ftok
14694#[no_mangle]
14695pub unsafe extern "C" fn ftok(path: *const c_char, id: c_int) -> c_int {
14696    let mut st: kernel_stat64 = core::mem::zeroed();
14697    let r = sys_stat(path as *const u8, &mut st);
14698    if r < 0 {
14699        ERRNO!() = (-r) as c_int;
14700        return -1;
14701    }
14702    ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16) | (((id as u32 & 0xff) << 24)) as u64) as c_int
14703}
14704
14705// msgget
14706#[no_mangle]
14707pub unsafe extern "C" fn msgget(key: c_int, msgflg: c_int) -> c_int {
14708    let r = sys_msgget(key, msgflg);
14709    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14710}
14711
14712// msgsnd
14713#[no_mangle]
14714pub unsafe extern "C" fn msgsnd(msqid: c_int, msgp: *const c_void, msgsz: usize, msgflg: c_int) -> c_int {
14715    let r = sys_msgsnd(msqid, msgp, msgsz, msgflg);
14716    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14717}
14718
14719// msgrcv
14720#[no_mangle]
14721pub unsafe extern "C" fn msgrcv(msqid: c_int, msgp: *mut c_void, msgsz: usize, msgtyp: c_long, msgflg: c_int) -> isize {
14722    let r = sys_msgrcv(msqid, msgp, msgsz, msgtyp, msgflg);
14723    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
14724}
14725
14726// msgctl
14727#[no_mangle]
14728pub unsafe extern "C" fn msgctl(msqid: c_int, cmd: c_int, buf: *mut c_void) -> c_int {
14729    let r = sys_msgctl(msqid, cmd, buf);
14730    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14731}
14732
14733// semget
14734#[no_mangle]
14735pub unsafe extern "C" fn semget(key: c_int, nsems: c_int, semflg: c_int) -> c_int {
14736    if nsems > 65535 { ERRNO!() = 22; return -1; }
14737    let r = sys_semget(key, nsems, semflg);
14738    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14739}
14740
14741// semop
14742#[no_mangle]
14743pub unsafe extern "C" fn semop(semid: c_int, sops: *const c_void, nsops: usize) -> c_int {
14744    let r = sys_semop(semid, sops, nsops);
14745    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14746}
14747
14748// semctl - C variadic
14749#[no_mangle]
14750pub unsafe extern "C" fn semctl(semid: c_int, semnum: c_int, cmd: c_int, mut args: ...) -> c_int {
14751    let mut arg: *mut c_void = core::ptr::null_mut();
14752    // Commands that take the union semun argument
14753    match cmd {
14754        // SETVAL/SETALL/GETALL, IPC_SET/IPC_STAT/IPC_INFO, SEM_STAT,
14755        // SEM_INFO, SEM_STAT_ANY and the 32-bit compat variants all carry
14756        // the `union semun` argument.
14757        16 | 13 | 17 | 1 | 2 | 3 | 18 | 19 | 20 | 0x102 | 0x104 | 0x106 => {
14758            arg = args.next_arg::<*mut c_void>();
14759        }
14760        _ => {}
14761    }
14762    let r = sys_semctl(semid, semnum, cmd, arg);
14763    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14764}
14765
14766// shmget
14767#[no_mangle]
14768pub unsafe extern "C" fn shmget(key: c_int, size: usize, shmflg: c_int) -> c_int {
14769    let r = sys_shmget(key, size, shmflg);
14770    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14771}
14772
14773// shmat
14774#[no_mangle]
14775pub unsafe extern "C" fn shmat(shmid: c_int, shmaddr: *const c_void, shmflg: c_int) -> *mut c_void {
14776    let r = sys_shmat(shmid, shmaddr, shmflg);
14777    if (r as usize) > (-(4096isize as isize)) as usize {
14778        ERRNO!() = (-r) as c_int;
14779        return -1isize as *mut c_void;
14780    }
14781    r as *mut c_void
14782}
14783
14784// shmdt
14785#[no_mangle]
14786pub unsafe extern "C" fn shmdt(shmaddr: *const c_void) -> c_int {
14787    let r = sys_shmdt(shmaddr);
14788    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14789}
14790
14791// shmctl
14792#[no_mangle]
14793pub unsafe extern "C" fn shmctl(shmid: c_int, cmd: c_int, buf: *mut c_void) -> c_int {
14794    let r = sys_shmctl(shmid, cmd, buf);
14795    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
14796}
14797
14798// ============================================================
14799// Startup: __libc_start_main
14800//
14801// musl crt1.o _start_c calls:
14802//   __libc_start_main(main, argc, argv, _init, _fini, rtld_fini, stack_end)
14803// ============================================================
14804
14805// Auxiliary vector pointer, populated by the dynamic linker before
14806// constructors run so getauxval() works during early startup.
14807#[no_mangle]
14808pub static mut __auxv: *const usize = core::ptr::null();
14809#[no_mangle]
14810pub static mut __keel_static_base: usize = 0;
14811static mut RC_STATIC_EXEC: bool = false;
14812
14813#[no_mangle]
14814pub static mut __progname: *mut c_char = core::ptr::null_mut();
14815#[no_mangle]
14816pub static mut __progname_full: *mut c_char = core::ptr::null_mut();
14817#[no_mangle]
14818pub static mut program_invocation_name: *mut c_char = core::ptr::null_mut();
14819#[no_mangle]
14820pub static mut program_invocation_short_name: *mut c_char = core::ptr::null_mut();
14821
14822#[no_mangle]
14823pub static in6addr_any: [u32; 4] = [0; 4];
14824#[no_mangle]
14825pub static in6addr_loopback: [u32; 4] = [0, 0, 0, 0x0100_0000];
14826
14827#[no_mangle]
14828pub static mut __daylight: c_int = 0;
14829#[no_mangle]
14830pub static mut __timezone: c_long = 0;
14831#[no_mangle]
14832pub static mut __tzname: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
14833
14834#[no_mangle]
14835pub unsafe extern "C" fn getauxval(type_: c_ulong) -> c_ulong {
14836    let mut p = __auxv;
14837    if p.is_null() {
14838        return 0;
14839    }
14840    loop {
14841        let tag = *p;
14842        if tag == 0 {
14843            return 0;
14844        }
14845        if tag == type_ as usize {
14846            return *p.add(1) as c_ulong;
14847        }
14848        p = p.add(2);
14849    }
14850}
14851
14852
14853unsafe fn run_static_init() {
14854    if !RC_STATIC_EXEC {
14855        return;
14856    }
14857    extern "C" {
14858        static __preinit_array_start: usize;
14859        static __preinit_array_end: usize;
14860        static __init_array_start: usize;
14861        static __init_array_end: usize;
14862    }
14863    let mut p = core::ptr::addr_of!(__preinit_array_start) as usize;
14864    let end = core::ptr::addr_of!(__preinit_array_end) as usize;
14865    while p < end {
14866        let f = core::ptr::read_unaligned(p as *const usize);
14867        if f != 0 {
14868            let f: unsafe extern "C" fn() = core::mem::transmute(f);
14869            f();
14870        }
14871        p += core::mem::size_of::<usize>();
14872    }
14873    p = core::ptr::addr_of!(__init_array_start) as usize;
14874    let end = core::ptr::addr_of!(__init_array_end) as usize;
14875    while p < end {
14876        let f = core::ptr::read_unaligned(p as *const usize);
14877        if f != 0 {
14878            let f: unsafe extern "C" fn() = core::mem::transmute(f);
14879            f();
14880        }
14881        p += core::mem::size_of::<usize>();
14882    }
14883}
14884
14885type MainFn = unsafe extern "C" fn(c_int, *const *const c_char, *const *const c_char) -> c_int;
14886type InitFn = unsafe extern "C" fn();
14887
14888#[cfg(target_arch = "x86_64")]
14889unsafe fn static_tls_tp() -> usize {
14890    let mut fs: u64 = 0;
14891    if arch_prctl(0x1003, &mut fs as *mut u64 as u64) != 0 {
14892        0
14893    } else {
14894        fs as usize
14895    }
14896}
14897
14898#[cfg(target_arch = "x86_64")]
14899unsafe fn set_static_tls_tp(tp: usize) {
14900    let _ = arch_prctl(0x1002, tp as u64);
14901}
14902
14903#[cfg(target_arch = "aarch64")]
14904unsafe fn static_tls_tp() -> usize {
14905    let tp: usize;
14906    core::arch::asm!("mrs {}, tpidr_el0", out(reg) tp, options(nostack));
14907    tp
14908}
14909
14910#[cfg(target_arch = "aarch64")]
14911unsafe fn set_static_tls_tp(tp: usize) {
14912    core::arch::asm!("msr tpidr_el0, {}", in(reg) tp, options(nostack));
14913}
14914
14915#[cfg(target_arch = "riscv64")]
14916unsafe fn static_tls_tp() -> usize {
14917    let tp: usize;
14918    core::arch::asm!("mv {}, tp", out(reg) tp, options(nostack));
14919    tp
14920}
14921
14922#[cfg(target_arch = "riscv64")]
14923unsafe fn set_static_tls_tp(tp: usize) {
14924    core::arch::asm!("mv tp, {}", in(reg) tp, options(nostack));
14925}
14926
14927static mut STATIC_TLS_BLOCK_SIZE: usize = 0;
14928static mut STATIC_TLS_TP_OFFSET: usize = 0;
14929static mut STATIC_TLS_VAR_OFFSET: usize = 0;
14930static mut STATIC_TLS_TLS_SIZE: usize = 0;
14931static mut STATIC_TLS_IMAGE: *const u8 = core::ptr::null();
14932static mut STATIC_TLS_FILESZ: usize = 0;
14933static mut STATIC_TLS_CANARY: u64 = 0;
14934
14935unsafe fn static_tls_init_block(block: *mut u8) -> *mut u8 {
14936    if block.is_null() || STATIC_TLS_BLOCK_SIZE == 0 {
14937        return core::ptr::null_mut();
14938    }
14939    let var_base = block.add(STATIC_TLS_VAR_OFFSET);
14940    if STATIC_TLS_TLS_SIZE > 0 {
14941        core::ptr::write_bytes(var_base, 0, STATIC_TLS_TLS_SIZE);
14942    }
14943    if STATIC_TLS_FILESZ > 0 && !STATIC_TLS_IMAGE.is_null() {
14944        core::ptr::copy_nonoverlapping(STATIC_TLS_IMAGE, var_base, STATIC_TLS_FILESZ);
14945    }
14946    let tp = block.add(STATIC_TLS_TP_OFFSET);
14947    let tcb = if cfg!(target_arch = "x86_64") {
14948        tp as usize
14949    } else {
14950        block as usize
14951    };
14952    core::ptr::write_unaligned(tcb as *mut u64, tcb as u64);
14953    core::ptr::write_unaligned((tcb as *mut u64).add(1), 1);
14954    core::ptr::write_unaligned((tcb as *mut u64).add(2), STATIC_TLS_TLS_SIZE as u64);
14955    core::ptr::write_unaligned((tcb as *mut u64).add(3), 1);
14956    core::ptr::write_unaligned((tcb as *mut u64).add(4), 0); // reserved
14957    core::ptr::write_unaligned((tcb as *mut u64).add(5), STATIC_TLS_CANARY); // 0x28
14958    core::ptr::write_unaligned((tcb as *mut u64).add(6), 0); // errno at 0x30
14959    core::ptr::write_unaligned((tcb as *mut u64).add(7), 0); // vDSO getrandom state at 0x38
14960    core::ptr::write_unaligned((tcb as *mut u64).add(8), 0); // Thread record at 0x40
14961    tp
14962}
14963
14964unsafe fn static_tls_create_block() -> *mut u8 {
14965    if STATIC_TLS_BLOCK_SIZE == 0 {
14966        return core::ptr::null_mut();
14967    }
14968    let block = sys_mmap(
14969        core::ptr::null_mut(),
14970        STATIC_TLS_BLOCK_SIZE,
14971        PROT_READ | PROT_WRITE,
14972        MAP_PRIVATE | MAP_ANONYMOUS,
14973        -1,
14974        0,
14975    );
14976    if block.is_null() || block == MMAP_FAILED {
14977        return core::ptr::null_mut();
14978    }
14979    static_tls_init_block(block)
14980}
14981
14982#[repr(C)]
14983pub struct TlsIndex {
14984    pub ti_module: usize,
14985    pub ti_offset: usize,
14986}
14987
14988/// Global-dynamic TLS access.  The dynamic loader intercepts this symbol for
14989/// dynamically linked programs and uses its own multi-module implementation.
14990/// A static executable has only module 0, so resolve directly against the
14991/// static TLS block created by `init_static_tls()`.
14992static mut TLS_GET_ADDR_IMPL: usize = 0;
14993
14994/// The dynamic loader installs its multi-module TLS resolver here before
14995/// running constructors.  Keeping a dispatch pointer means a program that
14996/// obtains `__tls_get_addr` through `dlsym` still reaches the loader's
14997/// implementation rather than the static fallback below.
14998#[no_mangle]
14999pub unsafe extern "C" fn __keel_set_tls_get_addr(f: usize) {
15000    TLS_GET_ADDR_IMPL = f;
15001}
15002
15003#[no_mangle]
15004pub unsafe extern "C" fn __tls_get_addr(ti: *const TlsIndex) -> *mut u8 {
15005    if TLS_GET_ADDR_IMPL != 0 {
15006        let f: unsafe extern "C" fn(*const TlsIndex) -> *mut u8 =
15007            core::mem::transmute(TLS_GET_ADDR_IMPL);
15008        return f(ti);
15009    }
15010    if ti.is_null() || (*ti).ti_module != 0 || !RC_STATIC_EXEC {
15011        return core::ptr::null_mut();
15012    }
15013    let tp = static_tls_tp();
15014    if tp == 0 {
15015        return core::ptr::null_mut();
15016    }
15017    (tp - STATIC_TLS_TP_OFFSET + STATIC_TLS_VAR_OFFSET + (*ti).ti_offset) as *mut u8
15018}
15019
15020/// Static executables have no dynamic loader to build a TCB.  Allocate one
15021/// from PT_TLS so that `%fs`/TP-relative TLS accesses and errno work.
15022unsafe fn init_static_tls() {
15023    if static_tls_tp() != 0 {
15024        return;
15025    }
15026    let phdr = getauxval(3) as usize; // AT_PHDR
15027    let phnum = getauxval(5) as usize; // AT_PHNUM
15028    let phent = getauxval(4) as usize; // AT_PHENT
15029    if phdr == 0 || phnum == 0 || phent < 56 {
15030        return;
15031    }
15032
15033    let mut tls_vaddr = 0usize;
15034    let mut tls_filesz = 0usize;
15035    let mut tls_memsz = 0usize;
15036    let mut tls_align = 1usize;
15037    let mut exec_base = __keel_static_base;
15038    let mut i = 0usize;
15039    while i < phnum {
15040        let ph = phdr + i * phent;
15041        let p_type = core::ptr::read_unaligned(ph as *const u32);
15042        if p_type == 3 {
15043            // PT_INTERP means the dynamic loader already owns TLS.
15044            return;
15045        }
15046        if p_type == 6 {
15047            // PT_PHDR
15048            if exec_base == 0 {
15049                let p_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
15050                exec_base = phdr.wrapping_sub(p_vaddr);
15051            }
15052        } else if p_type == 7 {
15053            // PT_TLS
15054            tls_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
15055            tls_filesz = core::ptr::read_unaligned((ph + 32) as *const u64) as usize;
15056            tls_memsz = core::ptr::read_unaligned((ph + 40) as *const u64) as usize;
15057            let align = core::ptr::read_unaligned((ph + 48) as *const u64) as usize;
15058            if align > 1 {
15059                tls_align = align;
15060            }
15061        }
15062        i += 1;
15063    }
15064
15065    let tcb_size = 256usize;
15066    #[cfg(target_arch = "x86_64")]
15067    let gap = 0usize;
15068    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
15069    let gap = if cfg!(target_arch = "aarch64") { 16usize } else { 0usize };
15070
15071    let tls_size = if tls_align > 1 {
15072        (tls_memsz + tls_align - 1) & !(tls_align - 1)
15073    } else {
15074        tls_memsz
15075    };
15076    let total = tcb_size + gap + tls_size + tls_align;
15077    STATIC_TLS_BLOCK_SIZE = total;
15078    STATIC_TLS_TP_OFFSET = if cfg!(target_arch = "x86_64") {
15079        tls_size
15080    } else {
15081        tcb_size
15082    };
15083    STATIC_TLS_VAR_OFFSET = if cfg!(target_arch = "x86_64") {
15084        0
15085    } else {
15086        tcb_size + gap
15087    };
15088    STATIC_TLS_TLS_SIZE = tls_size;
15089    STATIC_TLS_IMAGE = (exec_base + tls_vaddr) as *const u8;
15090    STATIC_TLS_FILESZ = tls_filesz;
15091    let random = getauxval(25) as *const u8; // AT_RANDOM
15092    STATIC_TLS_CANARY = if random.is_null() {
15093        0xdefaced_cafebeefu64
15094    } else {
15095        core::ptr::read_unaligned(random as *const u64)
15096            ^ core::ptr::read_unaligned(random.add(8) as *const u64)
15097    };
15098
15099    let block = sys_mmap(
15100        core::ptr::null_mut(),
15101        total,
15102        PROT_READ | PROT_WRITE,
15103        MAP_PRIVATE | MAP_ANONYMOUS,
15104        -1,
15105        0,
15106    );
15107    if block.is_null() || block == MMAP_FAILED {
15108        return;
15109    }
15110    let tp = static_tls_init_block(block);
15111    if tp.is_null() {
15112        return;
15113    }
15114    set_static_tls_tp(tp as usize);
15115    RC_STATIC_EXEC = true;
15116}
15117
15118
15119#[no_mangle]
15120pub unsafe extern "C" fn __libc_start_main(
15121    main: MainFn,
15122    argc: c_int,
15123    argv: *const *const c_char,
15124    _init: *const c_void,
15125    _fini: *const c_void,
15126    _rtld_fini: *const c_void,
15127    _stack_end: *const c_void,
15128) -> ! {
15129    let envp = argv.add((argc + 1) as usize);
15130    let mut aux = envp;
15131    while !(*aux).is_null() {
15132        aux = aux.add(1);
15133    }
15134    __auxv = aux.add(1) as *const usize;
15135    init_static_tls();
15136    errno_init();
15137    // Register the main thread during startup.  pthread_exit() uses the
15138    // thread table to decide whether it is the last thread; if the main
15139    // thread only registered lazily, a worker exiting first could call
15140    // exit() while the main thread was still alive.  Register slot 0
15141    // directly: pthread_self() would otherwise scan the whole static thread
15142    // table and fault in roughly 1 MiB on every process start.
15143    register_main_thread();
15144
15145    __environ = envp as *mut *mut c_char;
15146    environ = __environ; // sync environ alias
15147    ___environ = __environ;
15148    _environ = __environ;
15149
15150    // glibc-compatible program name globals.
15151    if !argv.is_null() && argc > 0 {
15152        let argv0 = *argv;
15153        __progname_full = argv0 as *mut c_char;
15154        program_invocation_name = argv0 as *mut c_char;
15155        let mut base = argv0;
15156        let mut p = argv0;
15157        while *p != 0 {
15158            if *p == b'/' as c_char { base = p.add(1); }
15159            p = p.add(1);
15160        }
15161        __progname = base as *mut c_char;
15162        program_invocation_short_name = base as *mut c_char;
15163    }
15164
15165    __stdio_init();
15166    run_static_init();
15167
15168    let mut set: SigSetT = 0;
15169    sigemptyset(&mut set);
15170    sigaddset(&mut set, SIGCANCEL);
15171    sigprocmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
15172
15173    if !_init.is_null() {
15174        let init_fn: InitFn = core::mem::transmute(_init);
15175        init_fn();
15176    }
15177
15178    // aarch64/riscv64 GCC reads __stack_chk_guard as a global (GOT-based for PIE),
15179    // so we must initialize it from AT_RANDOM before calling main.
15180    // x86_64 uses %fs:0x28 which the kernel already set up.
15181    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
15182    {
15183        let random_ptr = getauxval(25) as *const u8; // AT_RANDOM = 25
15184        if !random_ptr.is_null() {
15185            let a = core::ptr::read_unaligned(random_ptr as *const u64);
15186            let b = core::ptr::read_unaligned(random_ptr.add(8) as *const u64);
15187            __stack_chk_guard = (a ^ b) as usize;
15188        } else {
15189            // ponytail: fallback entropy, not crypto-grade but nonzero
15190            __stack_chk_guard = 0xdefaced_cafebeef;
15191        }
15192    }
15193
15194    let result = main(argc, argv, envp);
15195
15196    if !_fini.is_null() {
15197        let fini_fn: InitFn = core::mem::transmute(_fini);
15198        fini_fn();
15199    }
15200
15201    exit(result);
15202}
15203
15204type LdsoDlopenFn = unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void;
15205type LdsoDlsymFn = unsafe extern "C" fn(*mut c_void, *const c_char, *mut c_void) -> *mut c_void;
15206type LdsoDlcloseFn = unsafe extern "C" fn(*mut c_void) -> c_int;
15207type LdsoDlerrorFn = unsafe extern "C" fn() -> *const c_char;
15208
15209static mut LDSO_DLOPEN: Option<LdsoDlopenFn> = None;
15210static mut LDSO_DLSYM: Option<LdsoDlsymFn> = None;
15211static mut LDSO_DLCLOSE: Option<LdsoDlcloseFn> = None;
15212static mut LDSO_DLERROR: Option<LdsoDlerrorFn> = None;
15213
15214#[no_mangle]
15215pub unsafe extern "C" fn __ldso_register_dlopen(f: LdsoDlopenFn) {
15216    LDSO_DLOPEN = Some(f);
15217}
15218
15219#[no_mangle]
15220pub unsafe extern "C" fn __ldso_register_dlsym(f: LdsoDlsymFn) {
15221    LDSO_DLSYM = Some(f);
15222}
15223
15224#[no_mangle]
15225pub unsafe extern "C" fn __ldso_register_dlclose(f: LdsoDlcloseFn) {
15226    LDSO_DLCLOSE = Some(f);
15227}
15228
15229#[no_mangle]
15230pub unsafe extern "C" fn __ldso_register_dlerror(f: LdsoDlerrorFn) {
15231    LDSO_DLERROR = Some(f);
15232}
15233
15234#[no_mangle]
15235pub unsafe extern "C" fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void {
15236    if let Some(f) = LDSO_DLOPEN {
15237        f(filename, flags)
15238    } else {
15239        null_mut()
15240    }
15241}
15242
15243#[no_mangle]
15244pub unsafe extern "C" fn dlsym_impl(
15245    handle: *mut c_void,
15246    symbol: *const c_char,
15247    ra: *mut c_void,
15248) -> *mut c_void {
15249    if let Some(f) = LDSO_DLSYM {
15250        f(handle, symbol, ra)
15251    } else {
15252        null_mut()
15253    }
15254}
15255
15256// dlsym() must pass its own return address to the loader so that
15257// RTLD_NEXT can identify the calling object.  Keep the public entry
15258// point in assembly and tail-jump into the Rust implementation.
15259#[no_mangle]
15260#[unsafe(naked)]
15261#[cfg(target_arch = "x86_64")]
15262pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15263    core::arch::naked_asm!("mov rdx, [rsp]", "jmp dlsym_impl");
15264}
15265
15266#[no_mangle]
15267#[unsafe(naked)]
15268#[cfg(target_arch = "aarch64")]
15269pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15270    core::arch::naked_asm!("mov x2, x30", "b dlsym_impl");
15271}
15272
15273#[no_mangle]
15274#[unsafe(naked)]
15275#[cfg(target_arch = "riscv64")]
15276pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15277    core::arch::naked_asm!("mv a2, ra", "la t0, dlsym_impl", "jr t0");
15278}
15279
15280#[no_mangle]
15281pub unsafe extern "C" fn dlclose(handle: *mut c_void) -> c_int {
15282    if let Some(f) = LDSO_DLCLOSE {
15283        f(handle)
15284    } else {
15285        0
15286    }
15287}
15288
15289#[no_mangle]
15290pub unsafe extern "C" fn dlerror() -> *const c_char {
15291    if let Some(f) = LDSO_DLERROR {
15292        f()
15293    } else {
15294        core::ptr::null()
15295    }
15296}
15297
15298include!("crypt_impl.rs");
15299include!("statvfs.rs");
15300include!("daemon.rs");
15301include!("dn_expand.rs");
15302include!("lrand48.rs");
15303include!("strverscmp.rs");
15304include!("syscall.rs");
15305include!("pthread_atfork.rs");
15306include!("fenv.rs");
15307include!("locale_ctype.rs");
15308include!("regression_stubs.rs");
15309include!("netdb_extra.rs");
15310include!("compat_extra.rs");
15311include!("stdio_extra.rs");
15312include!("ns_parse.rs");
15313include!("fts.rs");
15314include!("ifaddrs.rs");
15315include!("dl_extra.rs");
15316include!("des.rs");
15317include!("path_extra.rs");
15318include!("wordexp.rs");
15319include!("getopt_impl.rs");
15320
15321// ============================================================
15322// regex.h
15323// ============================================================
15324
15325// musl defines regoff_t as _Addr (long on every Linux target), not int.
15326type regoff_t = c_long;
15327
15328#[repr(C)]
15329pub struct regex_t {
15330    pub re_nsub: usize,
15331    pub __opaque: *mut c_void,
15332    pub __padding: [*mut c_void; 4],
15333    pub __nsub2: usize,
15334    pub __padding2: c_char,
15335}
15336
15337#[repr(C)]
15338pub struct regmatch_t {
15339    pub rm_so: regoff_t,
15340    pub rm_eo: regoff_t,
15341}
15342
15343include!("regex.rs");
15344include!("tz.rs");
15345
15346// The dynamic loader is part of libc, mirroring musl's single-file design.
15347// It is compiled as a module so its private syscall/string helpers do not
15348// collide with the libc namespace; its exported entry points remain global.
15349#[allow(dead_code, deref_nullptr)]
15350mod ldso;
15351
15352#[cfg(test)]
15353mod libc_unit_stub {
15354    #[test]
15355    fn stub() {
15356        assert!(true);
15357    }
15358}
15359
15360// ============================================================
15361// Missing math functions - simple implementations
15362// ============================================================
15363
15364#[inline]
15365pub(crate) fn fmax_impl(x: f64, y: f64) -> f64 {
15366    if x.is_nan() { return y; }
15367    if y.is_nan() { return x; }
15368    if x == 0.0 && y == 0.0 {
15369        return if x.is_sign_negative() && y.is_sign_negative() { -0.0 } else { 0.0 };
15370    }
15371    if x > y { x } else { y }
15372}
15373
15374#[inline]
15375pub(crate) fn fmin_impl(x: f64, y: f64) -> f64 {
15376    if x.is_nan() { return y; }
15377    if y.is_nan() { return x; }
15378    if x == 0.0 && y == 0.0 {
15379        return if x.is_sign_negative() || y.is_sign_negative() { -0.0 } else { 0.0 };
15380    }
15381    if x < y { x } else { y }
15382}
15383
15384#[inline]
15385pub(crate) fn fmaxf_impl(x: f32, y: f32) -> f32 {
15386    if x.is_nan() { return y; }
15387    if y.is_nan() { return x; }
15388    if x == 0.0 && y == 0.0 {
15389        return if x.is_sign_negative() && y.is_sign_negative() { -0.0 } else { 0.0 };
15390    }
15391    if x > y { x } else { y }
15392}
15393
15394#[inline]
15395pub(crate) fn fminf_impl(x: f32, y: f32) -> f32 {
15396    if x.is_nan() { return y; }
15397    if y.is_nan() { return x; }
15398    if x == 0.0 && y == 0.0 {
15399        return if x.is_sign_negative() || y.is_sign_negative() { -0.0 } else { 0.0 };
15400    }
15401    if x < y { x } else { y }
15402}
15403
15404#[inline(never)]
15405#[no_mangle]
15406pub unsafe extern "C" fn fmax(x: f64, y: f64) -> f64 {
15407    fmax_impl(x, y)
15408}
15409
15410#[inline(never)]
15411#[no_mangle]
15412pub unsafe extern "C" fn fmin(x: f64, y: f64) -> f64 {
15413    fmin_impl(x, y)
15414}
15415
15416#[no_mangle]
15417pub unsafe extern "C" fn fminf(x: f32, y: f32) -> f32 {
15418    fminf_impl(x, y)
15419}
15420
15421#[no_mangle]
15422pub unsafe extern "C" fn fdim(x: f64, y: f64) -> f64 {
15423    if x.is_nan() || y.is_nan() {
15424        return f64::NAN;
15425    }
15426    if x > y { x - y } else { 0.0 }
15427}
15428
15429#[no_mangle]
15430pub unsafe extern "C" fn fma(x: f64, y: f64, z: f64) -> f64 {
15431    if (x.is_infinite() && y == 0.0) || (y.is_infinite() && x == 0.0) {
15432        feraiseexcept(FE_INVALID);
15433        return f64::NAN;
15434    }
15435    if x.is_nan() || y.is_nan() || z.is_nan() {
15436        return f64::NAN;
15437    }
15438    let r = libm::fma(x, y, z);
15439    // inf-inf is invalid; libm may return NaN without raising.
15440    if r.is_nan() {
15441        feraiseexcept(FE_INVALID);
15442    }
15443    r
15444}
15445
15446#[no_mangle]
15447pub unsafe extern "C" fn ilogb(x: f64) -> i32 {
15448    if x.is_nan() {
15449        feraiseexcept(FE_INVALID);
15450        return -0x7fffffff - 1; // FP_ILOGBNAN
15451    }
15452    if x == 0.0 || x.is_infinite() {
15453        feraiseexcept(FE_INVALID);
15454        return if x == 0.0 { -0x7fffffff - 1 } else { 0x7fffffff };
15455    }
15456    let bits = x.to_bits();
15457    let exp = ((bits >> 52) & 0x7ff) as i32;
15458    if exp == 0 {
15459        // subnormal
15460        let mut v = bits & 0xfffffffffffff;
15461        let mut e = -1022;
15462        while v < (1u64 << 52) { v <<= 1; e -= 1; }
15463        e
15464    } else {
15465        exp - 1023
15466    }
15467}
15468
15469#[no_mangle]
15470pub unsafe extern "C" fn logb(x: f64) -> f64 {
15471    if x.is_nan() { return x; }
15472    if x == 0.0 { return __math_divzero(1); }
15473    let bits = x.to_bits();
15474    let exp = ((bits >> 52) & 0x7ff) as i32;
15475    if exp == 0 {
15476        // subnormal
15477        let mut v = bits & 0xfffffffffffff;
15478        let mut e = -1022i32;
15479        while v < (1u64 << 52) { v <<= 1; e -= 1; }
15480        e as f64
15481    } else if exp == 0x7ff {
15482        x * x // infinity * infinity = infinity (preserves sign)
15483    } else {
15484        (exp - 1023) as f64
15485    }
15486}
15487
15488#[no_mangle]
15489pub unsafe extern "C" fn nearbyint(x: f64) -> f64 {
15490    let had_inexact = fetestexcept(FE_INEXACT) & FE_INEXACT != 0;
15491    let r = libm::rint(x);
15492    if !had_inexact {
15493        feclearexcept(FE_INEXACT);
15494    }
15495    r
15496}
15497
15498#[no_mangle]
15499pub unsafe extern "C" fn nextafter(x: f64, y: f64) -> f64 {
15500    if x.is_nan() || y.is_nan() { return x + y; }
15501    if x == 0.0 && y == 0.0 { return y; }
15502    if x == y { return x; }
15503    let r = libm::nextafter(x, y);
15504    if r.is_infinite() && x.is_finite() {
15505        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
15506    } else if r != x {
15507        let bits = r.to_bits();
15508        let is_subnormal = (bits & 0x7ff0000000000000) == 0 && (bits & 0xfffffffffffff) != 0;
15509        if r == 0.0 || is_subnormal {
15510            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
15511        }
15512    }
15513    r
15514}
15515
15516#[no_mangle]
15517pub unsafe extern "C" fn nexttoward(x: f64, y: f64) -> f64 {
15518    // On x86_64, long double = f64, so nexttoward = nextafter
15519    if x == 0.0 && y == 0.0 {
15520        return if y.is_sign_negative() { -0.0 } else { 0.0 };
15521    }
15522    nextafter(x, y)
15523}
15524
15525#[no_mangle]
15526pub unsafe extern "C" fn remainder(x: f64, y: f64) -> f64 {
15527    if x.is_nan() || y.is_nan() { return x + y; }
15528    if y == 0.0 || x.is_infinite() { return __math_invalid(x); }
15529    libm::remainder(x, y)
15530}
15531
15532#[no_mangle]
15533pub unsafe extern "C" fn remquo(x: f64, y: f64, quo: *mut i32) -> f64 {
15534    if x.is_nan() || y.is_nan() {
15535        if !quo.is_null() { *quo = 0; }
15536        return x + y;
15537    }
15538    if y == 0.0 || x.is_infinite() {
15539        if !quo.is_null() { *quo = 0; }
15540        return __math_invalid(x);
15541    }
15542    let (r, q) = libm::remquo(x, y);
15543    if !quo.is_null() { *quo = q; }
15544    r
15545}
15546
15547#[no_mangle]
15548pub unsafe extern "C" fn exp2(x: f64) -> f64 {
15549    exp2_impl(x)
15550}
15551
15552#[no_mangle]
15553pub unsafe extern "C" fn expm1(x: f64) -> f64 {
15554    let r = libm::expm1(x);
15555    // Raise UNDERFLOW for very small results that underflow
15556    if r != 0.0 && x != 0.0 && libm::fabs(x) < 1e-307 {
15557        feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
15558    }
15559    r
15560}
15561
15562#[no_mangle]
15563pub unsafe extern "C" fn log1p(x: f64) -> f64 {
15564    if x == -1.0 {
15565        feraiseexcept(FE_DIVBYZERO);
15566        return f64::NEG_INFINITY;
15567    }
15568    libm::log1p(x)
15569}
15570
15571#[no_mangle]
15572pub unsafe extern "C" fn acosh(x: f64) -> f64 {
15573    if x < 1.0 {
15574        feraiseexcept(FE_INVALID);
15575        return f64::NAN;
15576    }
15577    libm::acosh(x)
15578}
15579
15580#[no_mangle]
15581pub unsafe extern "C" fn asinh(x: f64) -> f64 {
15582    if x == 0.0 { return x; }
15583    libm::asinh(x)
15584}
15585
15586#[no_mangle]
15587pub unsafe extern "C" fn atanh(x: f64) -> f64 {
15588    if x == 0.0 { return x; }
15589    let e = ((x.to_bits() >> 52) & 0x7ff) as i32;
15590    if e < 0x3ff - 32 {
15591        feraiseexcept(FE_INEXACT);
15592        if e == 0 { feraiseexcept(FE_UNDERFLOW); }
15593        return x;
15594    }
15595    if x == 1.0 {
15596        feraiseexcept(FE_DIVBYZERO);
15597        return f64::INFINITY;
15598    }
15599    if x == -1.0 {
15600        feraiseexcept(FE_DIVBYZERO);
15601        return f64::NEG_INFINITY;
15602    }
15603    if x.is_nan() { return x; }
15604    let ax = libm::fabs(x);
15605    if ax > 1.0 {
15606        feraiseexcept(FE_INVALID);
15607        return f64::NAN;
15608    }
15609    if ax < 0.5 {
15610        // For small x: use log1p formula with |x| and negate
15611        let r = libm::log1p(2.0 * (ax + ax * ax / (1.0 - ax))) / 2.0;
15612        if x < 0.0 { -r } else { r }
15613    } else {
15614        // For larger x: use log formula with |x| and negate
15615        let r = 0.5 * libm::log((1.0 + ax) / (1.0 - ax));
15616        if x < 0.0 { -r } else { r }
15617    }
15618}
15619
15620#[no_mangle]
15621pub unsafe extern "C" fn cbrt(x: f64) -> f64 {
15622    libm::cbrt(x)
15623}
15624
15625#[no_mangle]
15626pub unsafe extern "C" fn erf(x: f64) -> f64 {
15627    erf_impl(x)
15628}
15629
15630#[no_mangle]
15631pub unsafe extern "C" fn erfc(x: f64) -> f64 {
15632    erfc_impl(x)
15633}
15634
15635#[no_mangle]
15636pub unsafe extern "C" fn lgamma(x: f64) -> f64 {
15637    lgamma_impl(x)
15638}
15639
15640#[no_mangle]
15641pub unsafe extern "C" fn tgamma(x: f64) -> f64 {
15642    tgamma_impl(x)
15643}
15644
15645#[no_mangle]
15646pub unsafe extern "C" fn lround(x: f64) -> core::ffi::c_long {
15647    libm::round(x) as core::ffi::c_long
15648}
15649
15650#[no_mangle]
15651pub unsafe extern "C" fn llround(x: f64) -> i64 {
15652    libm::round(x) as i64
15653}
15654
15655// ============================================================
15656// Complex math functions - using (f64, f64) pairs
15657// ============================================================
15658
15659// Helper: complex number as (real, imag) pair
15660// cabs: magnitude = sqrt(re^2 + im^2)
15661#[no_mangle]
15662pub unsafe extern "C" fn cabs(z: (f64, f64)) -> f64 {
15663    libm::sqrt(z.0 * z.0 + z.1 * z.1)
15664}
15665
15666#[no_mangle]
15667pub unsafe extern "C" fn cabsf(z: (f32, f32)) -> f32 {
15668    libm::sqrtf(z.0 * z.0 + z.1 * z.1)
15669}
15670
15671#[no_mangle]
15672pub unsafe extern "C" fn cabsl(z: (f64, f64)) -> f64 {
15673    cabs(z)
15674}
15675
15676#[no_mangle]
15677pub unsafe extern "C" fn carg(z: (f64, f64)) -> f64 {
15678    libm::atan2(z.1, z.0)
15679}
15680
15681#[no_mangle]
15682pub unsafe extern "C" fn cargf(z: (f32, f32)) -> f32 {
15683    libm::atan2f(z.1, z.0)
15684}
15685
15686#[no_mangle]
15687pub unsafe extern "C" fn cargl(z: (f64, f64)) -> f64 {
15688    carg(z)
15689}
15690
15691#[no_mangle]
15692pub unsafe extern "C" fn cimag(z: (f64, f64)) -> f64 {
15693    z.1
15694}
15695
15696#[no_mangle]
15697pub unsafe extern "C" fn cimagf(z: (f32, f32)) -> f32 {
15698    z.1
15699}
15700
15701#[no_mangle]
15702pub unsafe extern "C" fn cimagl(z: (f64, f64)) -> f64 {
15703    z.1
15704}
15705
15706#[no_mangle]
15707pub unsafe extern "C" fn creal(z: (f64, f64)) -> f64 {
15708    z.0
15709}
15710
15711#[no_mangle]
15712pub unsafe extern "C" fn crealf(z: (f32, f32)) -> f32 {
15713    z.0
15714}
15715
15716#[no_mangle]
15717pub unsafe extern "C" fn creall(z: (f64, f64)) -> f64 {
15718    z.0
15719}
15720
15721#[no_mangle]
15722pub unsafe extern "C" fn conj(z: (f64, f64)) -> (f64, f64) {
15723    (z.0, -z.1)
15724}
15725
15726#[no_mangle]
15727pub unsafe extern "C" fn conjf(z: (f32, f32)) -> (f32, f32) {
15728    (z.0, -z.1)
15729}
15730
15731#[no_mangle]
15732pub unsafe extern "C" fn conjl(z: (f64, f64)) -> (f64, f64) {
15733    conj(z)
15734}
15735
15736#[no_mangle]
15737pub unsafe extern "C" fn cproj(z: (f64, f64)) -> (f64, f64) {
15738    if z.0.is_infinite() || z.1.is_infinite() {
15739        (f64::INFINITY, if z.1.is_sign_positive() { 0.0 } else { -0.0 })
15740    } else {
15741        z
15742    }
15743}
15744
15745#[no_mangle]
15746pub unsafe extern "C" fn cprojf(z: (f32, f32)) -> (f32, f32) {
15747    if z.0.is_infinite() || z.1.is_infinite() {
15748        (f32::INFINITY, if z.1.is_sign_positive() { 0.0 } else { -0.0 })
15749    } else {
15750        z
15751    }
15752}
15753
15754#[no_mangle]
15755pub unsafe extern "C" fn cprojl(z: (f64, f64)) -> (f64, f64) {
15756    cproj(z)
15757}
15758
15759// cexp: e^z = e^(re + i*im) = e^re * (cos(im) + i*sin(im))
15760#[no_mangle]
15761pub unsafe extern "C" fn cexp(z: (f64, f64)) -> (f64, f64) {
15762    let r = libm::exp(z.0);
15763    (r * libm::cos(z.1), r * libm::sin(z.1))
15764}
15765
15766#[no_mangle]
15767pub unsafe extern "C" fn cexpf(z: (f32, f32)) -> (f32, f32) {
15768    let r = libm::expf(z.0);
15769    (r * libm::cosf(z.1), r * libm::sinf(z.1))
15770}
15771
15772#[no_mangle]
15773pub unsafe extern "C" fn cexpl(z: (f64, f64)) -> (f64, f64) {
15774    cexp(z)
15775}
15776
15777// clog: ln(z) = ln|z| + i*arg(z)
15778#[no_mangle]
15779pub unsafe extern "C" fn clog(z: (f64, f64)) -> (f64, f64) {
15780    (libm::log(cabs(z)), carg(z))
15781}
15782
15783#[no_mangle]
15784pub unsafe extern "C" fn clogf(z: (f32, f32)) -> (f32, f32) {
15785    (libm::logf(cabsf(z)), cargf(z))
15786}
15787
15788#[no_mangle]
15789pub unsafe extern "C" fn clogl(z: (f64, f64)) -> (f64, f64) {
15790    clog(z)
15791}
15792
15793// csqrt: sqrt(z) = sqrt((|z|+re)/2) + i*sign(im)*sqrt((|z|-re)/2)
15794#[no_mangle]
15795pub unsafe extern "C" fn csqrt(z: (f64, f64)) -> (f64, f64) {
15796    let r = cabs(z);
15797    let sign = if z.1 < 0.0 { -1.0 } else { 1.0 };
15798    (libm::sqrt((r + z.0) / 2.0), sign * libm::sqrt((r - z.0) / 2.0))
15799}
15800
15801#[no_mangle]
15802pub unsafe extern "C" fn csqrtf(z: (f32, f32)) -> (f32, f32) {
15803    let r = cabsf(z);
15804    let sign = if z.1 < 0.0 { -1.0f32 } else { 1.0f32 };
15805    (libm::sqrtf((r + z.0) / 2.0), sign * libm::sqrtf((r - z.0) / 2.0))
15806}
15807
15808#[no_mangle]
15809pub unsafe extern "C" fn csqrtl(z: (f64, f64)) -> (f64, f64) {
15810    csqrt(z)
15811}
15812
15813// cpow: z^w = e^(w * log(z))
15814#[no_mangle]
15815pub unsafe extern "C" fn cpow(z: (f64, f64), w: (f64, f64)) -> (f64, f64) {
15816    let log_z = clog(z);
15817    let exp_arg = (w.0 * log_z.0 - w.1 * log_z.1, w.0 * log_z.1 + w.1 * log_z.0);
15818    cexp(exp_arg)
15819}
15820
15821#[no_mangle]
15822pub unsafe extern "C" fn cpowf(z: (f32, f32), w: (f32, f32)) -> (f32, f32) {
15823    let log_z = clogf(z);
15824    let exp_arg = (w.0 * log_z.0 - w.1 * log_z.1, w.0 * log_z.1 + w.1 * log_z.0);
15825    cexpf(exp_arg)
15826}
15827
15828#[no_mangle]
15829pub unsafe extern "C" fn cpowl(z: (f64, f64), w: (f64, f64)) -> (f64, f64) {
15830    cpow(z, w)
15831}
15832
15833// ccos: cos(z) = cos(re)*cosh(im) - i*sin(re)*sinh(im)
15834#[no_mangle]
15835pub unsafe extern "C" fn ccos(z: (f64, f64)) -> (f64, f64) {
15836    (libm::cos(z.0) * libm::cosh(z.1), -libm::sin(z.0) * libm::sinh(z.1))
15837}
15838
15839#[no_mangle]
15840pub unsafe extern "C" fn ccosf(z: (f32, f32)) -> (f32, f32) {
15841    (libm::cosf(z.0) * libm::coshf(z.1), -libm::sinf(z.0) * libm::sinhf(z.1))
15842}
15843
15844#[no_mangle]
15845pub unsafe extern "C" fn ccosl(z: (f64, f64)) -> (f64, f64) {
15846    ccos(z)
15847}
15848
15849// csin: sin(z) = sin(re)*cosh(im) + i*cos(re)*sinh(im)
15850#[no_mangle]
15851pub unsafe extern "C" fn csin(z: (f64, f64)) -> (f64, f64) {
15852    (libm::sin(z.0) * libm::cosh(z.1), libm::cos(z.0) * libm::sinh(z.1))
15853}
15854
15855#[no_mangle]
15856pub unsafe extern "C" fn csinf(z: (f32, f32)) -> (f32, f32) {
15857    (libm::sinf(z.0) * libm::coshf(z.1), libm::cosf(z.0) * libm::sinhf(z.1))
15858}
15859
15860#[no_mangle]
15861pub unsafe extern "C" fn csinl(z: (f64, f64)) -> (f64, f64) {
15862    csin(z)
15863}
15864
15865// ctan: tan(z) = sin(2re)/(cos(2re)+cosh(2im)) + i*sinh(2im)/(cos(2re)+cosh(2im))
15866#[no_mangle]
15867pub unsafe extern "C" fn ctan(z: (f64, f64)) -> (f64, f64) {
15868    let d = libm::cos(2.0 * z.0) + libm::cosh(2.0 * z.1);
15869    (libm::sin(2.0 * z.0) / d, libm::sinh(2.0 * z.1) / d)
15870}
15871
15872#[no_mangle]
15873pub unsafe extern "C" fn ctanf(z: (f32, f32)) -> (f32, f32) {
15874    let d = libm::cosf(2.0 * z.0) + libm::coshf(2.0 * z.1);
15875    (libm::sinf(2.0 * z.0) / d, libm::sinhf(2.0 * z.1) / d)
15876}
15877
15878#[no_mangle]
15879pub unsafe extern "C" fn ctanl(z: (f64, f64)) -> (f64, f64) {
15880    ctan(z)
15881}
15882
15883// ccosh: cosh(z) = cosh(re)*cos(im) + i*sinh(re)*sin(im)
15884#[no_mangle]
15885pub unsafe extern "C" fn ccosh(z: (f64, f64)) -> (f64, f64) {
15886    (libm::cosh(z.0) * libm::cos(z.1), libm::sinh(z.0) * libm::sin(z.1))
15887}
15888
15889#[no_mangle]
15890pub unsafe extern "C" fn ccoshf(z: (f32, f32)) -> (f32, f32) {
15891    (libm::coshf(z.0) * libm::cosf(z.1), libm::sinhf(z.0) * libm::sinf(z.1))
15892}
15893
15894#[no_mangle]
15895pub unsafe extern "C" fn ccoshl(z: (f64, f64)) -> (f64, f64) {
15896    ccosh(z)
15897}
15898
15899// csinh: sinh(z) = sinh(re)*cos(im) + i*cosh(re)*sin(im)
15900#[no_mangle]
15901pub unsafe extern "C" fn csinh(z: (f64, f64)) -> (f64, f64) {
15902    (libm::sinh(z.0) * libm::cos(z.1), libm::cosh(z.0) * libm::sin(z.1))
15903}
15904
15905#[no_mangle]
15906pub unsafe extern "C" fn csinhf(z: (f32, f32)) -> (f32, f32) {
15907    (libm::sinhf(z.0) * libm::cosf(z.1), libm::coshf(z.0) * libm::sinf(z.1))
15908}
15909
15910#[no_mangle]
15911pub unsafe extern "C" fn csinhl(z: (f64, f64)) -> (f64, f64) {
15912    csinh(z)
15913}
15914
15915// ctanh: tanh(z) = sinh(2re)/(cosh(2re)+cos(2im)) + i*sin(2im)/(cosh(2re)+cos(2im))
15916#[no_mangle]
15917pub unsafe extern "C" fn ctanh(z: (f64, f64)) -> (f64, f64) {
15918    let d = libm::cosh(2.0 * z.0) + libm::cos(2.0 * z.1);
15919    (libm::sinh(2.0 * z.0) / d, libm::sin(2.0 * z.1) / d)
15920}
15921
15922#[no_mangle]
15923pub unsafe extern "C" fn ctanhf(z: (f32, f32)) -> (f32, f32) {
15924    let d = libm::coshf(2.0 * z.0) + libm::cosf(2.0 * z.1);
15925    (libm::sinhf(2.0 * z.0) / d, libm::sinf(2.0 * z.1) / d)
15926}
15927
15928#[no_mangle]
15929pub unsafe extern "C" fn ctanhl(z: (f64, f64)) -> (f64, f64) {
15930    ctanh(z)
15931}
15932
15933// cacos: acos(z) = pi/2 - asin(z)
15934// asin(z) = -i * log(i*z + sqrt(1 - z^2))
15935#[no_mangle]
15936pub unsafe extern "C" fn cacos(z: (f64, f64)) -> (f64, f64) {
15937    let asin_z = casin(z);
15938    (3.14159265358979323846264338327950288419716939937510582097494459230781640 / 2.0 - asin_z.0, -asin_z.1)
15939}
15940
15941#[no_mangle]
15942pub unsafe extern "C" fn cacosf(z: (f32, f32)) -> (f32, f32) {
15943    let asin_z = casinf(z);
15944    (3.14159265358979323846264338327950288419716939937510582097494459230781640f32 / 2.0 - asin_z.0, -asin_z.1)
15945}
15946
15947#[no_mangle]
15948pub unsafe extern "C" fn cacosl(z: (f64, f64)) -> (f64, f64) {
15949    cacos(z)
15950}
15951
15952// casin: asin(z) = -i * log(i*z + sqrt(1 - z^2))
15953#[no_mangle]
15954pub unsafe extern "C" fn casin(z: (f64, f64)) -> (f64, f64) {
15955    // i*z = (-z.1, z.0)
15956    let iz = (-z.1, z.0);
15957    // 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)
15958    let one_minus_z2 = (1.0 - z.0 * z.0 + z.1 * z.1, -2.0 * z.0 * z.1);
15959    let sqrt_val = csqrt(one_minus_z2);
15960    let arg = clog((iz.0 + sqrt_val.0, iz.1 + sqrt_val.1));
15961    // -i * log(...) = (arg.1, -arg.0)
15962    (arg.1, -arg.0)
15963}
15964
15965#[no_mangle]
15966pub unsafe extern "C" fn casinf(z: (f32, f32)) -> (f32, f32) {
15967    let iz = (-z.1, z.0);
15968    let one_minus_z2 = (1.0 - z.0 * z.0 + z.1 * z.1, -2.0 * z.0 * z.1);
15969    let sqrt_val = csqrtf(one_minus_z2);
15970    let arg = clogf((iz.0 + sqrt_val.0, iz.1 + sqrt_val.1));
15971    (arg.1, -arg.0)
15972}
15973
15974#[no_mangle]
15975pub unsafe extern "C" fn casinl(z: (f64, f64)) -> (f64, f64) {
15976    casin(z)
15977}
15978
15979// catan: atan(z) = (i/2) * log((1 - i*z)/(1 + i*z))
15980#[no_mangle]
15981pub unsafe extern "C" fn catan(z: (f64, f64)) -> (f64, f64) {
15982    // i*z = (-z.1, z.0)
15983    // 1 - i*z = (1 + z.1, -z.0)
15984    // 1 + i*z = (1 - z.1, z.0)
15985    let num = (1.0 + z.1, -z.0);
15986    let den = (1.0 - z.1, z.0);
15987    let ratio = cdiv(num, den);
15988    let log_ratio = clog(ratio);
15989    // (i/2) * log = (-log.1/2, log.0/2)
15990    (-log_ratio.1 / 2.0, log_ratio.0 / 2.0)
15991}
15992
15993#[no_mangle]
15994pub unsafe extern "C" fn catanf(z: (f32, f32)) -> (f32, f32) {
15995    let num = (1.0 + z.1, -z.0);
15996    let den = (1.0 - z.1, z.0);
15997    let ratio = cdivf(num, den);
15998    let log_ratio = clogf(ratio);
15999    (-log_ratio.1 / 2.0, log_ratio.0 / 2.0)
16000}
16001
16002#[no_mangle]
16003pub unsafe extern "C" fn catanl(z: (f64, f64)) -> (f64, f64) {
16004    catan(z)
16005}
16006
16007// Helper: complex division
16008fn cdiv(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
16009    let d = b.0 * b.0 + b.1 * b.1;
16010    ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
16011}
16012
16013fn cdivf(a: (f32, f32), b: (f32, f32)) -> (f32, f32) {
16014    let d = b.0 * b.0 + b.1 * b.1;
16015    ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
16016}
16017
16018// cacosh: acosh(z) = log(z + sqrt(z^2 - 1))
16019#[no_mangle]
16020pub unsafe extern "C" fn cacosh(z: (f64, f64)) -> (f64, f64) {
16021    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16022    let z2_minus_1 = (z2.0 - 1.0, z2.1);
16023    let sqrt_val = csqrt(z2_minus_1);
16024    clog((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16025}
16026
16027#[no_mangle]
16028pub unsafe extern "C" fn cacoshf(z: (f32, f32)) -> (f32, f32) {
16029    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16030    let z2_minus_1 = (z2.0 - 1.0, z2.1);
16031    let sqrt_val = csqrtf(z2_minus_1);
16032    clogf((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16033}
16034
16035#[no_mangle]
16036pub unsafe extern "C" fn cacoshl(z: (f64, f64)) -> (f64, f64) {
16037    cacosh(z)
16038}
16039
16040// casinh: asinh(z) = log(z + sqrt(z^2 + 1))
16041#[no_mangle]
16042pub unsafe extern "C" fn casinh(z: (f64, f64)) -> (f64, f64) {
16043    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16044    let z2_plus_1 = (z2.0 + 1.0, z2.1);
16045    let sqrt_val = csqrt(z2_plus_1);
16046    clog((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16047}
16048
16049#[no_mangle]
16050pub unsafe extern "C" fn casinhf(z: (f32, f32)) -> (f32, f32) {
16051    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16052    let z2_plus_1 = (z2.0 + 1.0, z2.1);
16053    let sqrt_val = csqrtf(z2_plus_1);
16054    clogf((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16055}
16056
16057#[no_mangle]
16058pub unsafe extern "C" fn casinhl(z: (f64, f64)) -> (f64, f64) {
16059    casinh(z)
16060}
16061
16062// catanh: atanh(z) = (1/2) * log((1+z)/(1-z))
16063#[no_mangle]
16064pub unsafe extern "C" fn catanh(z: (f64, f64)) -> (f64, f64) {
16065    let num = (1.0 + z.0, z.1);
16066    let den = (1.0 - z.0, -z.1);
16067    let ratio = cdiv(num, den);
16068    let log_ratio = clog(ratio);
16069    (log_ratio.0 / 2.0, log_ratio.1 / 2.0)
16070}
16071
16072#[no_mangle]
16073pub unsafe extern "C" fn catanhf(z: (f32, f32)) -> (f32, f32) {
16074    let num = (1.0 + z.0, z.1);
16075    let den = (1.0 - z.0, -z.1);
16076    let ratio = cdivf(num, den);
16077    let log_ratio = clogf(ratio);
16078    (log_ratio.0 / 2.0, log_ratio.1 / 2.0)
16079}
16080
16081#[no_mangle]
16082pub unsafe extern "C" fn catanhl(z: (f64, f64)) -> (f64, f64) {
16083    catanh(z)
16084}
16085
16086// ============================================================
16087// Float math functions (f32 versions)
16088// ============================================================
16089
16090#[inline(never)]
16091#[no_mangle]
16092pub unsafe extern "C" fn fmaxf(x: f32, y: f32) -> f32 {
16093    fmaxf_impl(x, y)
16094}
16095
16096#[no_mangle]
16097pub unsafe extern "C" fn fdimf(x: f32, y: f32) -> f32 {
16098    if x.is_nan() || y.is_nan() {
16099        return f32::NAN;
16100    }
16101    if x > y { x - y } else { 0.0 }
16102}
16103
16104#[no_mangle]
16105pub unsafe extern "C" fn fmaf(x: f32, y: f32, z: f32) -> f32 {
16106    if (x.is_infinite() && y == 0.0) || (y.is_infinite() && x == 0.0) {
16107        feraiseexcept(FE_INVALID);
16108        return f32::NAN;
16109    }
16110    if x.is_nan() || y.is_nan() || z.is_nan() {
16111        return f32::NAN;
16112    }
16113    let r = libm::fmaf(x, y, z);
16114    if r.is_nan() {
16115        feraiseexcept(FE_INVALID);
16116    }
16117    r
16118}
16119
16120#[no_mangle]
16121pub unsafe extern "C" fn ilogbf(x: f32) -> i32 {
16122    if x.is_nan() {
16123        feraiseexcept(FE_INVALID);
16124        return -0x7fffffff - 1;
16125    }
16126    if x == 0.0 || x.is_infinite() {
16127        feraiseexcept(FE_INVALID);
16128        return if x == 0.0 { -0x7fffffff - 1 } else { 0x7fffffff };
16129    }
16130    let bits = x.to_bits();
16131    let exp = ((bits >> 23) & 0xff) as i32;
16132    if exp == 0 {
16133        let mut v = bits & 0x7fffff;
16134        let mut e = -126;
16135        while v < (1u32 << 23) { v <<= 1; e -= 1; }
16136        e
16137    } else {
16138        exp - 127
16139    }
16140}
16141
16142#[no_mangle]
16143pub unsafe extern "C" fn logbf(x: f32) -> f32 {
16144    if x.is_nan() { return x; }
16145    if x == 0.0 { return __math_divzerof(1); }
16146    let bits = x.to_bits();
16147    let exp = ((bits >> 23) & 0xff) as i32;
16148    if exp == 0 {
16149        let mut v = bits & 0x7fffff;
16150        let mut e = -126i32;
16151        while v < (1u32 << 23) { v <<= 1; e -= 1; }
16152        e as f32
16153    } else if exp == 0xff {
16154        x * x
16155    } else {
16156        (exp - 127) as f32
16157    }
16158}
16159
16160#[no_mangle]
16161pub unsafe extern "C" fn nearbyintf(x: f32) -> f32 {
16162    let had_inexact = fetestexcept(FE_INEXACT) & FE_INEXACT != 0;
16163    let r = libm::rintf(x);
16164    if !had_inexact {
16165        feclearexcept(FE_INEXACT);
16166    }
16167    r
16168}
16169
16170#[no_mangle]
16171pub unsafe extern "C" fn nextafterf(x: f32, y: f32) -> f32 {
16172    if x.is_nan() || y.is_nan() { return x + y; }
16173    if x == 0.0 && y == 0.0 { return y; }
16174    if x == y { return x; }
16175    let r = libm::nextafterf(x, y);
16176    if r.is_infinite() && x.is_finite() {
16177        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
16178    } else if r != x {
16179        let bits = r.to_bits();
16180        let is_subnormal = (bits & 0x7f800000) == 0 && (bits & 0x7fffff) != 0;
16181        if r == 0.0 || is_subnormal {
16182            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16183        }
16184    }
16185    r
16186}
16187
16188#[no_mangle]
16189#[cfg(target_arch = "x86_64")]
16190pub unsafe extern "C" fn nexttowardf(x: f32, y: f64) -> f32 {
16191    if y.is_nan() { return (x as f64 + y) as f32; }
16192    if x == 0.0 && y == 0.0 {
16193        return if y.is_sign_negative() { -0.0 } else { 0.0 };
16194    }
16195    if (x as f64) == y { return x; }
16196    nextafterf(x, if y > x as f64 { f32::INFINITY } else { f32::NEG_INFINITY })
16197}
16198
16199#[no_mangle]
16200#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
16201pub unsafe extern "C" fn nexttowardf(x: f32, y: f128) -> f32 {
16202    if y.is_nan() { return (x as f128 + y) as f32; }
16203    if (x as f128) == y { return x; }
16204    nextafterf(x, if y > x as f128 { f32::INFINITY } else { f32::NEG_INFINITY })
16205}
16206
16207#[no_mangle]
16208pub unsafe extern "C" fn remainderf(x: f32, y: f32) -> f32 {
16209    if x.is_nan() || y.is_nan() { return x + y; }
16210    if y == 0.0 || x.is_infinite() { return __math_invalidf(x); }
16211    libm::remainderf(x, y)
16212}
16213
16214#[no_mangle]
16215pub unsafe extern "C" fn remquof(x: f32, y: f32, quo: *mut i32) -> f32 {
16216    if x.is_nan() || y.is_nan() {
16217        if !quo.is_null() { *quo = 0; }
16218        return x + y;
16219    }
16220    if y == 0.0 || x.is_infinite() {
16221        if !quo.is_null() { *quo = 0; }
16222        return __math_invalidf(x);
16223    }
16224    let (r, q) = libm::remquof(x, y);
16225    if !quo.is_null() { *quo = q; }
16226    r
16227}
16228
16229#[no_mangle]
16230pub unsafe extern "C" fn exp2f(x: f32) -> f32 {
16231    if x == f32::INFINITY { return f32::INFINITY; }
16232    if x == f32::NEG_INFINITY { return 0.0; }
16233    if x.is_nan() { return f32::NAN; }
16234    let r = libm::exp2f(x);
16235    if r.is_infinite() && x.is_finite() {
16236        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
16237    } else if r == 0.0 && x < -149.0 {
16238        feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16239    } else if r != 0.0 && x != libm::truncf(x) {
16240        let bits = r.to_bits();
16241        if (bits & 0x7f800000) == 0 {
16242            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16243        }
16244    }
16245    r
16246}
16247
16248#[no_mangle]
16249pub unsafe extern "C" fn expm1f(x: f32) -> f32 {
16250    libm::expm1f(x)
16251}
16252
16253#[no_mangle]
16254pub unsafe extern "C" fn log1pf(x: f32) -> f32 {
16255    if x == -1.0 {
16256        feraiseexcept(FE_DIVBYZERO);
16257        return f32::NEG_INFINITY;
16258    }
16259    libm::log1pf(x)
16260}
16261
16262#[no_mangle]
16263pub unsafe extern "C" fn acoshf(x: f32) -> f32 {
16264    if x < 1.0 {
16265        feraiseexcept(FE_INVALID);
16266        return f32::NAN;
16267    }
16268    libm::acoshf(x)
16269}
16270
16271#[no_mangle]
16272pub unsafe extern "C" fn asinhf(x: f32) -> f32 {
16273    if x == 0.0 { return x; }
16274    libm::asinhf(x)
16275}
16276
16277#[no_mangle]
16278pub unsafe extern "C" fn atanhf(x: f32) -> f32 {
16279    if x == 0.0 { return x; }
16280    let e = ((x.to_bits() >> 23) & 0xff) as i32;
16281    if e < 0x7f - 32 {
16282        feraiseexcept(FE_INEXACT);
16283        if e == 0 { feraiseexcept(FE_UNDERFLOW); }
16284        return x;
16285    }
16286    if x == 1.0 {
16287        feraiseexcept(FE_DIVBYZERO);
16288        return f32::INFINITY;
16289    }
16290    if x == -1.0 {
16291        feraiseexcept(FE_DIVBYZERO);
16292        return f32::NEG_INFINITY;
16293    }
16294    if x.is_nan() { return x; }
16295    let ax = libm::fabsf(x);
16296    if ax > 1.0 {
16297        feraiseexcept(FE_INVALID);
16298        return f32::NAN;
16299    }
16300    if ax < 0.5 {
16301        let r = libm::log1pf(2.0 * (ax + ax * ax / (1.0 - ax))) / 2.0;
16302        if x < 0.0 { -r } else { r }
16303    } else {
16304        let r = 0.5 * libm::logf((1.0 + ax) / (1.0 - ax));
16305        if x < 0.0 { -r } else { r }
16306    }
16307}
16308
16309#[no_mangle]
16310pub unsafe extern "C" fn cbrtf(x: f32) -> f32 {
16311    libm::cbrtf(x)
16312}
16313
16314#[no_mangle]
16315pub unsafe extern "C" fn erff(x: f32) -> f32 {
16316    libm::erff(x)
16317}
16318
16319#[no_mangle]
16320pub unsafe extern "C" fn erfcf(x: f32) -> f32 {
16321    libm::erfcf(x)
16322}
16323
16324#[no_mangle]
16325pub unsafe extern "C" fn lgammaf(x: f32) -> f32 {
16326    if x.is_nan() {
16327        crate::signgam = 1;
16328        return x;
16329    }
16330    if x == 0.0 {
16331        crate::signgam = if x.is_sign_negative() { -1 } else { 1 };
16332        feraiseexcept(FE_DIVBYZERO);
16333        return f32::INFINITY;
16334    }
16335    let (r, sign) = libm::lgammaf_r(x);
16336    crate::signgam = sign;
16337    r
16338}
16339
16340#[no_mangle]
16341pub unsafe extern "C" fn tgammaf(x: f32) -> f32 {
16342    if x.is_nan() { return x; }
16343    if x == 0.0 {
16344        feraiseexcept(FE_DIVBYZERO);
16345        return if x.is_sign_negative() { f32::NEG_INFINITY } else { f32::INFINITY };
16346    }
16347    if x.is_infinite() {
16348        return if x.is_sign_negative() { __math_invalidf(x) } else { f32::INFINITY };
16349    }
16350    if x < 0.0 && x == libm::floorf(x) {
16351        feraiseexcept(FE_INVALID);
16352        return f32::NAN;
16353    }
16354    libm::tgammaf(x)
16355}
16356
16357#[no_mangle]
16358pub unsafe extern "C" fn lroundf(x: f32) -> core::ffi::c_long {
16359    libm::roundf(x) as core::ffi::c_long
16360}
16361
16362#[no_mangle]
16363pub unsafe extern "C" fn llroundf(x: f32) -> i64 {
16364    libm::roundf(x) as i64
16365}
16366
16367// ============================================================
16368// Wide char functions
16369// ============================================================
16370
16371#[no_mangle]
16372pub unsafe extern "C" fn wcscasecmp(s1: *const u32, s2: *const u32) -> i32 {
16373    let mut i = 0;
16374    loop {
16375        let c1 = *s1.add(i);
16376        let c2 = *s2.add(i);
16377        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16378        let l1 = if c1 >= 'A' as u32 && c1 <= 'Z' as u32 { c1 + 32 } else { c1 };
16379        let l2 = if c2 >= 'A' as u32 && c2 <= 'Z' as u32 { c2 + 32 } else { c2 };
16380        if l1 != l2 { return (l1 as i32) - (l2 as i32); }
16381        i += 1;
16382    }
16383}
16384
16385#[no_mangle]
16386pub unsafe extern "C" fn wcscasecmp_l(s1: *const u32, s2: *const u32, _loc: *mut core::ffi::c_void) -> i32 {
16387    wcscasecmp(s1, s2)
16388}
16389
16390#[no_mangle]
16391pub unsafe extern "C" fn wcsncasecmp(s1: *const u32, s2: *const u32, n: usize) -> i32 {
16392    let mut i = 0;
16393    while i < n {
16394        let c1 = *s1.add(i);
16395        let c2 = *s2.add(i);
16396        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16397        let l1 = if c1 >= 'A' as u32 && c1 <= 'Z' as u32 { c1 + 32 } else { c1 };
16398        let l2 = if c2 >= 'A' as u32 && c2 <= 'Z' as u32 { c2 + 32 } else { c2 };
16399        if l1 != l2 { return (l1 as i32) - (l2 as i32); }
16400        i += 1;
16401    }
16402    0
16403}
16404
16405#[no_mangle]
16406pub unsafe extern "C" fn wcsncasecmp_l(s1: *const u32, s2: *const u32, n: usize, _loc: *mut core::ffi::c_void) -> i32 {
16407    wcsncasecmp(s1, s2, n)
16408}
16409
16410#[no_mangle]
16411pub unsafe extern "C" fn wcscoll(s1: *const u32, s2: *const u32) -> i32 {
16412    // ponytail: simplified collation - just compare codepoints
16413    let mut i = 0;
16414    loop {
16415        let c1 = *s1.add(i);
16416        let c2 = *s2.add(i);
16417        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16418        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
16419        i += 1;
16420    }
16421}
16422
16423#[no_mangle]
16424pub unsafe extern "C" fn wcstok(s: *mut u32, sep: *const u32, p: *mut *mut u32) -> *mut u32 {
16425    let mut src = if s.is_null() { *p } else { s };
16426    // Skip leading separators
16427    while *src != 0 && *sep.add(0) == *src { src = src.add(1); }
16428    if *src == 0 { return core::ptr::null_mut(); }
16429    let start = src;
16430    // Find end of token
16431    while *src != 0 && *sep.add(0) != *src { src = src.add(1); }
16432    if *src != 0 {
16433        *src = 0;
16434        *p = src.add(1);
16435    } else {
16436        *p = src;
16437    }
16438    start
16439}
16440
16441#[no_mangle]
16442pub unsafe extern "C" fn wcswcs(haystack: *const u32, needle: *const u32) -> *mut u32 {
16443    if *needle == 0 { return haystack as *mut u32; }
16444    let mut i = 0;
16445    while *haystack.add(i) != 0 {
16446        let mut j = 0;
16447        while *needle.add(j) != 0 && *haystack.add(i + j) == *needle.add(j) {
16448            j += 1;
16449        }
16450        if *needle.add(j) == 0 { return haystack.add(i) as *mut u32; }
16451        i += 1;
16452    }
16453    core::ptr::null_mut()
16454}
16455
16456#[no_mangle]
16457pub unsafe extern "C" fn wcswidth(s: *const u32, n: usize) -> i32 {
16458    let mut width = 0i32;
16459    let mut i = 0;
16460    while i < n {
16461        let c = *s.add(i);
16462        if c == 0 { break; }
16463        // ponytail: simplified width - assume all printable chars are width 1
16464        width += 1;
16465        i += 1;
16466    }
16467    width
16468}
16469
16470#[no_mangle]
16471pub unsafe extern "C" fn wcsftime(s: *mut u32, maxsize: usize, fmt: *const u32, tm: *const c_void) -> usize {
16472    if s.is_null() || fmt.is_null() || maxsize == 0 { return 0; }
16473    // Convert the wide format string to multibyte, let strftime do the work,
16474    // then convert the result back.
16475    let mut cfmt = [0u8; 1024];
16476    let mut o = 0usize;
16477    let mut i = 0usize;
16478    let mut st: c_uint = 0;
16479    while *fmt.add(i) != 0 && o + 8 < cfmt.len() {
16480        let n = wcrtomb(
16481            cfmt.as_mut_ptr().add(o) as *mut c_char,
16482            *fmt.add(i) as c_int,
16483            &mut st as *mut c_uint,
16484        );
16485        if n == !0usize { return 0; }
16486        o += n;
16487        i += 1;
16488    }
16489    cfmt[o] = 0;
16490    let mut out = [0u8; 4096];
16491    let mut lim = maxsize.saturating_mul(4);
16492    if lim > out.len() { lim = out.len(); }
16493    let n = strftime(out.as_mut_ptr() as *mut c_char, lim, cfmt.as_ptr() as *const c_char, tm as *const tm);
16494    if n == 0 { return 0; }
16495    let mut ws = 0usize;
16496    let mut p = 0usize;
16497    while p < n && ws + 1 < maxsize {
16498        let mut wc: c_int = 0;
16499        let mut st2: c_uint = 0;
16500        let r = mbrtowc(&mut wc, out.as_ptr().add(p) as *const c_char, n - p, &mut st2);
16501        if r == !0usize { return 0; }
16502        if r == 0 || r == !1usize { break; }
16503        *s.add(ws) = wc as u32;
16504        ws += 1;
16505        p += r;
16506    }
16507    *s.add(ws) = 0;
16508    ws
16509}
16510
16511#[no_mangle]
16512pub unsafe extern "C" fn mbsnrtowcs(
16513    dst: *mut u32,
16514    src: *mut *const u8,
16515    nms: usize,
16516    len: usize,
16517    st: *mut core::ffi::c_void,
16518) -> usize {
16519    if src.is_null() { return 0; }
16520    let mut s = *src;
16521    if s.is_null() { return 0; }
16522    let state = st as *mut c_uint;
16523    let limit = if dst.is_null() { usize::MAX } else { len };
16524    let mut count = 0usize;
16525    let mut n = nms;
16526    while count < limit && n > 0 {
16527        let c = *s;
16528        if c == 0 {
16529            if !dst.is_null() {
16530                if count < len { *dst.add(count) = 0; }
16531                *src = core::ptr::null();
16532            }
16533            return count;
16534        }
16535        let mut wc: c_int = 0;
16536        let r = mbrtowc(&mut wc, s as *const c_char, n, state);
16537        if r == !0usize {
16538            *src = s;
16539            return !0usize;
16540        }
16541        if r == !1usize { break; }
16542        if !dst.is_null() { *dst.add(count) = wc as u32; }
16543        count += 1;
16544        s = s.add(r);
16545        n -= r;
16546    }
16547    *src = s;
16548    count
16549}
16550
16551#[no_mangle]
16552pub unsafe extern "C" fn wcsnrtombs(dst: *mut u8, src: *mut *const u32, nwc: usize, len: usize, _st: *mut core::ffi::c_void) -> usize {
16553    let mut count = 0;
16554    let mut s = *src;
16555    let mut d = dst;
16556    while count < len && count < nwc {
16557        let c = *s;
16558        if c == 0 { break; }
16559        if !d.is_null() {
16560            if c < 0x80 {
16561                *d = c as u8;
16562                d = d.add(1);
16563                count += 1;
16564            } else if c < 0x800 {
16565                if count + 2 > len { break; }
16566                *d = 0xc0 | (c >> 6) as u8;
16567                *d.add(1) = 0x80 | (c & 0x3f) as u8;
16568                d = d.add(2);
16569                count += 2;
16570            } else if c < 0x10000 {
16571                if count + 3 > len { break; }
16572                *d = 0xe0 | (c >> 12) as u8;
16573                *d.add(1) = 0x80 | ((c >> 6) & 0x3f) as u8;
16574                *d.add(2) = 0x80 | (c & 0x3f) as u8;
16575                d = d.add(3);
16576                count += 3;
16577            } else {
16578                if count + 4 > len { break; }
16579                *d = 0xf0 | (c >> 18) as u8;
16580                *d.add(1) = 0x80 | ((c >> 12) & 0x3f) as u8;
16581                *d.add(2) = 0x80 | ((c >> 6) & 0x3f) as u8;
16582                *d.add(3) = 0x80 | (c & 0x3f) as u8;
16583                d = d.add(4);
16584                count += 4;
16585            }
16586        }
16587        s = s.add(1);
16588    }
16589    if !dst.is_null() { *src = s; }
16590    count
16591}
16592
16593// ============================================================
16594// Thread sync functions (C11 threads)
16595// ============================================================
16596
16597
16598// C11 thread types
16599pub type thrd_start_t = Option<unsafe extern "C" fn(arg: *mut core::ffi::c_void) -> i32>;
16600
16601// Thread function stubs - these need actual implementation
16602#[no_mangle]
16603pub unsafe extern "C" fn thrd_create(thr: *mut usize, func: thrd_start_t, arg: *mut core::ffi::c_void) -> i32 {
16604    let mut thread: u64 = 0;
16605    let r = pthread_create(&mut thread, core::ptr::null(), core::mem::transmute(func), arg);
16606    if r == 0 {
16607        *thr = thread as usize;
16608        0 // thrd_success
16609    } else {
16610        -1 // thrd_nomem
16611    }
16612}
16613
16614#[no_mangle]
16615pub unsafe extern "C" fn thrd_join(thr: usize, res: *mut i32) -> i32 {
16616    let mut retval: *mut core::ffi::c_void = core::ptr::null_mut();
16617    let r = pthread_join(thr as u64, &mut retval);
16618    if r == 0 {
16619        if !res.is_null() { *res = retval as i32; }
16620        0
16621    } else {
16622        -1
16623    }
16624}
16625
16626#[no_mangle]
16627pub unsafe extern "C" fn thrd_exit(res: i32) {
16628    pthread_exit(res as *mut core::ffi::c_void);
16629}
16630
16631#[no_mangle]
16632pub unsafe extern "C" fn thrd_detach(thr: usize) -> i32 {
16633    let r = pthread_detach(thr as u64);
16634    if r == 0 { 0 } else { -1 }
16635}
16636
16637#[no_mangle]
16638pub unsafe extern "C" fn thrd_current() -> usize {
16639    pthread_self() as usize
16640}
16641
16642#[no_mangle]
16643pub unsafe extern "C" fn thrd_equal(thr1: usize, thr2: usize) -> i32 {
16644    (thr1 == thr2) as i32
16645}
16646
16647#[no_mangle]
16648pub unsafe extern "C" fn thrd_sleep(duration: *const core::ffi::c_void, remaining: *mut core::ffi::c_void) -> i32 {
16649    nanosleep(duration as *const timespec, remaining as *mut timespec)
16650}
16651
16652#[no_mangle]
16653pub unsafe extern "C" fn thrd_yield() {
16654    sched_yield();
16655}
16656
16657// Mutex
16658#[no_mangle]
16659pub unsafe extern "C" fn mtx_init(mtx: *mut usize, _mtx_type: i32) -> i32 {
16660    let r = pthread_mutex_init(mtx as *mut pthread_mutex_t, core::ptr::null());
16661    if r == 0 { 0 } else { -1 }
16662}
16663
16664#[no_mangle]
16665pub unsafe extern "C" fn mtx_lock(mtx: *mut usize) -> i32 {
16666    let r = pthread_mutex_lock(mtx as *mut pthread_mutex_t);
16667    if r == 0 { 0 } else { -1 }
16668}
16669
16670#[no_mangle]
16671pub unsafe extern "C" fn mtx_trylock(mtx: *mut usize) -> i32 {
16672    let r = pthread_mutex_trylock(mtx as *mut pthread_mutex_t);
16673    if r == 0 { 0 } else { -1 }
16674}
16675
16676#[no_mangle]
16677pub unsafe extern "C" fn mtx_unlock(mtx: *mut usize) -> i32 {
16678    let r = pthread_mutex_unlock(mtx as *mut pthread_mutex_t);
16679    if r == 0 { 0 } else { -1 }
16680}
16681
16682#[no_mangle]
16683pub unsafe extern "C" fn mtx_destroy(mtx: *mut usize) {
16684    pthread_mutex_destroy(mtx as *mut pthread_mutex_t);
16685}
16686
16687#[no_mangle]
16688pub unsafe extern "C" fn mtx_timedlock(mtx: *mut usize, ts: *const core::ffi::c_void) -> i32 {
16689    let r = pthread_mutex_timedlock(mtx as *mut pthread_mutex_t, ts as *const timespec);
16690    if r == 0 { 0 } else { -1 }
16691}
16692
16693// Condition variable
16694#[no_mangle]
16695pub unsafe extern "C" fn cnd_init(cnd: *mut usize) -> i32 {
16696    let r = pthread_cond_init(cnd as *mut pthread_cond_t, core::ptr::null());
16697    if r == 0 { 0 } else { -1 }
16698}
16699
16700#[no_mangle]
16701pub unsafe extern "C" fn cnd_signal(cnd: *mut usize) -> i32 {
16702    let r = pthread_cond_signal(cnd as *mut pthread_cond_t);
16703    if r == 0 { 0 } else { -1 }
16704}
16705
16706#[no_mangle]
16707pub unsafe extern "C" fn cnd_broadcast(cnd: *mut usize) -> i32 {
16708    let r = pthread_cond_broadcast(cnd as *mut pthread_cond_t);
16709    if r == 0 { 0 } else { -1 }
16710}
16711
16712#[no_mangle]
16713pub unsafe extern "C" fn cnd_wait(cnd: *mut usize, mtx: *mut usize) -> i32 {
16714    let r = pthread_cond_wait(cnd as *mut pthread_cond_t, mtx as *mut pthread_mutex_t);
16715    if r == 0 { 0 } else { -1 }
16716}
16717
16718#[no_mangle]
16719pub unsafe extern "C" fn cnd_timedwait(cnd: *mut usize, mtx: *mut usize, ts: *const core::ffi::c_void) -> i32 {
16720    let r = pthread_cond_timedwait(cnd as *mut pthread_cond_t, mtx as *mut pthread_mutex_t, ts as *const timespec);
16721    if r == 0 { 0 } else { -1 }
16722}
16723
16724#[no_mangle]
16725pub unsafe extern "C" fn cnd_destroy(cnd: *mut usize) {
16726    pthread_cond_destroy(cnd as *mut pthread_cond_t);
16727}
16728
16729// Thread-specific storage
16730#[no_mangle]
16731pub unsafe extern "C" fn tss_create(key: *mut u32, dtor: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>) -> i32 {
16732    let r = pthread_key_create(key, dtor);
16733    if r == 0 { 0 } else { -1 }
16734}
16735
16736#[no_mangle]
16737pub unsafe extern "C" fn tss_delete(key: u32) {
16738    pthread_key_delete(key);
16739}
16740
16741#[no_mangle]
16742pub unsafe extern "C" fn tss_set(key: u32, val: *mut core::ffi::c_void) -> i32 {
16743    let r = pthread_setspecific(key, val);
16744    if r == 0 { 0 } else { -1 }
16745}
16746
16747#[no_mangle]
16748pub unsafe extern "C" fn tss_get(key: u32) -> *mut core::ffi::c_void {
16749    pthread_getspecific(key)
16750}
16751
16752// call_once
16753#[no_mangle]
16754pub unsafe extern "C" fn call_once(flag: *mut u32, func: Option<unsafe extern "C" fn()>) {
16755    if *flag == 0 {
16756        if let Some(f) = func { f(); }
16757        *flag = 1;
16758    }
16759}
16760
16761// ============================================================
16762// Network functions
16763// ============================================================
16764
16765// accept4 - Linux-specific extension
16766#[no_mangle]
16767pub unsafe extern "C" fn accept4(fd: i32, addr: *mut core::ffi::c_void, addrlen: *mut u32, flags: i32) -> i32 {
16768    syscall_ret(<Arch as Syscalls>::syscall4(SYS_ACCEPT4, fd as i64, addr as i64, addrlen as i64, flags as i64)) as i32
16769}
16770
16771// getifaddrs / freeifaddrs
16772// ============================================================
16773// epoll/eventfd/signalfd/timerfd
16774// ============================================================
16775
16776#[no_mangle]
16777pub unsafe extern "C" fn epoll_create(size: i32) -> i32 {
16778    #[cfg(target_arch = "x86_64")]
16779    { syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE, size as i64)) as i32 }
16780    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
16781    {
16782        if size < 1 {
16783            ERRNO!() = EINVAL;
16784            return -1;
16785        }
16786        syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE1, 0)) as i32
16787    }
16788}
16789
16790#[no_mangle]
16791pub unsafe extern "C" fn epoll_create1(flags: i32) -> i32 {
16792    syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE1, flags as i64)) as i32
16793}
16794
16795#[no_mangle]
16796pub unsafe extern "C" fn epoll_ctl(epfd: i32, op: i32, fd: i32, event: *mut core::ffi::c_void) -> i32 {
16797    syscall_ret(<Arch as Syscalls>::syscall4(SYS_EPOLL_CTL, epfd as i64, op as i64, fd as i64, event as i64)) as i32
16798}
16799
16800#[no_mangle]
16801pub unsafe extern "C" fn epoll_wait(epfd: i32, events: *mut core::ffi::c_void, maxevents: i32, timeout: i32) -> i32 {
16802    #[cfg(target_arch = "x86_64")]
16803    {
16804        syscall_ret(<Arch as Syscalls>::syscall4(
16805            SYS_EPOLL_WAIT,
16806            epfd as i64,
16807            events as i64,
16808            maxevents as i64,
16809            timeout as i64,
16810        )) as i32
16811    }
16812    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
16813    {
16814        epoll_pwait(epfd, events, maxevents, timeout, core::ptr::null())
16815    }
16816}
16817
16818#[no_mangle]
16819pub unsafe extern "C" fn epoll_pwait(
16820    epfd: i32,
16821    events: *mut core::ffi::c_void,
16822    maxevents: i32,
16823    timeout: i32,
16824    sigmask: *const u64,
16825) -> i32 {
16826    syscall_ret(<Arch as Syscalls>::syscall6(
16827        SYS_EPOLL_PWAIT,
16828        epfd as i64,
16829        events as i64,
16830        maxevents as i64,
16831        timeout as i64,
16832        sigmask as i64,
16833        8,
16834    )) as i32
16835}
16836
16837#[no_mangle]
16838pub unsafe extern "C" fn eventfd(initval: u32, flags: i32) -> i32 {
16839    syscall_ret(<Arch as Syscalls>::syscall2(SYS_EVENTFD2, initval as i64, flags as i64)) as i32
16840}
16841
16842#[no_mangle]
16843pub unsafe extern "C" fn eventfd_read(fd: i32, value: *mut u64) -> i32 {
16844    let n = crate::read(fd, value as *mut core::ffi::c_void, 8);
16845    if n == 8 { 0 } else { -1 }
16846}
16847
16848#[no_mangle]
16849pub unsafe extern "C" fn eventfd_write(fd: i32, value: u64) -> i32 {
16850    let n = crate::write(fd, &value as *const u64 as *const core::ffi::c_void, 8);
16851    if n == 8 { 0 } else { -1 }
16852}
16853
16854#[no_mangle]
16855pub unsafe extern "C" fn signalfd(fd: i32, mask: *const u64, flags: i32) -> i32 {
16856    syscall_ret(<Arch as Syscalls>::syscall4(SYS_SIGNALFD4, fd as i64, mask as i64, 8, flags as i64)) as i32
16857}
16858
16859#[no_mangle]
16860pub unsafe extern "C" fn timerfd_create(clockid: i32, flags: i32) -> i32 {
16861    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMERFD_CREATE, clockid as i64, flags as i64)) as i32
16862}
16863
16864#[no_mangle]
16865pub 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 {
16866    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
16867}
16868
16869#[no_mangle]
16870pub unsafe extern "C" fn timerfd_gettime(fd: i32, curr_value: *mut core::ffi::c_void) -> i32 {
16871    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMERFD_GETTIME, fd as i64, curr_value as i64)) as i32
16872}
16873
16874// ============================================================
16875// System functions
16876// ============================================================
16877
16878#[no_mangle]
16879pub unsafe extern "C" fn prctl(option: i32, mut args: ...) -> i32 {
16880    let a1 = args.next_arg::<i64>();
16881    let a2 = args.next_arg::<i64>();
16882    let a3 = args.next_arg::<i64>();
16883    let a4 = args.next_arg::<i64>();
16884    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PRCTL, option as i64, a1, a2, a3, a4)) as i32
16885}
16886
16887#[no_mangle]
16888pub unsafe extern "C" fn quotactl(cmd: i32, special: *const core::ffi::c_char, id: i32, addr: *mut core::ffi::c_char) -> i32 {
16889    syscall_ret(<Arch as Syscalls>::syscall4(sysno(179, 60), cmd as i64, special as i64, id as i64, addr as i64)) as i32
16890}
16891
16892#[no_mangle]
16893pub unsafe extern "C" fn klogctl(type_: i32, bufp: *mut core::ffi::c_char, len: i32) -> i32 {
16894    syscall_ret(<Arch as Syscalls>::syscall3(sysno(103, 116), type_ as i64, bufp as i64, len as i64)) as i32
16895}
16896
16897static mut SYSLOG_IDENT: [core::ffi::c_char; 64] = [0; 64];
16898static mut SYSLOG_OPTIONS: i32 = 0;
16899static mut SYSLOG_FACILITY: i32 = 1;
16900
16901#[no_mangle]
16902pub unsafe extern "C" fn openlog(ident: *const core::ffi::c_char, option: i32, facility: i32) {
16903    SYSLOG_OPTIONS = option;
16904    SYSLOG_FACILITY = facility & 0x3f8;
16905    SYSLOG_IDENT[0] = 0;
16906    if !ident.is_null() {
16907        let mut i = 0;
16908        while i < 63 && *ident.add(i) != 0 {
16909            SYSLOG_IDENT[i] = *ident.add(i);
16910            i += 1;
16911        }
16912        SYSLOG_IDENT[i] = 0;
16913    }
16914}
16915
16916#[repr(C)]
16917struct SockAddrUn {
16918    sun_family: u16,
16919    sun_path: [core::ffi::c_char; 108],
16920}
16921
16922unsafe fn syslog_emit(priority: i32, msg: *const core::ffi::c_char, len: usize) {
16923    let mut out = [0u8; 1200];
16924    let mut o = 0usize;
16925    let pri = (SYSLOG_FACILITY | (priority & 7)) as u32;
16926    out[o] = b'<'; o += 1;
16927    if pri >= 100 { out[o] = b'0' + (pri / 100) as u8; o += 1; }
16928    if pri >= 10 { out[o] = b'0' + ((pri / 10) % 10) as u8; o += 1; }
16929    out[o] = b'0' + (pri % 10) as u8; o += 1;
16930    out[o] = b'>'; o += 1;
16931    let mut i = 0;
16932    while i < 63 && SYSLOG_IDENT[i] != 0 && o + 1 < out.len() {
16933        out[o] = SYSLOG_IDENT[i] as u8; o += 1; i += 1;
16934    }
16935    if SYSLOG_OPTIONS & 1 != 0 {
16936        out[o] = b'['; o += 1;
16937        let mut pid = crate::getpid() as u32;
16938        let mut digits = [0u8; 10];
16939        let mut d = 0;
16940        if pid == 0 { digits[0] = b'0'; d = 1; }
16941        while pid > 0 { digits[d] = b'0' + (pid % 10) as u8; pid /= 10; d += 1; }
16942        while d > 0 { d -= 1; out[o] = digits[d]; o += 1; }
16943        out[o] = b']'; o += 1;
16944    }
16945    out[o] = b':'; o += 1; out[o] = b' '; o += 1;
16946    let copy = core::cmp::min(len, out.len() - o - 1);
16947    core::ptr::copy_nonoverlapping(msg as *const u8, out.as_mut_ptr().add(o), copy);
16948    o += copy;
16949    let fd = crate::socket(AF_UNIX, SOCK_DGRAM, 0);
16950    if fd >= 0 {
16951        let mut sa: SockAddrUn = core::mem::zeroed();
16952        sa.sun_family = AF_UNIX as u16;
16953        let path = b"/dev/log";
16954        for i in 0..path.len() { sa.sun_path[i] = path[i] as core::ffi::c_char; }
16955        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);
16956        crate::close(fd);
16957        if r >= 0 { return; }
16958    }
16959    crate::write(2, out.as_ptr() as *const core::ffi::c_void, o);
16960    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
16961}
16962
16963#[no_mangle]
16964pub unsafe extern "C" fn vsyslog(priority: c_int, fmt: *const c_char, ap: VaList) {
16965    let mut msg = [0 as c_char; 1024];
16966    let n = vsnprintf(msg.as_mut_ptr(), msg.len(), fmt, ap);
16967    if n > 0 { syslog_emit(priority, msg.as_ptr(), core::cmp::min(n as usize, msg.len() - 1)); }
16968}
16969
16970#[no_mangle]
16971pub unsafe extern "C" fn syslog(priority: c_int, fmt: *const c_char, args: ...) {
16972    vsyslog(priority, fmt, args);
16973}
16974
16975#[no_mangle]
16976pub unsafe extern "C" fn closelog() {
16977    // Nothing to do
16978}
16979
16980#[no_mangle]
16981pub unsafe extern "C" fn setlogmask(mask: i32) -> i32 {
16982    static mut LOG_MASK: i32 = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80;
16983    let old = LOG_MASK;
16984    if mask != 0 { LOG_MASK = mask; }
16985    old
16986}
16987
16988#[no_mangle]
16989pub unsafe extern "C" fn acct(filename: *const core::ffi::c_char) -> i32 {
16990    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ACCT, filename as i64)) as i32
16991}
16992
16993#[no_mangle]
16994pub unsafe extern "C" fn swapon(path: *const core::ffi::c_char, flags: i32) -> i32 {
16995    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SWAPON, path as i64, flags as i64)) as i32
16996}
16997
16998#[no_mangle]
16999pub unsafe extern "C" fn swapoff(path: *const core::ffi::c_char) -> i32 {
17000    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SWAPOFF, path as i64)) as i32
17001}
17002
17003#[no_mangle]
17004pub unsafe extern "C" fn syncfs(fd: i32) -> i32 {
17005    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SYNCFS, fd as i64)) as i32
17006}
17007
17008#[no_mangle]
17009pub unsafe extern "C" fn sync_file_range(fd: i32, offset: i64, nbytes: u64, flags: u32) -> i32 {
17010    syscall_ret(<Arch as Syscalls>::syscall4(sysno(277, 84), fd as i64, offset, nbytes as i64, flags as i64)) as i32
17011}
17012
17013#[no_mangle]
17014pub unsafe extern "C" fn posix_fadvise(fd: i32, offset: i64, len: u64, advice: i32) -> i32 {
17015    // POSIX returns the error number directly, not -1/errno.
17016    let r = <Arch as Syscalls>::syscall4(sysno(221, 223), fd as i64, offset, len as i64, advice as i64);
17017    if r < 0 { (-r) as i32 } else { 0 }
17018}
17019
17020#[no_mangle]
17021pub unsafe extern "C" fn posix_fallocate(fd: i32, offset: i64, len: u64) -> i32 {
17022    let r = <Arch as Syscalls>::syscall3(SYS_FALLOCATE, fd as i64, offset, len as i64);
17023    if r < 0 { (-r) as i32 } else { 0 }
17024}
17025
17026#[no_mangle]
17027pub unsafe extern "C" fn readahead(fd: i32, offset: i64, count: usize) -> isize {
17028    // musl declares readahead() as ssize_t; returning int leaves the upper
17029    // half of rax undefined for callers that expect a 64-bit result.
17030    syscall_ret(<Arch as Syscalls>::syscall3(sysno(187, 213), fd as i64, offset, count as i64)) as isize
17031}
17032
17033#[no_mangle]
17034pub unsafe extern "C" fn fallocate(fd: i32, mode: i32, offset: i64, len: u64) -> i32 {
17035    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FALLOCATE, fd as i64, mode as i64, offset, len as i64)) as i32
17036}
17037
17038// ============================================================
17039// Terminal functions
17040// ============================================================
17041
17042#[no_mangle]
17043pub unsafe extern "C" fn tcgetattr(fd: i32, termios_p: *mut core::ffi::c_void) -> i32 {
17044    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5401, termios_p as i64)) as i32
17045}
17046
17047#[no_mangle]
17048pub unsafe extern "C" fn tcsetattr(fd: i32, optional_actions: i32, termios_p: *const core::ffi::c_void) -> i32 {
17049    let cmd = match optional_actions {
17050        0 => 0x5402,
17051        1 => 0x5403,
17052        2 => 0x5404,
17053        _ => 0x5402,
17054    };
17055    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, cmd, termios_p as i64)) as i32
17056}
17057
17058#[no_mangle]
17059pub unsafe extern "C" fn tcdrain(fd: i32) -> i32 {
17060    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5409, 1)) as i32
17061}
17062
17063#[no_mangle]
17064pub unsafe extern "C" fn tcflush(fd: i32, queue_selector: i32) -> i32 {
17065    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540B, queue_selector as i64)) as i32
17066}
17067
17068#[no_mangle]
17069pub unsafe extern "C" fn tcflow(fd: i32, action: i32) -> i32 {
17070    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540A, action as i64)) as i32
17071}
17072
17073#[no_mangle]
17074pub unsafe extern "C" fn tcsendbreak(fd: i32, duration: i32) -> i32 {
17075    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5425, duration as i64)) as i32
17076}
17077
17078#[no_mangle]
17079pub unsafe extern "C" fn tcgetsid(fd: i32) -> i32 {
17080    let mut sid: i32 = 0;
17081    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5429, &mut sid as *mut i32 as i64);
17082    if r < 0 { -1 } else { sid }
17083}
17084
17085#[no_mangle]
17086pub unsafe extern "C" fn tcgetpgrp(fd: i32) -> i32 {
17087    let mut pgrp: i32 = 0;
17088    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540F, &mut pgrp as *mut i32 as i64);
17089    if r < 0 { -1 } else { pgrp }
17090}
17091
17092#[no_mangle]
17093pub unsafe extern "C" fn tcsetpgrp(fd: i32, pgrp: i32) -> i32 {
17094    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5410, &pgrp as *const i32 as i64)) as i32
17095}
17096
17097// ============================================================
17098// Memory locking functions
17099// ============================================================
17100
17101// ============================================================
17102
17103// ============================================================
17104// POSIX message queue functions
17105// ============================================================
17106
17107#[no_mangle]
17108pub unsafe extern "C" fn mq_open(name: *const core::ffi::c_char, oflag: i32, mut args: ...) -> i32 {
17109    if name.is_null() { ERRNO!() = EINVAL; return -1; }
17110    let mut p = name as *const u8;
17111    if *p == b'/' { p = p.add(1); }
17112    let mut mode: u32 = 0;
17113    let mut attr: *const core::ffi::c_void = core::ptr::null();
17114    if oflag & 0o100 != 0 {
17115        mode = args.next_arg::<u32>();
17116        attr = args.next_arg::<*const core::ffi::c_void>();
17117    }
17118    syscall_ret(<Arch as Syscalls>::syscall4(
17119        sysno(240, 180),
17120        p as i64,
17121        oflag as i64,
17122        mode as i64,
17123        attr as i64,
17124    )) as i32
17125}
17126
17127#[no_mangle]
17128pub unsafe extern "C" fn mq_close(mqdes: i32) -> i32 {
17129    crate::close(mqdes as i32)
17130}
17131
17132#[no_mangle]
17133pub unsafe extern "C" fn mq_unlink(name: *const core::ffi::c_char) -> i32 {
17134    if name.is_null() { ERRNO!() = EINVAL; return -1; }
17135    let mut p = name as *const u8;
17136    if *p == b'/' { p = p.add(1); }
17137    let r = <Arch as Syscalls>::syscall1(sysno(241, 181), p as i64);
17138    if r < 0 {
17139        // The kernel reports EPERM for an unlink while the queue is open.
17140        let e = if (-r) as c_int == 1 { 13 } else { (-r) as c_int };
17141        ERRNO!() = e;
17142        -1
17143    } else {
17144        0
17145    }
17146}
17147
17148#[no_mangle]
17149pub unsafe extern "C" fn mq_send(mqdes: i32, msg_ptr: *const core::ffi::c_char, msg_len: usize, msg_prio: u32) -> i32 {
17150    mq_timedsend(mqdes, msg_ptr, msg_len, msg_prio, core::ptr::null())
17151}
17152
17153#[no_mangle]
17154pub unsafe extern "C" fn mq_receive(mqdes: i32, msg_ptr: *mut core::ffi::c_char, msg_len: usize, msg_prio: *mut u32) -> isize {
17155    mq_timedreceive(mqdes, msg_ptr, msg_len, msg_prio, core::ptr::null())
17156}
17157
17158#[no_mangle]
17159pub unsafe extern "C" fn mq_timedsend(
17160    mqdes: i32,
17161    msg_ptr: *const core::ffi::c_char,
17162    msg_len: usize,
17163    msg_prio: u32,
17164    abs_timeout: *const core::ffi::c_void,
17165) -> i32 {
17166    syscall_ret(<Arch as Syscalls>::syscall5(
17167        sysno(242, 182),
17168        mqdes as i64,
17169        msg_ptr as i64,
17170        msg_len as i64,
17171        msg_prio as i64,
17172        abs_timeout as i64,
17173    )) as i32
17174}
17175
17176#[no_mangle]
17177pub unsafe extern "C" fn mq_timedreceive(
17178    mqdes: i32,
17179    msg_ptr: *mut core::ffi::c_char,
17180    msg_len: usize,
17181    msg_prio: *mut u32,
17182    abs_timeout: *const core::ffi::c_void,
17183) -> isize {
17184    syscall_ret(<Arch as Syscalls>::syscall5(
17185        sysno(243, 183),
17186        mqdes as i64,
17187        msg_ptr as i64,
17188        msg_len as i64,
17189        msg_prio as i64,
17190        abs_timeout as i64,
17191    )) as isize
17192}
17193
17194#[repr(C)]
17195pub struct SigEventFull {
17196    sigev_value: usize,
17197    sigev_signo: i32,
17198    sigev_notify: i32,
17199    sigev_function: usize,
17200    sigev_attributes: usize,
17201    sigev_pad: [u8; 32],
17202}
17203
17204struct MqNotifyArgs {
17205    sem: sem_t,
17206    sock: i32,
17207    mqd: i32,
17208    err: i32,
17209    func: usize,
17210    value: usize,
17211}
17212
17213unsafe extern "C" fn mq_notify_thread(arg: *mut c_void) -> *mut c_void {
17214    let a = &mut *(arg as *mut MqNotifyArgs);
17215    let sock = a.sock;
17216    let mqd = a.mqd;
17217    let func = a.func;
17218    let value = a.value;
17219    let zeros = [0u8; 32];
17220    let sev2 = SigEventFull {
17221        sigev_value: zeros.as_ptr() as usize,
17222        sigev_signo: sock,
17223        sigev_notify: 2, // SIGEV_THREAD, consumed by the kernel as a netlink fd
17224        sigev_function: 0,
17225        sigev_attributes: 0,
17226        sigev_pad: [0; 32],
17227    };
17228    let r = <Arch as Syscalls>::syscall2(sysno(244, 184), mqd as i64, &sev2 as *const SigEventFull as i64);
17229    a.err = if r < 0 { (-r) as i32 } else { 0 };
17230    sem_post(&mut a.sem);
17231    if a.err != 0 { return core::ptr::null_mut(); }
17232    pthread_detach(pthread_self());
17233    let mut buf = [0u8; 32];
17234    let n = recv(sock, buf.as_mut_ptr() as *mut c_void, buf.len(), 0x4000 | 0x100);
17235    crate::close(sock);
17236    if n as usize == buf.len() && buf[buf.len() - 1] == 1 && func != 0 {
17237        let f: extern "C" fn(usize) = core::mem::transmute(func);
17238        f(value);
17239    }
17240    core::ptr::null_mut()
17241}
17242
17243#[no_mangle]
17244pub unsafe extern "C" fn mq_notify(mqdes: i32, sev: *const core::ffi::c_void) -> i32 {
17245    if sev.is_null() {
17246        return syscall_ret(<Arch as Syscalls>::syscall2(sysno(244, 184), mqdes as i64, 0)) as i32;
17247    }
17248    let ev = &*(sev as *const SigEventFull);
17249    if ev.sigev_notify != 2 {
17250        return syscall_ret(<Arch as Syscalls>::syscall2(sysno(244, 184), mqdes as i64, sev as i64)) as i32;
17251    }
17252
17253    // SIGEV_THREAD is emulated with a netlink socket and a helper thread,
17254    // matching musl. The kernel only deals with the socket.
17255    let sock = socket(16 /* AF_NETLINK */, 3 | 0x80000 /* SOCK_RAW|SOCK_CLOEXEC */, 0);
17256    if sock < 0 { return -1; }
17257    let mut a = MqNotifyArgs {
17258        sem: core::mem::zeroed(),
17259        sock,
17260        mqd: mqdes,
17261        err: 0,
17262        func: ev.sigev_function,
17263        value: ev.sigev_value,
17264    };
17265    sem_init(&mut a.sem, 0, 0);
17266
17267    let mut attr: pthread_attr_t = core::mem::zeroed();
17268    if ev.sigev_attributes != 0 {
17269        attr = core::ptr::read(ev.sigev_attributes as *const pthread_attr_t);
17270    } else {
17271        pthread_attr_init(&mut attr);
17272    }
17273    pthread_attr_setdetachstate(&mut attr, PTHREAD_CREATE_JOINABLE);
17274
17275    let mut all: SigSetT = 0;
17276    sigfillset(&mut all);
17277    let mut orig: SigSetT = 0;
17278    pthread_sigmask(0 /* SIG_BLOCK */, &all, &mut orig);
17279
17280    let mut td: PthreadT = 0;
17281    let r = pthread_create(&mut td, &attr, mq_notify_thread as *const () as usize, &mut a as *mut MqNotifyArgs as *mut c_void);
17282    pthread_sigmask(2 /* SIG_SETMASK */, &orig, core::ptr::null_mut());
17283    if r != 0 {
17284        crate::close(sock);
17285        ERRNO!() = 11;
17286        return -1;
17287    }
17288    sem_wait(&mut a.sem);
17289    sem_destroy(&mut a.sem);
17290    if a.err != 0 {
17291        crate::close(sock);
17292        pthread_join(td, core::ptr::null_mut());
17293        ERRNO!() = a.err;
17294        return -1;
17295    }
17296    0
17297}
17298
17299#[no_mangle]
17300pub unsafe extern "C" fn mq_getattr(mqdes: i32, attr: *mut core::ffi::c_void) -> i32 {
17301    mq_setattr(mqdes, core::ptr::null(), attr)
17302}
17303
17304#[no_mangle]
17305pub unsafe extern "C" fn mq_setattr(
17306    mqdes: i32,
17307    new: *const core::ffi::c_void,
17308    old: *mut core::ffi::c_void,
17309) -> i32 {
17310    syscall_ret(<Arch as Syscalls>::syscall3(
17311        sysno(245, 185),
17312        mqdes as i64,
17313        new as i64,
17314        old as i64,
17315    )) as i32
17316}
17317
17318// ============================================================
17319// pthread functions
17320// ============================================================
17321
17322#[no_mangle]
17323pub unsafe extern "C" fn pthread_getaffinity_np(thread: usize, cpusetsize: usize, cpuset: *mut u8) -> i32 {
17324    sched_getaffinity(thread as i32, cpusetsize, cpuset)
17325}
17326
17327#[no_mangle]
17328pub unsafe extern "C" fn pthread_setaffinity_np(thread: usize, cpusetsize: usize, cpuset: *const u8) -> i32 {
17329    sched_setaffinity(thread as i32, cpusetsize, cpuset)
17330}
17331
17332// ============================================================
17333// sched functions
17334// ============================================================
17335
17336#[no_mangle]
17337pub unsafe extern "C" fn sched_yield() -> i32 {
17338    syscall_ret(<Arch as Syscalls>::syscall0(sysno(24, 124))) as i32
17339}
17340
17341#[no_mangle]
17342pub unsafe extern "C" fn sched_get_priority_max(policy: i32) -> i32 {
17343    syscall_ret(<Arch as Syscalls>::syscall1(sysno(146, 125), policy as i64)) as i32
17344}
17345
17346#[no_mangle]
17347pub unsafe extern "C" fn sched_get_priority_min(policy: i32) -> i32 {
17348    syscall_ret(<Arch as Syscalls>::syscall1(sysno(147, 126), policy as i64)) as i32
17349}
17350
17351#[no_mangle]
17352pub unsafe extern "C" fn sched_getparam(pid: i32, param: *mut core::ffi::c_void) -> i32 {
17353    syscall_ret(<Arch as Syscalls>::syscall2(sysno(143, 121), pid as i64, param as i64)) as i32
17354}
17355
17356#[no_mangle]
17357pub unsafe extern "C" fn sched_setparam(pid: i32, param: *const core::ffi::c_void) -> i32 {
17358    syscall_ret(<Arch as Syscalls>::syscall2(sysno(142, 118), pid as i64, param as i64)) as i32
17359}
17360
17361#[no_mangle]
17362pub unsafe extern "C" fn sched_getscheduler(pid: i32) -> i32 {
17363    syscall_ret(<Arch as Syscalls>::syscall1(sysno(145, 120), pid as i64)) as i32
17364}
17365
17366#[no_mangle]
17367pub unsafe extern "C" fn sched_setscheduler(pid: i32, policy: i32, param: *const core::ffi::c_void) -> i32 {
17368    syscall_ret(<Arch as Syscalls>::syscall3(sysno(144, 119), pid as i64, policy as i64, param as i64)) as i32
17369}
17370
17371#[no_mangle]
17372pub unsafe extern "C" fn sched_setaffinity(pid: i32, cpusetsize: usize, cpuset: *const u8) -> i32 {
17373    syscall_ret(<Arch as Syscalls>::syscall3(sysno(203, 122), pid as i64, cpusetsize as i64, cpuset as i64)) as i32
17374}
17375
17376#[no_mangle]
17377pub unsafe extern "C" fn sched_getaffinity(pid: i32, cpusetsize: usize, cpuset: *mut u8) -> i32 {
17378    let r = <Arch as Syscalls>::syscall3(sysno(204, 123), pid as i64, cpusetsize as i64, cpuset as i64);
17379    if r < 0 {
17380        ERRNO!() = (-r) as c_int;
17381        return -1;
17382    }
17383    // The kernel returns the number of bytes copied, not 0.
17384    0
17385}
17386
17387#[cold]
17388unsafe fn sched_getcpu_syscall(cpu: *mut u32) -> i32 {
17389    let r = <Arch as Syscalls>::syscall3(sysno(309, 168), cpu as i64, 0, 0);
17390    if r == 0 {
17391        core::ptr::read_unaligned(cpu) as i32
17392    } else {
17393        syscall_ret(r) as i32
17394    }
17395}
17396
17397#[no_mangle]
17398pub unsafe extern "C" fn sched_getcpu() -> i32 {
17399    // Both the vDSO and the syscall fill the slot on success.  A 16-byte
17400    // scratch area keeps the write away from the return address; a 4-byte
17401    // slot overlaps the compiler's push and triggers a store-forwarding
17402    // stall on the vDSO write (measured ~2.5 ns).
17403    let mut cpu = core::mem::MaybeUninit::<[u64; 2]>::uninit();
17404    let cpu_ptr = cpu.as_mut_ptr() as *mut u32;
17405    if vdso_getcpu(cpu_ptr) {
17406        return core::ptr::read_unaligned(cpu_ptr) as i32;
17407    }
17408    sched_getcpu_syscall(cpu_ptr)
17409}
17410
17411#[no_mangle]
17412pub unsafe extern "C" fn sched_rr_get_interval(pid: i32, tp: *mut core::ffi::c_void) -> i32 {
17413    syscall_ret(<Arch as Syscalls>::syscall2(sysno(148, 127), pid as i64, tp as i64)) as i32
17414}
17415
17416// ============================================================
17417// timer/clock functions
17418// ============================================================
17419
17420#[no_mangle]
17421pub unsafe extern "C" fn timer_create(clockid: i32, sevp: *mut core::ffi::c_void, timerid: *mut i32) -> i32 {
17422    syscall_ret(<Arch as Syscalls>::syscall3(sysno(222, 107), clockid as i64, sevp as i64, timerid as i64)) as i32
17423}
17424
17425#[no_mangle]
17426pub unsafe extern "C" fn timer_delete(timerid: i32) -> i32 {
17427    syscall_ret(<Arch as Syscalls>::syscall1(sysno(226, 111), timerid as i64)) as i32
17428}
17429
17430#[no_mangle]
17431pub 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 {
17432    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
17433}
17434
17435#[no_mangle]
17436pub unsafe extern "C" fn timer_gettime(timerid: i32, curr_value: *mut core::ffi::c_void) -> i32 {
17437    syscall_ret(<Arch as Syscalls>::syscall2(sysno(224, 108), timerid as i64, curr_value as i64)) as i32
17438}
17439
17440#[no_mangle]
17441pub unsafe extern "C" fn timer_getoverrun(timerid: i32) -> i32 {
17442    syscall_ret(<Arch as Syscalls>::syscall1(sysno(225, 109), timerid as i64)) as i32
17443}
17444
17445#[no_mangle]
17446pub unsafe extern "C" fn clock_adjtime(_clockid: i32, buf: *mut core::ffi::c_void) -> i32 {
17447    syscall_ret(<Arch as Syscalls>::syscall2(SYS_ADJTIMEX, buf as i64, 0)) as i32
17448}
17449
17450#[no_mangle]
17451pub unsafe extern "C" fn clock_getcpuclockid(pid: i32, clockid: *mut i32) -> i32 {
17452    if clockid.is_null() { return EINVAL; }
17453    let id: i32 = ((-(pid as i64) - 1) * 8 + 2) as i32;
17454    let mut ts: timespec = core::mem::zeroed();
17455    let r = <Arch as Syscalls>::syscall2(SYS_CLOCK_GETRES, id as i64, &mut ts as *mut timespec as i64);
17456    if r < 0 {
17457        let e = (-r) as c_int;
17458        return if e == EINVAL { 3 } else { e };
17459    }
17460    *clockid = id;
17461    0
17462}
17463
17464// ============================================================
17465// String functions
17466// ============================================================
17467
17468#[no_mangle]
17469pub unsafe extern "C" fn strcoll(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> i32 {
17470    // ponytail: simplified collation - just strcmp
17471    let mut i = 0;
17472    loop {
17473        let c1 = *s1.add(i) as u8;
17474        let c2 = *s2.add(i) as u8;
17475        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
17476        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
17477        i += 1;
17478    }
17479}
17480
17481#[no_mangle]
17482pub unsafe extern "C" fn strxfrm(dest: *mut core::ffi::c_char, src: *const core::ffi::c_char, n: usize) -> usize {
17483    let mut i = 0;
17484    while i < n {
17485        let c = *src.add(i);
17486        *dest.add(i) = c;
17487        if c == 0 { break; }
17488        i += 1;
17489    }
17490    i
17491}
17492
17493// ============================================================
17494// Directory functions
17495// ============================================================
17496
17497#[no_mangle]
17498pub 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 {
17499    let dir = opendir(dirp);
17500    if dir.is_null() { return -1; }
17501    let mut count = 0;
17502    loop {
17503        let ent = readdir(dir);
17504        if ent.is_null() { break; }
17505        count += 1;
17506    }
17507    closedir(dir);
17508    count
17509}
17510
17511#[no_mangle]
17512pub unsafe extern "C" fn alphasort(a: *const *const core::ffi::c_void, b: *const *const core::ffi::c_void) -> i32 {
17513    let s1 = *a as *const core::ffi::c_char;
17514    let s2 = *b as *const core::ffi::c_char;
17515    crate::strcmp(s1 as *const u8, s2 as *const u8)
17516}
17517
17518#[no_mangle]
17519pub unsafe extern "C" fn versionsort(a: *const *const core::ffi::c_void, b: *const *const core::ffi::c_void) -> i32 {
17520    let s1 = *a as *const core::ffi::c_char;
17521    let s2 = *b as *const core::ffi::c_char;
17522    crate::strcmp(s1 as *const u8, s2 as *const u8)
17523}
17524
17525// ============================================================
17526
17527
17528// ============================================================
17529// err functions
17530// ============================================================
17531
17532unsafe fn vwarn_impl(fmt: *const c_char, ap: VaList, with_errno: bool) {
17533    let mut buf = [0 as c_char; 1024];
17534    let n = vsnprintf(buf.as_mut_ptr(), buf.len(), fmt, ap);
17535    if n > 0 {
17536        let l = core::cmp::min(n as usize, buf.len() - 1);
17537        crate::write(2, buf.as_ptr() as *const c_void, l);
17538    }
17539    if with_errno {
17540        let e = ERRNO!();
17541        crate::write(2, b": ".as_ptr() as *const c_void, 2);
17542        let msg = strerror(e);
17543        crate::write(2, msg as *const c_void, crate::strlen(msg));
17544    }
17545    crate::write(2, b"\n".as_ptr() as *const c_void, 1);
17546}
17547
17548#[no_mangle]
17549pub unsafe extern "C" fn verr(eval: c_int, fmt: *const c_char, ap: VaList) {
17550    vwarn_impl(fmt, ap, true);
17551    crate::exit(eval);
17552}
17553
17554#[no_mangle]
17555pub unsafe extern "C" fn verrx(eval: c_int, fmt: *const c_char, ap: VaList) {
17556    vwarn_impl(fmt, ap, false);
17557    crate::exit(eval);
17558}
17559
17560#[no_mangle]
17561pub unsafe extern "C" fn vwarn(fmt: *const c_char, ap: VaList) {
17562    vwarn_impl(fmt, ap, true);
17563}
17564
17565#[no_mangle]
17566pub unsafe extern "C" fn vwarnx(fmt: *const c_char, ap: VaList) {
17567    vwarn_impl(fmt, ap, false);
17568}
17569
17570#[no_mangle]
17571pub unsafe extern "C" fn err(eval: c_int, fmt: *const c_char, args: ...) {
17572    verr(eval, fmt, args);
17573}
17574
17575#[no_mangle]
17576pub unsafe extern "C" fn errx(eval: c_int, fmt: *const c_char, args: ...) {
17577    verrx(eval, fmt, args);
17578}
17579
17580#[no_mangle]
17581pub unsafe extern "C" fn warn(fmt: *const c_char, args: ...) {
17582    vwarn(fmt, args);
17583}
17584
17585#[no_mangle]
17586pub unsafe extern "C" fn warnx(fmt: *const c_char, args: ...) {
17587    vwarnx(fmt, args);
17588}
17589
17590// ============================================================
17591// ecvt functions
17592// ============================================================
17593
17594#[no_mangle]
17595pub unsafe extern "C" fn ecvt(value: f64, ndigit: i32, decpt: *mut i32, sign: *mut i32) -> *mut core::ffi::c_char {
17596    static mut BUF: [core::ffi::c_char; 80] = [0; 80];
17597    if value < 0.0 { *sign = 1; } else { *sign = 0; }
17598    let v = if value < 0.0 { -value } else { value };
17599    if v == 0.0 { *decpt = 0; BUF[0] = 0; return BUF.as_mut_ptr(); }
17600    let mut d = 0i32;
17601    let mut tmp = v;
17602    while tmp >= 10.0 { tmp /= 10.0; d += 1; }
17603    while tmp < 1.0 { tmp *= 10.0; d -= 1; }
17604    *decpt = d + 1;
17605    let mut i = 0;
17606    let mut val = tmp;
17607    while i < ndigit as usize && i < 79 {
17608        let digit = val as i32;
17609        BUF[i] = (b'0' + digit as u8) as c_char;
17610        val = (val - digit as f64) * 10.0;
17611        i += 1;
17612    }
17613    BUF[i] = 0;
17614    BUF.as_mut_ptr()
17615}
17616
17617#[no_mangle]
17618pub unsafe extern "C" fn fcvt(value: f64, ndigit: i32, decpt: *mut i32, sign: *mut i32) -> *mut core::ffi::c_char {
17619    static mut BUF: [core::ffi::c_char; 80] = [0; 80];
17620    if value < 0.0 { *sign = 1; } else { *sign = 0; }
17621    let v = if value < 0.0 { -value } else { value };
17622    if v == 0.0 { *decpt = 0; BUF[0] = 0; return BUF.as_mut_ptr(); }
17623    let mut d = 0i32;
17624    let mut tmp = v;
17625    while tmp >= 10.0 { tmp /= 10.0; d += 1; }
17626    while tmp < 1.0 { tmp *= 10.0; d -= 1; }
17627    *decpt = d + 1;
17628    let mut val = tmp;
17629    let mut i = 0;
17630    while i < (*decpt) as usize && i < 79 {
17631        let digit = val as i32;
17632        BUF[i] = (b'0' + digit as u8) as c_char;
17633        val = (val - digit as f64) * 10.0;
17634        i += 1;
17635    }
17636    if ndigit > 0 && i < 79 {
17637        BUF[i] = '.' as c_char;
17638        i += 1;
17639        let mut frac = val;
17640        let mut j = 0;
17641        while j < ndigit as usize && i < 79 {
17642            let digit = frac as i32;
17643            BUF[i] = (b'0' + digit as u8) as c_char;
17644            frac = (frac - digit as f64) * 10.0;
17645            i += 1;
17646            j += 1;
17647        }
17648    }
17649    BUF[i] = 0;
17650    BUF.as_mut_ptr()
17651}
17652
17653#[no_mangle]
17654pub unsafe extern "C" fn gcvt(value: f64, _ndigit: i32, buf: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
17655    // Simple implementation - convert to string
17656    if value == 0.0 {
17657        *buf = '0' as c_char;
17658        *buf.add(1) = 0;
17659        return buf;
17660    }
17661    let mut i = 0;
17662    let v = if value < 0.0 { *buf = '-' as c_char; i = 1; -value } else { value };
17663    // Integer part
17664    let mut int_part = v as i64;
17665    let mut digits = [0u8; 32];
17666    let mut di = 0;
17667    if int_part == 0 {
17668        digits[0] = 0;
17669        di = 1;
17670    } else {
17671        while int_part > 0 && di < 32 {
17672            digits[di] = (int_part % 10) as u8;
17673            int_part /= 10;
17674            di += 1;
17675        }
17676    }
17677    while di > 0 && i < 79 {
17678        di -= 1;
17679        *buf.add(i) = (b'0' + digits[di]) as c_char;
17680        i += 1;
17681    }
17682    *buf.add(i) = 0;
17683    buf
17684}
17685
17686// ============================================================
17687// usershell functions
17688// ============================================================
17689
17690static mut SHELLS: [*const core::ffi::c_char; 3] = [
17691    b"/bin/sh\0".as_ptr() as *const core::ffi::c_char,
17692    b"/bin/bash\0".as_ptr() as *const core::ffi::c_char,
17693    core::ptr::null(),
17694];
17695static mut SHELL_IDX: usize = 0;
17696
17697#[no_mangle]
17698pub unsafe extern "C" fn getusershell() -> *mut core::ffi::c_char {
17699    let s = SHELLS[SHELL_IDX];
17700    if s.is_null() {
17701        SHELL_IDX = 0;
17702        return core::ptr::null_mut();
17703    }
17704    SHELL_IDX += 1;
17705    s as *mut core::ffi::c_char
17706}
17707
17708#[no_mangle]
17709pub unsafe extern "C" fn setusershell() {
17710    SHELL_IDX = 0;
17711}
17712
17713#[no_mangle]
17714pub unsafe extern "C" fn endusershell() {
17715    SHELL_IDX = 0;
17716}
17717
17718// ============================================================
17719// ether functions
17720// ============================================================
17721
17722#[no_mangle]
17723pub unsafe extern "C" fn ether_aton(s: *const core::ffi::c_char) -> *mut u8 {
17724    static mut EA: [u8; 6] = [0; 6];
17725    if ether_aton_r(s, EA.as_mut_ptr()).is_null() { core::ptr::null_mut() } else { EA.as_mut_ptr() }
17726}
17727
17728#[no_mangle]
17729pub unsafe extern "C" fn ether_aton_r(s: *const core::ffi::c_char, ea: *mut u8) -> *mut u8 {
17730    if ea.is_null() { return core::ptr::null_mut(); }
17731    let mut i = 0;
17732    let mut j = 0;
17733    let mut val: u32 = 0;
17734    let mut digits = 0;
17735    while *s.add(i) != 0 && j < 6 {
17736        let c = *s.add(i);
17737        if c == ':' as c_char {
17738            if digits == 0 { return core::ptr::null_mut(); }
17739            *ea.add(j) = val as u8;
17740            j += 1;
17741            val = 0;
17742            digits = 0;
17743        } 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) {
17744            let d = if c >= '0' as c_char && c <= '9' as c_char { (c - '0' as c_char) as u32 }
17745                   else if c >= 'a' as c_char { (c - 'a' as c_char + 10) as u32 }
17746                   else { (c - 'A' as c_char + 10) as u32 };
17747            val = val * 16 + d;
17748            if val > 255 { return core::ptr::null_mut(); }
17749            digits += 1;
17750            if digits > 2 { return core::ptr::null_mut(); }
17751        } else {
17752            return core::ptr::null_mut();
17753        }
17754        i += 1;
17755    }
17756    if digits == 0 || j != 5 { return core::ptr::null_mut(); }
17757    *ea.add(j) = val as u8;
17758    ea
17759}
17760
17761#[no_mangle]
17762pub unsafe extern "C" fn ether_ntoa(ea: *const u8) -> *mut core::ffi::c_char {
17763    static mut BUF: [core::ffi::c_char; 18] = [0; 18];
17764    ether_ntoa_r(ea, BUF.as_mut_ptr());
17765    BUF.as_mut_ptr()
17766}
17767
17768#[no_mangle]
17769pub unsafe extern "C" fn ether_ntoa_r(ea: *const u8, buf: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
17770    let a = *ea.add(0); let b = *ea.add(1); let c = *ea.add(2);
17771    let d = *ea.add(3); let e = *ea.add(4); let f = *ea.add(5);
17772    let hex = b"0123456789abcdef\0".as_ptr() as *const u8;
17773    let mut i = 0;
17774    *buf.add(i) = *hex.add((a >> 4) as usize) as c_char; i += 1;
17775    *buf.add(i) = *hex.add((a & 0xf) as usize) as c_char; i += 1;
17776    *buf.add(i) = ':' as c_char; i += 1;
17777    *buf.add(i) = *hex.add((b >> 4) as usize) as c_char; i += 1;
17778    *buf.add(i) = *hex.add((b & 0xf) as usize) as c_char; i += 1;
17779    *buf.add(i) = ':' as c_char; i += 1;
17780    *buf.add(i) = *hex.add((c >> 4) as usize) as c_char; i += 1;
17781    *buf.add(i) = *hex.add((c & 0xf) as usize) as c_char; i += 1;
17782    *buf.add(i) = ':' as c_char; i += 1;
17783    *buf.add(i) = *hex.add((d >> 4) as usize) as c_char; i += 1;
17784    *buf.add(i) = *hex.add((d & 0xf) as usize) as c_char; i += 1;
17785    *buf.add(i) = ':' as c_char; i += 1;
17786    *buf.add(i) = *hex.add((e >> 4) as usize) as c_char; i += 1;
17787    *buf.add(i) = *hex.add((e & 0xf) as usize) as c_char; i += 1;
17788    *buf.add(i) = ':' as c_char; i += 1;
17789    *buf.add(i) = *hex.add((f >> 4) as usize) as c_char; i += 1;
17790    *buf.add(i) = *hex.add((f & 0xf) as usize) as c_char; i += 1;
17791    *buf.add(i) = 0;
17792    buf
17793}
17794
17795// ============================================================
17796// utmpx functions
17797// ============================================================
17798
17799#[no_mangle]
17800pub unsafe extern "C" fn getutxent() -> *mut core::ffi::c_void {
17801    getutent()
17802}
17803
17804#[no_mangle]
17805pub unsafe extern "C" fn getutxid(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
17806    getutid(ut)
17807}
17808
17809#[no_mangle]
17810pub unsafe extern "C" fn getutxline(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
17811    getutline(ut)
17812}
17813
17814#[no_mangle]
17815pub unsafe extern "C" fn pututxline(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
17816    pututline(ut)
17817}
17818
17819#[no_mangle]
17820pub unsafe extern "C" fn setutxent() {
17821    setutent()
17822}
17823
17824#[no_mangle]
17825pub unsafe extern "C" fn endutxent() {
17826    endutent()
17827}
17828
17829// ============================================================
17830// exec functions
17831// ============================================================
17832
17833#[no_mangle]
17834pub unsafe extern "C" fn execv(path: *const core::ffi::c_char, argv: *const *const core::ffi::c_char) -> i32 {
17835    crate::execve(path, argv, __environ as *const *const core::ffi::c_char)
17836}
17837
17838#[no_mangle]
17839pub unsafe extern "C" fn execlp(file: *const core::ffi::c_char, _args: ...) -> i32 {
17840    let mut cap = 16usize;
17841    let mut argv = malloc(cap * core::mem::size_of::<*const core::ffi::c_char>()) as *mut *const core::ffi::c_char;
17842    if argv.is_null() { ERRNO!() = ENOMEM; return -1; }
17843    let mut i = 0usize;
17844    let mut args = _args;
17845    loop {
17846        let arg = args.next_arg::<*const core::ffi::c_char>();
17847        if arg.is_null() { break; }
17848        if i + 1 >= cap {
17849            cap = match cap.checked_mul(2) { Some(v) => v, None => { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; } };
17850            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;
17851            if grown.is_null() { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; }
17852            argv = grown;
17853        }
17854        *argv.add(i) = arg;
17855        i += 1;
17856    }
17857    *argv.add(i) = core::ptr::null();
17858    let r = execvp(file, argv);
17859    free(argv as *mut c_void);
17860    r
17861}
17862
17863#[no_mangle]
17864pub unsafe extern "C" fn execvp(file: *const core::ffi::c_char, argv: *const *const core::ffi::c_char) -> i32 {
17865    execvpe(file, argv, __environ as *const *const core::ffi::c_char)
17866}
17867
17868#[no_mangle]
17869pub unsafe extern "C" fn fexecve(fd: i32, argv: *const *const core::ffi::c_char, envp: *const *const core::ffi::c_char) -> i32 {
17870    // Read /proc/self/fd/N to get the path
17871    let mut path: [core::ffi::c_char; 64] = [0; 64];
17872    let mut i = 0;
17873    let src = b"/proc/self/fd/\0".as_ptr() as *const core::ffi::c_char;
17874    while i < 63 && *src.add(i) != 0 { path[i] = *src.add(i); i += 1; }
17875    let mut n = fd as usize;
17876    if n == 0 { path[i] = '0' as c_char; i += 1; }
17877    while n > 0 && i < 63 {
17878        path[i] = (b'0' + (n % 10) as u8) as c_char;
17879        n /= 10;
17880        i += 1;
17881    }
17882    path[i] = 0;
17883    crate::execve(path.as_ptr(), argv, envp)
17884}
17885
17886// ============================================================
17887// conf functions
17888// ============================================================
17889
17890#[no_mangle]
17891pub unsafe extern "C" fn confstr(name: i32, buf: *mut core::ffi::c_char, len: usize) -> usize {
17892    // _CS_PATH is the only value with content; the POSIX_V6/V7 option
17893    // strings are empty on Linux. Truncation follows snprintf semantics.
17894    let value: &[u8] = if name == 0 {
17895        b"/bin:/usr/bin"
17896    } else if (1..=37).contains(&name) {
17897        b""
17898    } else {
17899        ERRNO!() = EINVAL;
17900        return 0;
17901    };
17902    let need = value.len() + 1;
17903    if !buf.is_null() && len > 0 {
17904        let n = core::cmp::min(value.len(), len - 1);
17905        core::ptr::copy_nonoverlapping(value.as_ptr(), buf as *mut u8, n);
17906        *buf.add(n) = 0;
17907    }
17908    need
17909}
17910
17911#[no_mangle]
17912pub unsafe extern "C" fn pathconf(_path: *const core::ffi::c_char, name: i32) -> i64 {
17913    // Return default values
17914    match name {
17915        0 => 4096, // _PC_LINK_MAX
17916        1 => 255,  // _PC_MAX_CANON
17917        2 => 255,  // _PC_MAX_INPUT
17918        3 => 255,  // _PC_NAME_MAX
17919        4 => 4096, // _PC_PATH_MAX
17920        5 => 4096, // _PC_PIPE_BUF
17921        6 => 1,    // _PC_CHOWN_RESTRICTED
17922        7 => 0,    // _PC_NO_TRUNC
17923        8 => 0,    // _PC_VDISABLE
17924        _ => -1,
17925    }
17926}
17927
17928#[no_mangle]
17929pub unsafe extern "C" fn fpathconf(_fd: i32, name: i32) -> i64 {
17930    // Return default values
17931    match name {
17932        0 => 4096, // _PC_LINK_MAX
17933        1 => 255,  // _PC_MAX_CANON
17934        2 => 255,  // _PC_MAX_INPUT
17935        3 => 255,  // _PC_NAME_MAX
17936        4 => 4096, // _PC_PATH_MAX
17937        5 => 4096, // _PC_PIPE_BUF
17938        6 => 1,    // _PC_CHOWN_RESTRICTED
17939        7 => 0,    // _PC_NO_TRUNC
17940        8 => 0,    // _PC_VDISABLE
17941        _ => -1,
17942    }
17943}
17944
17945// ============================================================
17946// exp10 functions
17947// ============================================================
17948
17949#[no_mangle]
17950pub unsafe extern "C" fn exp10(x: f64) -> f64 {
17951    libm::pow(10.0, x)
17952}
17953
17954#[no_mangle]
17955pub unsafe extern "C" fn exp10f(x: f32) -> f32 {
17956    libm::powf(10.0, x)
17957}
17958
17959// ============================================================
17960// memory functions
17961// ============================================================
17962
17963#[no_mangle]
17964pub unsafe extern "C" fn explicit_bzero(s: *mut u8, n: usize) {
17965    core::ptr::write_bytes(s, 0, n);
17966    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
17967}
17968
17969#[no_mangle]
17970pub unsafe extern "C" fn memccpy(dest: *mut u8, src: *const u8, c: i32, n: usize) -> *mut u8 {
17971    let mut i = 0;
17972    while i < n {
17973        let byte = *src.add(i);
17974        *dest.add(i) = byte;
17975        if byte == c as u8 {
17976            return dest.add(i + 1);
17977        }
17978        i += 1;
17979    }
17980    core::ptr::null_mut()
17981}
17982
17983// ============================================================
17984// *at functions
17985// ============================================================
17986
17987#[no_mangle]
17988pub unsafe extern "C" fn faccessat(dirfd: i32, pathname: *const core::ffi::c_char, mode: i32, flags: i32) -> i32 {
17989    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FACCESSAT, dirfd as i64, pathname as i64, mode as i64, flags as i64)) as i32
17990}
17991
17992#[no_mangle]
17993pub unsafe extern "C" fn fchmodat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32, flags: i32) -> i32 {
17994    if flags == 0 {
17995        return syscall_ret(<Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, pathname as i64, mode as i64, 0)) as i32;
17996    }
17997    if flags != 0x100 {
17998        // Only AT_SYMLINK_NOFOLLOW is defined for fchmodat.
17999        ERRNO!() = EINVAL;
18000        return -1;
18001    }
18002    syscall_ret(<Arch as Syscalls>::syscall4(sysno(452, 452), dirfd as i64, pathname as i64, mode as i64, flags as i64)) as i32
18003}
18004
18005#[no_mangle]
18006pub unsafe extern "C" fn fchownat(dirfd: i32, pathname: *const core::ffi::c_char, uid: u32, gid: u32, flags: i32) -> i32 {
18007    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
18008}
18009
18010#[no_mangle]
18011pub unsafe extern "C" fn linkat(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char, flags: i32) -> i32 {
18012    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
18013}
18014
18015#[no_mangle]
18016pub unsafe extern "C" fn mkdirat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18017    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, pathname as i64, mode as i64)) as i32
18018}
18019
18020#[no_mangle]
18021pub unsafe extern "C" fn mkfifoat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18022    mknodat(dirfd, pathname, mode | 0o010000, 0)
18023}
18024
18025#[no_mangle]
18026pub unsafe extern "C" fn mknodat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
18027    syscall_ret(<Arch as Syscalls>::syscall4(sysno(259, 33), dirfd as i64, pathname as i64, mode as i64, dev as i64)) as i32
18028}
18029
18030#[no_mangle]
18031pub unsafe extern "C" fn readlinkat(dirfd: i32, pathname: *const core::ffi::c_char, buf: *mut core::ffi::c_char, bufsiz: usize) -> isize {
18032    syscall_ret(<Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, pathname as i64, buf as i64, bufsiz as i64)) as isize
18033}
18034
18035#[no_mangle]
18036pub unsafe extern "C" fn renameat(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char) -> i32 {
18037    syscall_ret(<Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, 0)) as i32
18038}
18039
18040#[no_mangle]
18041pub unsafe extern "C" fn renameat2(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char, flags: u32) -> i32 {
18042    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
18043}
18044
18045#[no_mangle]
18046pub unsafe extern "C" fn symlinkat(target: *const core::ffi::c_char, newdirfd: i32, linkpath: *const core::ffi::c_char) -> i32 {
18047    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)) as i32
18048}
18049
18050#[no_mangle]
18051pub unsafe extern "C" fn unlinkat(dirfd: i32, pathname: *const core::ffi::c_char, flags: i32) -> i32 {
18052    syscall_ret(<Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, pathname as i64, flags as i64)) as i32
18053}
18054
18055#[no_mangle]
18056pub unsafe extern "C" fn utimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
18057    utimensat(AT_FDCWD, filename, times as *const timespec, 0)
18058}
18059
18060#[no_mangle]
18061pub unsafe extern "C" fn futimes(fd: i32, times: *const core::ffi::c_void) -> i32 {
18062    utimensat(fd, core::ptr::null(), times as *const timespec, 0)
18063}
18064
18065// ============================================================
18066// inotify functions
18067// ============================================================
18068
18069#[no_mangle]
18070pub unsafe extern "C" fn inotify_init() -> i32 {
18071    syscall_ret(<Arch as Syscalls>::syscall1(sysno(253, 26), 0)) as i32
18072}
18073
18074#[no_mangle]
18075pub unsafe extern "C" fn inotify_init1(flags: i32) -> i32 {
18076    syscall_ret(<Arch as Syscalls>::syscall1(sysno(294, 26), flags as i64)) as i32
18077}
18078
18079#[no_mangle]
18080pub unsafe extern "C" fn inotify_add_watch(fd: i32, pathname: *const core::ffi::c_char, mask: u32) -> i32 {
18081    syscall_ret(<Arch as Syscalls>::syscall3(sysno(254, 27), fd as i64, pathname as i64, mask as i64)) as i32
18082}
18083
18084#[no_mangle]
18085pub unsafe extern "C" fn inotify_rm_watch(fd: i32, wd: i32) -> i32 {
18086    syscall_ret(<Arch as Syscalls>::syscall2(sysno(255, 28), fd as i64, wd as i64)) as i32
18087}
18088
18089#[no_mangle]
18090pub unsafe extern "C" fn fanotify_init(flags: i32, event_f_flags: i32) -> i32 {
18091    syscall_ret(<Arch as Syscalls>::syscall2(sysno(300, 262), flags as i64, event_f_flags as i64)) as i32
18092}
18093
18094#[no_mangle]
18095pub unsafe extern "C" fn fanotify_mark(fd: i32, flags: i32, mask: u64, dirfd: i32, pathname: *const core::ffi::c_char) -> i32 {
18096    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
18097}
18098
18099// ============================================================
18100// ffs functions
18101// ============================================================
18102
18103#[no_mangle]
18104pub unsafe extern "C" fn ffs(x: i32) -> i32 {
18105    if x == 0 { return 0; }
18106    x.trailing_zeros() as i32 + 1
18107}
18108
18109#[no_mangle]
18110pub unsafe extern "C" fn ffsl(x: i64) -> i32 {
18111    if x == 0 { return 0; }
18112    x.trailing_zeros() as i32 + 1
18113}
18114
18115#[no_mangle]
18116pub unsafe extern "C" fn ffsll(x: i64) -> i32 {
18117    if x == 0 { return 0; }
18118    x.trailing_zeros() as i32 + 1
18119}
18120
18121// ============================================================
18122// More system functions
18123// ============================================================
18124
18125#[no_mangle]
18126pub unsafe extern "C" fn fchdir(fd: i32) -> i32 {
18127    syscall_ret(<Arch as Syscalls>::syscall1(SYS_FCHDIR, fd as i64)) as i32
18128}
18129
18130#[no_mangle]
18131pub unsafe extern "C" fn fchown(fd: i32, uid: u32, gid: u32) -> i32 {
18132    syscall_ret(<Arch as Syscalls>::syscall3(SYS_FCHOWN, fd as i64, uid as i64, gid as i64)) as i32
18133}
18134
18135#[no_mangle]
18136pub unsafe extern "C" fn fdopendir(fd: i32) -> *mut core::ffi::c_void {
18137    if fd < 0 { ERRNO!() = 9; return core::ptr::null_mut(); }
18138    dir_stream_new(fd)
18139}
18140
18141#[no_mangle]
18142pub unsafe extern "C" fn getdtablesize() -> i32 {
18143    let mut rlim: Rlimit = core::mem::zeroed();
18144    if getrlimit(RLIMIT_NOFILE, &mut rlim) == 0 {
18145        rlim.rlim_cur as i32
18146    } else {
18147        1024
18148    }
18149}
18150
18151#[no_mangle]
18152pub unsafe extern "C" fn getentropy(buf: *mut u8, buflen: usize) -> i32 {
18153    if buflen > 256 {
18154        ERRNO!() = EIO_VAL;
18155        return -1;
18156    }
18157    let mut pos = buf;
18158    let mut left = buflen;
18159    while left > 0 {
18160        let r = getrandom(pos, left, 0);
18161        if r < 0 {
18162            if ERRNO!() == EINTR_VAL {
18163                continue;
18164            }
18165            return -1;
18166        }
18167        pos = pos.add(r as usize);
18168        left -= r as usize;
18169    }
18170    0
18171}
18172
18173#[no_mangle]
18174pub unsafe extern "C" fn getrandom(buf: *mut u8, buflen: usize, flags: u32) -> isize {
18175    if let Some(r) = vgetrandom(buf, buflen, flags) {
18176        return if r < 0 {
18177            ERRNO!() = (-r) as c_int;
18178            -1
18179        } else {
18180            r
18181        };
18182    }
18183    let r = <Arch as Syscalls>::syscall3(sysno(318, 278), buf as i64, buflen as i64, flags as i64);
18184    if r < 0 {
18185        ERRNO!() = (-r) as c_int;
18186        -1
18187    } else {
18188        r as isize
18189    }
18190}
18191
18192#[no_mangle]
18193pub unsafe extern "C" fn killpg(pgrp: i32, sig: i32) -> i32 {
18194    syscall_ret(<Arch as Syscalls>::syscall2(SYS_KILL, -pgrp as i64, sig as i64)) as i32
18195}
18196
18197#[no_mangle]
18198pub unsafe extern "C" fn mkfifo(pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18199    mknod(pathname, 0o010000 | mode, 0)
18200}
18201
18202// ============================================================
18203// Memory allocation functions
18204// ============================================================
18205
18206#[no_mangle]
18207pub unsafe extern "C" fn aligned_alloc(alignment: usize, size: usize) -> *mut core::ffi::c_void {
18208    alloc_aligned_impl(alignment, size) as *mut core::ffi::c_void
18209}
18210
18211#[no_mangle]
18212pub unsafe extern "C" fn memalign(alignment: usize, size: usize) -> *mut core::ffi::c_void {
18213    alloc_aligned_impl(alignment, size) as *mut core::ffi::c_void
18214}
18215
18216#[no_mangle]
18217pub unsafe extern "C" fn posix_memalign(memptr: *mut *mut core::ffi::c_void, alignment: usize, size: usize) -> i32 {
18218    if memptr.is_null() { return EINVAL; }
18219    if alignment < core::mem::size_of::<*mut core::ffi::c_void>() || !alignment.is_power_of_two() {
18220        return EINVAL;
18221    }
18222    let p = alloc_aligned_impl(alignment, size);
18223    if p.is_null() { return ENOMEM; }
18224    *memptr = p as *mut core::ffi::c_void;
18225    0
18226}
18227
18228#[no_mangle]
18229pub unsafe extern "C" fn valloc(size: usize) -> *mut core::ffi::c_void {
18230    alloc_aligned_impl(PAGE, size) as *mut core::ffi::c_void
18231}
18232
18233// ============================================================
18234// glob functions
18235// ============================================================
18236
18237// ============================================================
18238// wordexp functions
18239// ============================================================
18240
18241// ============================================================
18242// gettext functions
18243// ============================================================
18244
18245#[no_mangle]
18246pub unsafe extern "C" fn gettext(msgid: *const core::ffi::c_char) -> *const core::ffi::c_char {
18247    msgid
18248}
18249
18250#[no_mangle]
18251pub unsafe extern "C" fn dgettext(_domainname: *const core::ffi::c_char, msgid: *const core::ffi::c_char) -> *const core::ffi::c_char {
18252    msgid
18253}
18254
18255#[no_mangle]
18256pub unsafe extern "C" fn dcgettext(_domainname: *const core::ffi::c_char, msgid: *const core::ffi::c_char, _category: i32) -> *const core::ffi::c_char {
18257    msgid
18258}
18259
18260#[no_mangle]
18261pub unsafe extern "C" fn ngettext(msgid1: *const core::ffi::c_char, msgid2: *const core::ffi::c_char, n: u64) -> *const core::ffi::c_char {
18262    if n == 1 { msgid1 } else { msgid2 }
18263}
18264
18265#[no_mangle]
18266pub 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 {
18267    if n == 1 { msgid1 } else { msgid2 }
18268}
18269
18270#[no_mangle]
18271pub 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 {
18272    if n == 1 { msgid1 } else { msgid2 }
18273}
18274
18275#[no_mangle]
18276pub unsafe extern "C" fn textdomain(domainname: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18277    static mut DOMAIN: [core::ffi::c_char; 256] = [0; 256];
18278    if domainname.is_null() { return DOMAIN.as_mut_ptr(); }
18279    let mut i = 0;
18280    while i < 255 && *domainname.add(i) != 0 {
18281        DOMAIN[i] = *domainname.add(i);
18282        i += 1;
18283    }
18284    DOMAIN[i] = 0;
18285    DOMAIN.as_mut_ptr()
18286}
18287
18288#[no_mangle]
18289pub unsafe extern "C" fn bindtextdomain(_domainname: *const core::ffi::c_char, dirname: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18290    dirname as *mut core::ffi::c_char
18291}
18292
18293#[no_mangle]
18294pub unsafe extern "C" fn bind_textdomain_codeset(_domainname: *const core::ffi::c_char, codeset: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18295    codeset as *mut core::ffi::c_char
18296}
18297
18298// ============================================================
18299// Wide string functions
18300// ============================================================
18301
18302#[no_mangle]
18303pub unsafe extern "C" fn wmemcpy(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18304    let mut i = 0;
18305    while i < n {
18306        *dest.add(i) = *src.add(i);
18307        i += 1;
18308    }
18309    dest
18310}
18311
18312#[no_mangle]
18313pub unsafe extern "C" fn wmemmove(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18314    if dest as usize <= src as usize {
18315        let mut i = 0;
18316        while i < n {
18317            *dest.add(i) = *src.add(i);
18318            i += 1;
18319        }
18320    } else {
18321        let mut i = n;
18322        while i > 0 {
18323            i -= 1;
18324            *dest.add(i) = *src.add(i);
18325        }
18326    }
18327    dest
18328}
18329
18330#[no_mangle]
18331pub unsafe extern "C" fn wmemset(dest: *mut u32, c: u32, n: usize) -> *mut u32 {
18332    let mut i = 0;
18333    while i < n {
18334        *dest.add(i) = c;
18335        i += 1;
18336    }
18337    dest
18338}
18339
18340#[no_mangle]
18341pub unsafe extern "C" fn wmemcmp(s1: *const u32, s2: *const u32, n: usize) -> i32 {
18342    let mut i = 0;
18343    while i < n {
18344        let c1 = *s1.add(i);
18345        let c2 = *s2.add(i);
18346        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
18347        i += 1;
18348    }
18349    0
18350}
18351
18352#[no_mangle]
18353pub unsafe extern "C" fn wmemchr(s: *const u32, c: u32, n: usize) -> *mut u32 {
18354    let mut i = 0;
18355    while i < n {
18356        if *s.add(i) == c { return s.add(i) as *mut u32; }
18357        i += 1;
18358    }
18359    core::ptr::null_mut()
18360}
18361
18362#[no_mangle]
18363pub unsafe extern "C" fn wcpcpy(dest: *mut u32, src: *const u32) -> *mut u32 {
18364    let mut i = 0;
18365    loop {
18366        let c = *src.add(i);
18367        *dest.add(i) = c;
18368        if c == 0 { return dest.add(i); }
18369        i += 1;
18370    }
18371}
18372
18373#[no_mangle]
18374pub unsafe extern "C" fn wcpncpy(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18375    let mut i = 0;
18376    while i < n {
18377        let c = *src.add(i);
18378        *dest.add(i) = c;
18379        if c == 0 { return dest.add(i); }
18380        i += 1;
18381    }
18382    dest.add(n)
18383}
18384
18385#[no_mangle]
18386pub unsafe extern "C" fn wprintf(fmt: *const wchar_t, args: ...) -> c_int {
18387    vfwprintf(stdout, fmt, args)
18388}
18389
18390#[no_mangle]
18391pub unsafe extern "C" fn vwprintf(fmt: *const wchar_t, ap: core::ffi::VaList) -> c_int {
18392    vfwprintf(stdout, fmt, ap)
18393}
18394
18395// ============================================================
18396// C32 functions
18397// ============================================================
18398
18399#[no_mangle]
18400pub unsafe extern "C" fn c16rtomb(s: *mut u8, c16: u16, ps: *mut core::ffi::c_void) -> usize {
18401    // UTF-16 to UTF-8, with surrogate pairs tracked in the mbstate.
18402    let state = ps as *mut u32;
18403    let saved: u32 = if state.is_null() { 0 } else { *state };
18404    if s.is_null() {
18405        if !state.is_null() { *state = 0; }
18406        return 1;
18407    }
18408    let cp: u32;
18409    if saved != 0 {
18410        if c16 < 0xdc00 || c16 > 0xdfff {
18411            if !state.is_null() { *state = 0; }
18412            ERRNO!() = EILSEQ;
18413            return !0usize;
18414        }
18415        cp = 0x10000 + (((saved - 0xd800) << 10) | ((c16 as u32) - 0xdc00));
18416        if !state.is_null() { *state = 0; }
18417    } else if c16 >= 0xd800 && c16 <= 0xdbff {
18418        if !state.is_null() { *state = c16 as u32; }
18419        return 0;
18420    } else if c16 >= 0xdc00 && c16 <= 0xdfff {
18421        ERRNO!() = EILSEQ;
18422        return !0usize;
18423    } else {
18424        cp = c16 as u32;
18425    }
18426    if cp < 0x80 {
18427        *s = cp as u8;
18428        1
18429    } else if cp < 0x800 {
18430        *s = (0xc0 | (cp >> 6)) as u8;
18431        *s.add(1) = (0x80 | (cp & 0x3f)) as u8;
18432        2
18433    } else if cp < 0x10000 {
18434        *s = (0xe0 | (cp >> 12)) as u8;
18435        *s.add(1) = (0x80 | ((cp >> 6) & 0x3f)) as u8;
18436        *s.add(2) = (0x80 | (cp & 0x3f)) as u8;
18437        3
18438    } else {
18439        *s = (0xf0 | (cp >> 18)) as u8;
18440        *s.add(1) = (0x80 | ((cp >> 12) & 0x3f)) as u8;
18441        *s.add(2) = (0x80 | ((cp >> 6) & 0x3f)) as u8;
18442        *s.add(3) = (0x80 | (cp & 0x3f)) as u8;
18443        4
18444    }
18445}
18446
18447#[no_mangle]
18448pub unsafe extern "C" fn c32rtomb(s: *mut u8, c32: u32, _ps: *mut core::ffi::c_void) -> usize {
18449    if s.is_null() { return 1; }
18450    if c32 > 0x10ffff || (c32 >= 0xd800 && c32 <= 0xdfff) {
18451        ERRNO!() = EILSEQ;
18452        return !0usize;
18453    }
18454    if c32 < 0x80 {
18455        *s = c32 as u8;
18456        1
18457    } else if c32 < 0x800 {
18458        *s = (0xc0 | (c32 >> 6)) as u8;
18459        *s.add(1) = (0x80 | (c32 & 0x3f)) as u8;
18460        2
18461    } else if c32 < 0x10000 {
18462        *s = (0xe0 | (c32 >> 12)) as u8;
18463        *s.add(1) = (0x80 | ((c32 >> 6) & 0x3f)) as u8;
18464        *s.add(2) = (0x80 | (c32 & 0x3f)) as u8;
18465        3
18466    } else {
18467        *s = (0xf0 | (c32 >> 18)) as u8;
18468        *s.add(1) = (0x80 | ((c32 >> 12) & 0x3f)) as u8;
18469        *s.add(2) = (0x80 | ((c32 >> 6) & 0x3f)) as u8;
18470        *s.add(3) = (0x80 | (c32 & 0x3f)) as u8;
18471        4
18472    }
18473}
18474
18475#[no_mangle]
18476pub unsafe extern "C" fn mbrtoc16(pc16: *mut u16, s: *const u8, n: usize, _ps: *mut core::ffi::c_void) -> usize {
18477    if s.is_null() { return 0; }
18478    if n == 0 { return 1; }
18479    let c = *s;
18480    if c == 0 { return 0; }
18481    if c < 0x80 {
18482        if !pc16.is_null() { *pc16 = c as u16; }
18483        return 1;
18484    }
18485    if c < 0xC2 { return 1; } // Invalid
18486    if c < 0xE0 {
18487        if n < 2 { return 1; }
18488        let c2 = *s.add(1);
18489        if (c2 & 0xC0) != 0x80 { return 1; }
18490        if !pc16.is_null() { *pc16 = ((((c & 0x1F) as u32) << 6) | ((c2 & 0x3F) as u32)) as u16; }
18491        return 2;
18492    }
18493    if c < 0xF0 {
18494        if n < 3 { return 1; }
18495        let c2 = *s.add(1);
18496        let c3 = *s.add(2);
18497        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 { return 1; }
18498        if !pc16.is_null() { *pc16 = ((((c & 0x0F) as u32) << 12) | (((c2 & 0x3F) as u32) << 6) | ((c3 & 0x3F) as u32)) as u16; }
18499        return 3;
18500    }
18501    1
18502}
18503
18504#[no_mangle]
18505pub unsafe extern "C" fn mbrtoc32(pc32: *mut u32, s: *const u8, n: usize, _ps: *mut core::ffi::c_void) -> usize {
18506    if s.is_null() { return 0; }
18507    if n == 0 { return 1; }
18508    let c = *s;
18509    if c == 0 { return 0; }
18510    if c < 0x80 {
18511        if !pc32.is_null() { *pc32 = c as u32; }
18512        return 1;
18513    }
18514    if c < 0xC2 { return 1; } // Invalid
18515    if c < 0xE0 {
18516        if n < 2 { return 1; }
18517        let c2 = *s.add(1);
18518        if (c2 & 0xC0) != 0x80 { return 1; }
18519        if !pc32.is_null() { *pc32 = (((c & 0x1F) as u32) << 6) | ((c2 & 0x3F) as u32); }
18520        return 2;
18521    }
18522    if c < 0xF0 {
18523        if n < 3 { return 1; }
18524        let c2 = *s.add(1);
18525        let c3 = *s.add(2);
18526        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 { return 1; }
18527        if !pc32.is_null() { *pc32 = (((c & 0x0F) as u32) << 12) | (((c2 & 0x3F) as u32) << 6) | ((c3 & 0x3F) as u32); }
18528        return 3;
18529    }
18530    if c < 0xF5 {
18531        if n < 4 { return 1; }
18532        let c2 = *s.add(1);
18533        let c3 = *s.add(2);
18534        let c4 = *s.add(3);
18535        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80 { return 1; }
18536        if !pc32.is_null() { *pc32 = (((c & 0x07) as u32) << 18) | (((c2 & 0x3F) as u32) << 12) | (((c3 & 0x3F) as u32) << 6) | ((c4 & 0x3F) as u32); }
18537        return 4;
18538    }
18539    1
18540}
18541
18542// ============================================================
18543// Shadow functions
18544// ============================================================
18545
18546
18547
18548
18549// ============================================================
18550// chown functions
18551// ============================================================
18552
18553#[no_mangle]
18554pub unsafe extern "C" fn chown(path: *const core::ffi::c_char, uid: u32, gid: u32) -> i32 {
18555    syscall_ret(<Arch as Syscalls>::syscall5(
18556        SYS_FCHOWNAT,
18557        AT_FDCWD as i64,
18558        path as i64,
18559        uid as i64,
18560        gid as i64,
18561        0,
18562    )) as i32
18563}
18564
18565#[no_mangle]
18566pub unsafe extern "C" fn lchown(path: *const core::ffi::c_char, uid: u32, gid: u32) -> i32 {
18567    syscall_ret(<Arch as Syscalls>::syscall5(
18568        SYS_FCHOWNAT,
18569        AT_FDCWD as i64,
18570        path as i64,
18571        uid as i64,
18572        gid as i64,
18573        0x100, // AT_SYMLINK_NOFOLLOW
18574    )) as i32
18575}
18576
18577// ============================================================
18578// chroot functions
18579// ============================================================
18580
18581#[no_mangle]
18582pub unsafe extern "C" fn chroot(path: *const core::ffi::c_char) -> i32 {
18583    syscall_ret(<Arch as Syscalls>::syscall1(SYS_CHROOT, path as i64)) as i32
18584}
18585
18586#[no_mangle]
18587pub unsafe extern "C" fn get_current_dir_name() -> *mut core::ffi::c_char {
18588    static mut BUF: [core::ffi::c_char; 4096] = [0; 4096];
18589    let r = getcwd(BUF.as_mut_ptr(), 4096);
18590    if r.is_null() { core::ptr::null_mut() } else { BUF.as_mut_ptr() }
18591}
18592
18593// ============================================================
18594// I/O functions
18595// ============================================================
18596
18597#[no_mangle]
18598pub unsafe extern "C" fn creat(pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18599    // O_WRONLY | O_CREAT | O_TRUNC. The previous flags included O_EXCL.
18600    open(pathname, 1 | 0o100 | 0o1000, mode as i32)
18601}
18602
18603#[no_mangle]
18604pub unsafe extern "C" fn openat(dirfd: i32, pathname: *const core::ffi::c_char, flags: i32, mode: u32) -> i32 {
18605    syscall_ret(<Arch as Syscalls>::syscall4(SYS_OPENAT, dirfd as i64, pathname as i64, flags as i64, mode as i64)) as i32
18606}
18607
18608#[no_mangle]
18609pub unsafe extern "C" fn pwrite(fd: i32, buf: *const u8, count: usize, offset: i64) -> isize {
18610    syscall_ret(<Arch as Syscalls>::syscall4(sysno(18, 68), fd as i64, buf as i64, count as i64, offset)) as isize
18611}
18612
18613#[no_mangle]
18614pub unsafe extern "C" fn readv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32) -> isize {
18615    syscall_ret(<Arch as Syscalls>::syscall3(sysno(19, 65), fd as i64, iov as i64, iovcnt as i64)) as isize
18616}
18617
18618#[no_mangle]
18619pub unsafe extern "C" fn writev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32) -> isize {
18620    syscall_ret(<Arch as Syscalls>::syscall3(sysno(20, 66), fd as i64, iov as i64, iovcnt as i64)) as isize
18621}
18622
18623// ============================================================
18624// Lock functions
18625// ============================================================
18626
18627#[no_mangle]
18628pub unsafe extern "C" fn flock(fd: i32, operation: i32) -> i32 {
18629    syscall_ret(<Arch as Syscalls>::syscall2(SYS_FLOCK, fd as i64, operation as i64)) as i32
18630}
18631
18632#[no_mangle]
18633pub unsafe extern "C" fn lockf(fd: i32, cmd: i32, len: i64) -> i32 {
18634    let r = <Arch as Syscalls>::syscall3(SYS_FCNTL, fd as i64, if cmd == 0 { 7 } else if cmd == 1 { 6 } else { 5 } , len);
18635    if r < 0 { return -1; }
18636    0
18637}
18638
18639// ============================================================
18640// Hostname/login functions
18641// ============================================================
18642
18643#[no_mangle]
18644pub unsafe extern "C" fn getdomainname(name: *mut core::ffi::c_char, len: usize) -> i32 {
18645    if name.is_null() || len == 0 {
18646        ERRNO!() = EINVAL;
18647        return -1;
18648    }
18649    let mut uts: UtsName = core::mem::zeroed();
18650    let r = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
18651    if r < 0 {
18652        ERRNO!() = (-r) as c_int;
18653        return -1;
18654    }
18655    let mut n = 0usize;
18656    while n < uts.domainname.len() && uts.domainname[n] != 0 { n += 1; }
18657    if n >= len {
18658        ERRNO!() = EINVAL;
18659        return -1;
18660    }
18661    core::ptr::copy_nonoverlapping(uts.domainname.as_ptr(), name as *mut u8, n);
18662    *name.add(n) = 0;
18663    0
18664}
18665
18666#[no_mangle]
18667pub unsafe extern "C" fn setdomainname(name: *const core::ffi::c_char, len: usize) -> i32 {
18668    syscall_ret(<Arch as Syscalls>::syscall2(sysno(171, 162), name as i64, len as i64)) as i32
18669}
18670
18671#[no_mangle]
18672pub unsafe extern "C" fn sethostname(name: *const core::ffi::c_char, len: usize) -> i32 {
18673    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)) as i32
18674}
18675
18676#[no_mangle]
18677pub unsafe extern "C" fn getlogin_r(name: *mut core::ffi::c_char, bufsize: usize) -> i32 {
18678    let user = getlogin();
18679    if user.is_null() { return ENXIO_VAL; }
18680    let len = crate::strlen(user);
18681    if len >= bufsize { return 34; } // ERANGE
18682    core::ptr::copy_nonoverlapping(user, name, len + 1);
18683    0
18684}
18685
18686#[no_mangle]
18687pub unsafe extern "C" fn cuserid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
18688    let user = crate::getenv(b"USER\0".as_ptr() as *const core::ffi::c_char);
18689    if user.is_null() { return core::ptr::null_mut(); }
18690    if s.is_null() {
18691        static mut BUF: [core::ffi::c_char; 32] = [0; 32];
18692        let mut i = 0;
18693        while i < 31 && *user.add(i) != 0 { BUF[i] = *user.add(i); i += 1; }
18694        BUF[i] = 0;
18695        BUF.as_mut_ptr()
18696    } else {
18697        let mut i = 0;
18698        while i < 31 && *user.add(i) != 0 { *s.add(i) = *user.add(i); i += 1; }
18699        *s.add(i) = 0;
18700        s
18701    }
18702}
18703
18704// ============================================================
18705// Group and passwd functions
18706// ============================================================
18707
18708#[repr(C)]
18709#[derive(Copy, Clone)]
18710pub struct Passwd {
18711    pub pw_name: *mut c_char,
18712    pub pw_passwd: *mut c_char,
18713    pub pw_uid: u32,
18714    pub pw_gid: u32,
18715    pub pw_gecos: *mut c_char,
18716    pub pw_dir: *mut c_char,
18717    pub pw_shell: *mut c_char,
18718}
18719
18720#[repr(C)]
18721#[derive(Copy, Clone)]
18722pub struct Group {
18723    pub gr_name: *mut c_char,
18724    pub gr_passwd: *mut c_char,
18725    pub gr_gid: u32,
18726    pub gr_mem: *mut *mut c_char,
18727}
18728
18729static mut PWD_ENT: Passwd = Passwd {
18730    pw_name: core::ptr::null_mut(), pw_passwd: core::ptr::null_mut(),
18731    pw_uid: 0, pw_gid: 0, pw_gecos: core::ptr::null_mut(),
18732    pw_dir: core::ptr::null_mut(), pw_shell: core::ptr::null_mut(),
18733};
18734static mut PWD_LINE: *mut c_char = core::ptr::null_mut();
18735static mut PWD_LINE_CAP: usize = 0;
18736static mut PWD_BUF: *mut c_char = core::ptr::null_mut();
18737static mut PWD_BUF_CAP: usize = 0;
18738static mut PWD_FILE: *mut FILE = core::ptr::null_mut();
18739
18740unsafe fn ensure_pwd_buf(n: usize) -> bool {
18741    if n <= PWD_BUF_CAP {
18742        return true;
18743    }
18744    let mut cap = if PWD_BUF_CAP == 0 { 1024 } else { PWD_BUF_CAP };
18745    while cap < n {
18746        cap *= 2;
18747    }
18748    let p = realloc(PWD_BUF as *mut c_void, cap) as *mut c_char;
18749    if p.is_null() {
18750        return false;
18751    }
18752    PWD_BUF = p;
18753    PWD_BUF_CAP = cap;
18754    true
18755}
18756
18757static mut GRP_ENT: Group = Group {
18758    gr_name: core::ptr::null_mut(), gr_passwd: core::ptr::null_mut(),
18759    gr_gid: 0, gr_mem: core::ptr::null_mut(),
18760};
18761static mut GRP_LINE: *mut c_char = core::ptr::null_mut();
18762static mut GRP_LINE_CAP: usize = 0;
18763static mut GRP_BUF: *mut c_char = core::ptr::null_mut();
18764static mut GRP_BUF_CAP: usize = 0;
18765static mut GRP_MEM: *mut *mut c_char = core::ptr::null_mut();
18766static mut GRP_MEM_CAP: usize = 0;
18767static mut GRP_FILE: *mut FILE = core::ptr::null_mut();
18768
18769unsafe fn ensure_grp_buf(n: usize) -> bool {
18770    if n <= GRP_BUF_CAP {
18771        return true;
18772    }
18773    let mut cap = if GRP_BUF_CAP == 0 { 2048 } else { GRP_BUF_CAP };
18774    while cap < n {
18775        cap *= 2;
18776    }
18777    let p = realloc(GRP_BUF as *mut c_void, cap) as *mut c_char;
18778    if p.is_null() {
18779        return false;
18780    }
18781    GRP_BUF = p;
18782    GRP_BUF_CAP = cap;
18783    true
18784}
18785
18786unsafe fn ensure_grp_mem(n: usize) -> bool {
18787    if n <= GRP_MEM_CAP {
18788        return true;
18789    }
18790    let mut cap = if GRP_MEM_CAP == 0 { 32 } else { GRP_MEM_CAP };
18791    while cap < n {
18792        cap *= 2;
18793    }
18794    let p = realloc(
18795        GRP_MEM as *mut c_void,
18796        cap * core::mem::size_of::<*mut c_char>(),
18797    ) as *mut *mut c_char;
18798    if p.is_null() {
18799        return false;
18800    }
18801    GRP_MEM = p;
18802    GRP_MEM_CAP = cap;
18803    true
18804}
18805
18806unsafe fn parse_passwd(line: *const c_char, ent: *mut Passwd, buf: *mut c_char, buflen: usize) -> bool {
18807    let mut src = line;
18808    let mut o = 0usize;
18809    let mut fields: [*mut c_char; 7] = [core::ptr::null_mut(); 7];
18810    let mut n = 0usize;
18811    while n < 7 {
18812        let start = o;
18813        while *src != 0 && *src != b':' as c_char {
18814            if o + 1 >= buflen { return false; }
18815            *buf.add(o) = *src;
18816            o += 1;
18817            src = src.add(1);
18818        }
18819        *buf.add(o) = 0;
18820        o += 1;
18821        fields[n] = buf.add(start);
18822        n += 1;
18823        if *src == 0 { break; }
18824        src = src.add(1);
18825    }
18826    if n < 7 { return false; }
18827    (*ent).pw_name = fields[0];
18828    (*ent).pw_passwd = fields[1];
18829    (*ent).pw_uid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
18830    (*ent).pw_gid = crate::strtol(fields[3], core::ptr::null_mut(), 10) as u32;
18831    (*ent).pw_gecos = fields[4];
18832    (*ent).pw_dir = fields[5];
18833    (*ent).pw_shell = fields[6];
18834    true
18835}
18836
18837unsafe fn parse_group(line: *const c_char, ent: *mut Group, buf: *mut c_char, buflen: usize) -> bool {
18838    let mut src = line;
18839    let mut o = 0usize;
18840    let mut fields: [*mut c_char; 4] = [core::ptr::null_mut(); 4];
18841    let mut n = 0usize;
18842    while n < 4 {
18843        let start = o;
18844        while *src != 0 && *src != b':' as c_char {
18845            if o + 1 >= buflen { return false; }
18846            *buf.add(o) = *src;
18847            o += 1;
18848            src = src.add(1);
18849        }
18850        *buf.add(o) = 0;
18851        o += 1;
18852        fields[n] = buf.add(start);
18853        n += 1;
18854        if *src == 0 { break; }
18855        src = src.add(1);
18856    }
18857    if n < 4 { return false; }
18858    (*ent).gr_name = fields[0];
18859    (*ent).gr_passwd = fields[1];
18860    (*ent).gr_gid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
18861    let mut count = 1usize;
18862    let mut m = fields[3];
18863    while *m != 0 {
18864        if *m == b',' as c_char { count += 1; }
18865        m = m.add(1);
18866    }
18867    if !ensure_grp_mem(count + 1) { return false; }
18868    let mut mi = 0usize;
18869    m = fields[3];
18870    if *m != 0 {
18871        loop {
18872            *GRP_MEM.add(mi) = m;
18873            mi += 1;
18874            while *m != 0 && *m != b',' as c_char { m = m.add(1); }
18875            if *m == 0 { break; }
18876            *m = 0;
18877            m = m.add(1);
18878        }
18879    }
18880    *GRP_MEM.add(mi) = core::ptr::null_mut();
18881    (*ent).gr_mem = GRP_MEM;
18882    true
18883}
18884
18885#[no_mangle]
18886pub unsafe extern "C" fn getpwnam(name: *const c_char) -> *mut Passwd {
18887    if name.is_null() { return core::ptr::null_mut(); }
18888    setpwent();
18889    loop {
18890        let p = getpwent();
18891        if p.is_null() { break; }
18892        if crate::strcmp((*p).pw_name as *const u8, name as *const u8) == 0 { endpwent(); return p; }
18893    }
18894    endpwent();
18895    core::ptr::null_mut()
18896}
18897
18898#[no_mangle]
18899pub unsafe extern "C" fn getpwuid(uid: u32) -> *mut Passwd {
18900    setpwent();
18901    loop {
18902        let p = getpwent();
18903        if p.is_null() { break; }
18904        if (*p).pw_uid == uid { endpwent(); return p; }
18905    }
18906    endpwent();
18907    core::ptr::null_mut()
18908}
18909
18910#[no_mangle]
18911pub unsafe extern "C" fn setpwent() {
18912    endpwent();
18913    PWD_FILE = crate::fopen(b"/etc/passwd\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
18914}
18915
18916#[no_mangle]
18917pub unsafe extern "C" fn getpwent() -> *mut Passwd {
18918    if PWD_FILE.is_null() { setpwent(); if PWD_FILE.is_null() { return core::ptr::null_mut(); } }
18919    loop {
18920        let n = crate::getline(&raw mut PWD_LINE, &raw mut PWD_LINE_CAP, PWD_FILE);
18921        if n < 0 { return core::ptr::null_mut(); }
18922        let mut len = n as usize;
18923        if len > 0 && *PWD_LINE.add(len - 1) == b'\n' as c_char {
18924            *PWD_LINE.add(len - 1) = 0;
18925            len -= 1;
18926        }
18927        let need = len + 1;
18928        if !ensure_pwd_buf(need) { return core::ptr::null_mut(); }
18929        if parse_passwd(PWD_LINE, &raw mut PWD_ENT, PWD_BUF, need) {
18930            return &raw mut PWD_ENT;
18931        }
18932    }
18933}
18934
18935#[no_mangle]
18936pub unsafe extern "C" fn endpwent() {
18937    if !PWD_FILE.is_null() { crate::fclose(PWD_FILE); PWD_FILE = core::ptr::null_mut(); }
18938}
18939
18940#[no_mangle]
18941pub 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 {
18942    if result.is_null() { return EINVAL; }
18943    let p = getpwnam(name);
18944    if p.is_null() { *result = core::ptr::null_mut(); 0 } else { *pwd = *p; *result = pwd; 0 }
18945}
18946
18947#[no_mangle]
18948pub unsafe extern "C" fn getpwuid_r(uid: u32, pwd: *mut Passwd, _buf: *mut c_char, _buflen: usize, result: *mut *mut Passwd) -> c_int {
18949    if result.is_null() { return EINVAL; }
18950    let p = getpwuid(uid);
18951    if p.is_null() { *result = core::ptr::null_mut(); 0 } else { *pwd = *p; *result = pwd; 0 }
18952}
18953
18954#[no_mangle]
18955pub unsafe extern "C" fn fgetpwent(f: *mut FILE) -> *mut Passwd {
18956    if f.is_null() { return core::ptr::null_mut(); }
18957    loop {
18958        let n = crate::getline(&raw mut PWD_LINE, &raw mut PWD_LINE_CAP, f);
18959        if n < 0 { return core::ptr::null_mut(); }
18960        let mut len = n as usize;
18961        if len > 0 && *PWD_LINE.add(len - 1) == b'\n' as c_char {
18962            *PWD_LINE.add(len - 1) = 0;
18963            len -= 1;
18964        }
18965        let need = len + 1;
18966        if !ensure_pwd_buf(need) { return core::ptr::null_mut(); }
18967        if parse_passwd(PWD_LINE, &raw mut PWD_ENT, PWD_BUF, need) {
18968            return &raw mut PWD_ENT;
18969        }
18970    }
18971}
18972
18973#[no_mangle]
18974pub unsafe extern "C" fn putpwent(f: *mut FILE, p: *const Passwd) -> c_int {
18975    if f.is_null() || p.is_null() { return -1; }
18976    crate::fprintf(f, b"%s:%s:%u:%u:%s:%s:%s\n\0".as_ptr() as *const c_char,
18977        (*p).pw_name, (*p).pw_passwd, (*p).pw_uid, (*p).pw_gid,
18978        (*p).pw_gecos, (*p).pw_dir, (*p).pw_shell)
18979}
18980
18981#[no_mangle]
18982pub unsafe extern "C" fn getgrnam(name: *const c_char) -> *mut Group {
18983    if name.is_null() { return core::ptr::null_mut(); }
18984    setgrent();
18985    loop {
18986        let g = getgrent();
18987        if g.is_null() { break; }
18988        if crate::strcmp((*g).gr_name as *const u8, name as *const u8) == 0 { endgrent(); return g; }
18989    }
18990    endgrent();
18991    core::ptr::null_mut()
18992}
18993
18994#[no_mangle]
18995pub unsafe extern "C" fn getgrgid(gid: u32) -> *mut Group {
18996    setgrent();
18997    loop {
18998        let g = getgrent();
18999        if g.is_null() { break; }
19000        if (*g).gr_gid == gid { endgrent(); return g; }
19001    }
19002    endgrent();
19003    core::ptr::null_mut()
19004}
19005
19006#[no_mangle]
19007pub unsafe extern "C" fn setgrent() {
19008    endgrent();
19009    GRP_FILE = crate::fopen(b"/etc/group\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19010}
19011
19012#[no_mangle]
19013pub unsafe extern "C" fn getgrent() -> *mut Group {
19014    if GRP_FILE.is_null() { setgrent(); if GRP_FILE.is_null() { return core::ptr::null_mut(); } }
19015    loop {
19016        let n = crate::getline(&raw mut GRP_LINE, &raw mut GRP_LINE_CAP, GRP_FILE);
19017        if n < 0 { return core::ptr::null_mut(); }
19018        let mut len = n as usize;
19019        if len > 0 && *GRP_LINE.add(len - 1) == b'\n' as c_char {
19020            *GRP_LINE.add(len - 1) = 0;
19021            len -= 1;
19022        }
19023        let need = len + 1;
19024        if !ensure_grp_buf(need) { return core::ptr::null_mut(); }
19025        if parse_group(GRP_LINE, &raw mut GRP_ENT, GRP_BUF, need) {
19026            return &raw mut GRP_ENT;
19027        }
19028    }
19029}
19030
19031#[no_mangle]
19032pub unsafe extern "C" fn endgrent() {
19033    if !GRP_FILE.is_null() { crate::fclose(GRP_FILE); GRP_FILE = core::ptr::null_mut(); }
19034}
19035
19036#[no_mangle]
19037pub 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 {
19038    if result.is_null() { return EINVAL; }
19039    let g = getgrnam(name);
19040    if g.is_null() { *result = core::ptr::null_mut(); 0 } else { *grp = *g; *result = grp; 0 }
19041}
19042
19043#[no_mangle]
19044pub unsafe extern "C" fn getgrgid_r(gid: u32, grp: *mut Group, _buf: *mut c_char, _buflen: usize, result: *mut *mut Group) -> c_int {
19045    if result.is_null() { return EINVAL; }
19046    let g = getgrgid(gid);
19047    if g.is_null() { *result = core::ptr::null_mut(); 0 } else { *grp = *g; *result = grp; 0 }
19048}
19049
19050#[no_mangle]
19051pub unsafe extern "C" fn fgetgrent(f: *mut FILE) -> *mut Group {
19052    if f.is_null() { return core::ptr::null_mut(); }
19053    loop {
19054        let n = crate::getline(&raw mut GRP_LINE, &raw mut GRP_LINE_CAP, f);
19055        if n < 0 { return core::ptr::null_mut(); }
19056        let mut len = n as usize;
19057        if len > 0 && *GRP_LINE.add(len - 1) == b'\n' as c_char {
19058            *GRP_LINE.add(len - 1) = 0;
19059            len -= 1;
19060        }
19061        let need = len + 1;
19062        if !ensure_grp_buf(need) { return core::ptr::null_mut(); }
19063        if parse_group(GRP_LINE, &raw mut GRP_ENT, GRP_BUF, need) {
19064            return &raw mut GRP_ENT;
19065        }
19066    }
19067}
19068
19069#[no_mangle]
19070pub unsafe extern "C" fn putgrent(f: *mut FILE, g: *const Group) -> c_int {
19071    if f.is_null() || g.is_null() { return -1; }
19072    crate::fprintf(f, b"%s:%s:%u:\0".as_ptr() as *const c_char, (*g).gr_name, (*g).gr_passwd, (*g).gr_gid);
19073    if !(*g).gr_mem.is_null() {
19074        let mut i = 0;
19075        while !(*(*g).gr_mem.add(i)).is_null() {
19076            if i > 0 { crate::fputc(b',' as c_int, f); }
19077            crate::fputs(*(*g).gr_mem.add(i), f);
19078            i += 1;
19079        }
19080    }
19081    crate::fputc(b'\n' as c_int, f);
19082    0
19083}
19084
19085// ============================================================
19086// User/group functions
19087// ============================================================
19088
19089#[no_mangle]
19090pub unsafe extern "C" fn setgroups(ngroups: usize, gidset: *const u32) -> i32 {
19091    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETGROUPS, ngroups as i64, gidset as i64)) as i32
19092}
19093
19094#[no_mangle]
19095pub unsafe extern "C" fn setresuid(ruid: u32, euid: u32, suid: u32) -> i32 {
19096    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETRESUID, ruid as i64, euid as i64, suid as i64)) as i32
19097}
19098
19099#[no_mangle]
19100pub unsafe extern "C" fn setresgid(rgid: u32, egid: u32, sgid: u32) -> i32 {
19101    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETRESGID, rgid as i64, egid as i64, sgid as i64)) as i32
19102}
19103
19104#[no_mangle]
19105pub unsafe extern "C" fn getresuid(ruid: *mut u32, euid: *mut u32, suid: *mut u32) -> i32 {
19106    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETRESUID, ruid as i64, euid as i64, suid as i64)) as i32
19107}
19108
19109#[no_mangle]
19110pub unsafe extern "C" fn getresgid(rgid: *mut u32, egid: *mut u32, sgid: *mut u32) -> i32 {
19111    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETRESGID, rgid as i64, egid as i64, sgid as i64)) as i32
19112}
19113
19114// ============================================================
19115// Socket functions
19116// ============================================================
19117
19118// musl's public struct msghdr uses 32-bit msg_iovlen/msg_controllen followed
19119// by padding on 64-bit little-endian. The kernel reads 64-bit fields, so the
19120// padding must be zero; callers (nginx, for example) do not initialize it.
19121#[repr(C)]
19122struct KernelMsgHdr {
19123    msg_name: *mut c_void,
19124    msg_namelen: u32,
19125    __pad0: u32,
19126    msg_iov: *mut c_void,
19127    msg_iovlen: u64,
19128    msg_control: *mut c_void,
19129    msg_controllen: u64,
19130    msg_flags: u32,
19131    __pad1: u32,
19132}
19133
19134#[repr(C)]
19135struct UserMsgHdr {
19136    msg_name: *mut c_void,
19137    msg_namelen: u32,
19138    msg_iov: *mut c_void,
19139    msg_iovlen: i32,
19140    __pad1: i32,
19141    msg_control: *mut c_void,
19142    msg_controllen: u32,
19143    __pad2: i32,
19144    msg_flags: i32,
19145}
19146
19147unsafe fn msg_to_kernel(msg: *const UserMsgHdr, out: &mut KernelMsgHdr) {
19148    *out = KernelMsgHdr {
19149        msg_name: (*msg).msg_name,
19150        msg_namelen: (*msg).msg_namelen,
19151        __pad0: 0,
19152        msg_iov: (*msg).msg_iov,
19153        msg_iovlen: (*msg).msg_iovlen as u32 as u64,
19154        msg_control: (*msg).msg_control,
19155        msg_controllen: (*msg).msg_controllen as u64,
19156        msg_flags: (*msg).msg_flags as u32,
19157        __pad1: 0,
19158    };
19159}
19160
19161#[no_mangle]
19162pub unsafe extern "C" fn sendmsg(fd: i32, msg: *const core::ffi::c_void, flags: i32) -> isize {
19163    if msg.is_null() {
19164        ERRNO!() = EINVAL;
19165        return -1;
19166    }
19167    let mut k: KernelMsgHdr = core::mem::zeroed();
19168    msg_to_kernel(msg as *const UserMsgHdr, &mut k);
19169    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SENDMSG, fd as i64, &k as *const KernelMsgHdr as i64, flags as i64)) as isize
19170}
19171
19172#[no_mangle]
19173pub unsafe extern "C" fn recvmsg(fd: i32, msg: *mut core::ffi::c_void, flags: i32) -> isize {
19174    if msg.is_null() {
19175        ERRNO!() = EINVAL;
19176        return -1;
19177    }
19178    let user = msg as *mut UserMsgHdr;
19179    let mut k: KernelMsgHdr = core::mem::zeroed();
19180    msg_to_kernel(user, &mut k);
19181    let r = syscall_ret(<Arch as Syscalls>::syscall3(SYS_RECVMSG, fd as i64, &mut k as *mut KernelMsgHdr as i64, flags as i64));
19182    (*user).msg_flags = k.msg_flags as i32;
19183    (*user).msg_controllen = k.msg_controllen as u32;
19184    r as isize
19185}
19186
19187#[no_mangle]
19188pub unsafe extern "C" fn sendmmsg(fd: i32, msgvec: *mut core::ffi::c_void, vlen: u32, flags: i32) -> i32 {
19189    syscall_ret(<Arch as Syscalls>::syscall4(sysno(307, 269), fd as i64, msgvec as i64, vlen as i64, flags as i64)) as i32
19190}
19191
19192#[no_mangle]
19193pub unsafe extern "C" fn recvmmsg(fd: i32, msgvec: *mut core::ffi::c_void, vlen: u32, flags: i32, timeout: *mut core::ffi::c_void) -> i32 {
19194    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
19195}
19196
19197#[no_mangle]
19198pub unsafe extern "C" fn getpeername(fd: i32, addr: *mut core::ffi::c_void, addrlen: *mut u32) -> i32 {
19199    syscall_ret(<Arch as Syscalls>::syscall3(sysno(52, 205), fd as i64, addr as i64, addrlen as i64)) as i32
19200}
19201
19202#[no_mangle]
19203pub unsafe extern "C" fn getsockopt(fd: i32, level: i32, optname: i32, optval: *mut core::ffi::c_void, optlen: *mut u32) -> i32 {
19204    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
19205}
19206
19207// ============================================================
19208// stdio unlocked functions
19209// ============================================================
19210
19211#[no_mangle]
19212pub unsafe extern "C" fn ftrylockfile(file: *mut FILE) -> i32 {
19213    if file.is_null() { return EINVAL; }
19214    if (*file).lock < 0 { return 0; }
19215    let tid = sys_gettid() as c_int;
19216    let v = a_load(&raw const (*file).lock);
19217    if v == tid {
19218        (*file).lockcount += 1;
19219        return 0;
19220    }
19221    if v == 0 && a_cas(&raw mut (*file).lock, 0, tid) == 0 {
19222        (*file).lockcount = 1;
19223        return 0;
19224    }
19225    EBUSY
19226}
19227
19228#[no_mangle]
19229pub unsafe extern "C" fn getc_unlocked(file: *mut core::ffi::c_char) -> i32 {
19230    getc(file as *mut FILE)
19231}
19232
19233#[no_mangle]
19234pub unsafe extern "C" fn getchar_unlocked() -> i32 {
19235    getchar()
19236}
19237
19238#[no_mangle]
19239pub unsafe extern "C" fn putc_unlocked(c: i32, file: *mut core::ffi::c_char) -> i32 {
19240    putc(c, file as *mut FILE)
19241}
19242
19243#[no_mangle]
19244pub unsafe extern "C" fn putchar_unlocked(c: i32) -> i32 {
19245    putchar(c)
19246}
19247
19248// ============================================================
19249// getopt functions
19250// ============================================================
19251
19252#[no_mangle] pub static mut optarg: *mut core::ffi::c_char = core::ptr::null_mut();
19253#[no_mangle] pub static mut optind: i32 = 1;
19254#[no_mangle] pub static mut opterr: i32 = 1;
19255#[no_mangle] pub static mut optopt: i32 = '?' as i32;
19256#[no_mangle] pub static mut optreset: i32 = 0;
19257
19258// ============================================================
19259// Timer functions
19260// ============================================================
19261
19262#[no_mangle]
19263pub unsafe extern "C" fn getitimer(which: i32, curr_value: *mut core::ffi::c_void) -> i32 {
19264    syscall_ret(<Arch as Syscalls>::syscall2(sysno(36, 102), which as i64, curr_value as i64)) as i32
19265}
19266
19267#[no_mangle]
19268pub unsafe extern "C" fn setitimer(which: i32, new_value: *const core::ffi::c_void, old_value: *mut core::ffi::c_void) -> i32 {
19269    syscall_ret(<Arch as Syscalls>::syscall3(sysno(38, 103), which as i64, new_value as i64, old_value as i64)) as i32
19270}
19271
19272// ============================================================
19273// System info functions
19274// ============================================================
19275
19276#[no_mangle]
19277pub unsafe extern "C" fn getloadavg(loadavg: *mut f64, nelem: i32) -> i32 {
19278    let fd = crate::open(b"/proc/loadavg\0".as_ptr() as *const core::ffi::c_char, 0, 0);
19279    if fd < 0 { return -1; }
19280    let mut buf: [u8; 64] = [0; 64];
19281    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
19282    crate::close(fd);
19283    if n <= 0 { return -1; }
19284    buf[n as usize] = 0;
19285    let mut i = 0;
19286    while i < nelem as usize && i < 3 {
19287        let val = crate::strtod((buf.as_ptr() as *const core::ffi::c_char).add(i * 5), core::ptr::null_mut());
19288        *loadavg.add(i) = val;
19289        i += 1;
19290    }
19291    i as i32
19292}
19293
19294#[no_mangle]
19295pub unsafe extern "C" fn get_nprocs() -> i32 {
19296    sysconf(84) as i32 // _SC_NPROCESSORS_ONLN
19297}
19298
19299#[no_mangle]
19300pub unsafe extern "C" fn get_nprocs_conf() -> i32 {
19301    sysconf(83) as i32 // _SC_NPROCESSORS_CONF
19302}
19303
19304#[no_mangle]
19305pub unsafe extern "C" fn get_avphys_pages() -> i64 {
19306    sysconf(86) // _SC_AVPHYS_PAGES
19307}
19308
19309#[no_mangle]
19310pub unsafe extern "C" fn get_phys_pages() -> i64 {
19311    sysconf(85) // _SC_PHYS_PAGES
19312}
19313
19314// ============================================================
19315// Capability functions
19316// ============================================================
19317
19318#[no_mangle]
19319pub unsafe extern "C" fn capget(header: *mut core::ffi::c_void, data: *mut core::ffi::c_void) -> i32 {
19320    syscall_ret(<Arch as Syscalls>::syscall2(SYS_CAPGET, header as i64, data as i64)) as i32
19321}
19322
19323#[no_mangle]
19324pub unsafe extern "C" fn capset(header: *const core::ffi::c_void, data: *const core::ffi::c_void) -> i32 {
19325    syscall_ret(<Arch as Syscalls>::syscall2(SYS_CAPSET, header as i64, data as i64)) as i32
19326}
19327
19328#[no_mangle]
19329pub unsafe extern "C" fn arch_prctl(code: i32, addr: u64) -> i32 {
19330    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 }
19331}
19332
19333// ============================================================
19334// termios functions
19335// ============================================================
19336
19337#[no_mangle]
19338pub unsafe extern "C" fn cfgetospeed(termios_p: *const core::ffi::c_void) -> u32 {
19339    unsafe { *(termios_p as *const u32).add(1) }
19340}
19341
19342#[no_mangle]
19343pub unsafe extern "C" fn cfgetispeed(termios_p: *const core::ffi::c_void) -> u32 {
19344    unsafe { *(termios_p as *const u32).add(2) }
19345}
19346
19347#[no_mangle]
19348pub unsafe extern "C" fn cfsetospeed(termios_p: *mut core::ffi::c_void, speed: u32) -> i32 {
19349    unsafe { *(termios_p as *mut u32).add(1) = speed; }
19350    0
19351}
19352
19353#[no_mangle]
19354pub unsafe extern "C" fn cfsetispeed(termios_p: *mut core::ffi::c_void, speed: u32) -> i32 {
19355    unsafe { *(termios_p as *mut u32).add(2) = speed; }
19356    0
19357}
19358
19359#[no_mangle]
19360pub unsafe extern "C" fn cfmakeraw(termios_p: *mut core::ffi::c_void) {
19361    unsafe {
19362        let p = termios_p as *mut u32;
19363        *p.add(0) &= !0o37;
19364        *p.add(0) &= !(0o4000 | 0o2000 | 0o10000 | 0o20);
19365        *p.add(0) |= 0o60;
19366        *p.add(3) &= !0o17;
19367        *p.add(3) &= !(0o1000 | 0o40000000);
19368        *p.add(1) = 1;
19369        *p.add(2) = 0;
19370    }
19371}
19372
19373// ============================================================
19374// Resource functions
19375// ============================================================
19376
19377#[no_mangle]
19378pub unsafe extern "C" fn getrusage(who: i32, usage: *mut core::ffi::c_void) -> i32 {
19379    syscall_ret(<Arch as Syscalls>::syscall2(sysno(98, 165), who as i64, usage as i64)) as i32
19380}
19381
19382#[no_mangle]
19383pub unsafe extern "C" fn getpriority(which: i32, who: u32) -> i32 {
19384    // The kernel encodes nice as 20 - nice; musl converts it back.
19385    let r = <Arch as Syscalls>::syscall2(SYS_GETPRIORITY, which as i64, who as i64);
19386    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
19387    20 - r as i32
19388}
19389
19390#[no_mangle]
19391pub unsafe extern "C" fn setpriority(which: i32, who: u32, prio: i32) -> i32 {
19392    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETPRIORITY, which as i64, who as i64, prio as i64)) as i32
19393}
19394
19395#[no_mangle]
19396pub unsafe extern "C" fn prlimit(pid: u32, resource: i32, new_limit: *const core::ffi::c_void, old_limit: *mut core::ffi::c_void) -> i32 {
19397    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
19398}
19399
19400// ============================================================
19401// fork/clone functions
19402// ============================================================
19403
19404#[no_mangle]
19405pub unsafe extern "C" fn clone(
19406    func: usize,
19407    stack: *mut u8,
19408    flags: c_int,
19409    arg: *mut c_void,
19410    mut args: ...
19411) -> c_int {
19412    // musl-compatible signature: clone(fn, stack, flags, arg, ptid, tls, ctid).
19413    const CLONE_PIDFD_C: c_int = 0x00001000;
19414    const CLONE_VM_C: c_int = 0x00000100;
19415    const CLONE_THREAD_C: c_int = 0x00010000;
19416    const CLONE_SETTLS_C: c_int = 0x00080000;
19417    const CLONE_PARENT_SETTID_C: c_int = 0x00100000;
19418    const CLONE_CHILD_SETTID_C: c_int = 0x01000000;
19419    const CLONE_CHILD_CLEARTID_C: c_int = 0x00200000;
19420    let _ = CLONE_VM_C;
19421    if flags & (CLONE_THREAD_C | CLONE_SETTLS_C | CLONE_CHILD_CLEARTID_C) != 0
19422        || stack.is_null()
19423    {
19424        ERRNO!() = EINVAL;
19425        return -1;
19426    }
19427    let mut ptid: *mut c_int = core::ptr::null_mut();
19428    let mut tls: c_ulong = 0;
19429    let mut ctid: *mut c_int = core::ptr::null_mut();
19430    if flags & (CLONE_PIDFD_C | CLONE_PARENT_SETTID_C | CLONE_CHILD_SETTID_C) != 0 {
19431        ptid = args.next_arg::<*mut c_int>();
19432    }
19433    if flags & CLONE_CHILD_SETTID_C != 0 {
19434        tls = args.next_arg::<c_ulong>();
19435        ctid = args.next_arg::<*mut c_int>();
19436    }
19437    let r = __keel_clone(func, stack, flags as c_ulong, arg, ptid, tls, ctid);
19438    if r < 0 {
19439        ERRNO!() = (-r) as c_int;
19440        -1
19441    } else {
19442        r as c_int
19443    }
19444}
19445
19446#[no_mangle]
19447pub unsafe extern "C" fn _Fork() -> i32 {
19448    crate::fork()
19449}
19450
19451#[no_mangle]
19452pub 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 {
19453    let mut master: i32 = 0;
19454    let mut slave: i32 = 0;
19455    if openpty(&mut master, &mut slave, name, termp, winp) < 0 { return -1; }
19456    let pid = crate::fork();
19457    if pid < 0 { crate::close(master); crate::close(slave); return -1; }
19458    if pid == 0 {
19459        crate::close(master);
19460        crate::setsid();
19461        crate::dup2(slave, 0);
19462        crate::dup2(slave, 1);
19463        crate::dup2(slave, 2);
19464    } else {
19465        crate::close(slave);
19466        if !amaster.is_null() { *amaster = master; }
19467    }
19468    pid
19469}
19470
19471#[no_mangle]
19472pub 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 {
19473    let master = crate::open(b"/dev/ptmx\0".as_ptr() as *const core::ffi::c_char, 0o2000, 0);
19474    if master < 0 { return -1; }
19475    grantpt(master);
19476    unlockpt(master);
19477    let slave_name = ptsname(master);
19478    if slave_name.is_null() { crate::close(master); return -1; }
19479    let slave = crate::open(slave_name, 0o2000, 0);
19480    if slave < 0 { crate::close(master); return -1; }
19481    if !amaster.is_null() { *amaster = master; }
19482    if !aslave.is_null() { *aslave = slave; }
19483    if !name.is_null() { crate::strcpy(name as *mut u8, slave_name as *const u8); }
19484    0
19485}
19486
19487#[no_mangle]
19488pub unsafe extern "C" fn login_tty(fd: i32) -> i32 {
19489    crate::setsid();
19490    crate::dup2(fd, 0);
19491    crate::dup2(fd, 1);
19492    crate::dup2(fd, 2);
19493    0
19494}
19495
19496// ============================================================
19497// dl functions
19498// ============================================================
19499
19500#[no_mangle]
19501pub unsafe extern "C" fn __dls2b() {}
19502#[no_mangle]
19503pub unsafe extern "C" fn __dls3() {}
19504#[no_mangle]
19505pub unsafe extern "C" fn _dlstart() {}
19506
19507// ============================================================
19508// string functions
19509// ============================================================
19510
19511#[no_mangle]
19512pub unsafe extern "C" fn index(s: *const core::ffi::c_char, c: i32) -> *mut core::ffi::c_char {
19513    let mut i = 0;
19514    loop {
19515        let ch = *s.add(i);
19516        if ch == c as core::ffi::c_char { return s.add(i) as *mut core::ffi::c_char; }
19517        if ch == 0 { return core::ptr::null_mut(); }
19518        i += 1;
19519    }
19520}
19521
19522#[no_mangle]
19523pub unsafe extern "C" fn rindex(s: *const core::ffi::c_char, c: i32) -> *mut core::ffi::c_char {
19524    let mut last = core::ptr::null_mut();
19525    let mut i = 0;
19526    loop {
19527        let ch = *s.add(i);
19528        if ch == 0 { return last; }
19529        if ch == c as core::ffi::c_char { last = s.add(i) as *mut core::ffi::c_char; }
19530        i += 1;
19531    }
19532}
19533
19534// ============================================================
19535// intmax functions
19536// ============================================================
19537
19538#[no_mangle]
19539pub unsafe extern "C" fn imaxabs(j: i64) -> i64 {
19540    j.abs()
19541}
19542
19543#[no_mangle]
19544pub unsafe extern "C" fn imaxdiv(numer: i64, denom: i64) -> (i64, i64) {
19545    (numer / denom, numer % denom)
19546}
19547
19548// ============================================================
19549// herror functions
19550// ============================================================
19551
19552#[no_mangle]
19553pub static mut h_errno: i32 = 0;
19554
19555#[no_mangle]
19556pub unsafe extern "C" fn __h_errno_location() -> *mut i32 {
19557    &mut h_errno
19558}
19559
19560#[no_mangle]
19561pub unsafe extern "C" fn herror(s: *const core::ffi::c_char) {
19562    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
19563    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
19564    crate::write(2, hstrerror(*__h_errno_location()) as *const core::ffi::c_void, crate::strlen(hstrerror(*__h_errno_location())));
19565    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
19566}
19567
19568#[no_mangle]
19569pub unsafe extern "C" fn hstrerror(_err: i32) -> *const core::ffi::c_char {
19570    b"Unknown error\0".as_ptr() as *const core::ffi::c_char
19571}
19572
19573// ============================================================
19574// gettid function
19575// ============================================================
19576
19577#[no_mangle]
19578pub unsafe extern "C" fn gettid() -> i32 {
19579    syscall_ret(<Arch as Syscalls>::syscall0(SYS_GETTID)) as i32
19580}
19581
19582// ============================================================
19583// ioctl functions
19584// ============================================================
19585
19586#[no_mangle]
19587pub unsafe extern "C" fn ioctl(fd: i32, request: u32, mut args: ...) -> i32 {
19588    let arg = args.next_arg::<i64>();
19589    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg)) as i32
19590}
19591
19592#[no_mangle]
19593pub unsafe extern "C" fn ioperm(from: u64, num: u64, turn_on: i32) -> i32 {
19594    #[cfg(target_arch = "x86_64")]
19595    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOPERM, from as i64, num as i64, turn_on as i64)) as i32 }
19596    #[cfg(not(target_arch = "x86_64"))]
19597    {
19598        let _ = (from, num, turn_on);
19599        ERRNO!() = ENOSYS_VAL;
19600        -1
19601    }
19602}
19603
19604#[no_mangle]
19605pub unsafe extern "C" fn iopl(level: i32) -> i32 {
19606    #[cfg(target_arch = "x86_64")]
19607    { syscall_ret(<Arch as Syscalls>::syscall1(SYS_IOPL, level as i64)) as i32 }
19608    #[cfg(not(target_arch = "x86_64"))]
19609    {
19610        let _ = level;
19611        ERRNO!() = ENOSYS_VAL;
19612        -1
19613    }
19614}
19615
19616// ============================================================
19617// xattr functions
19618// ============================================================
19619
19620#[no_mangle]
19621pub unsafe extern "C" fn getxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
19622    syscall_ret(<Arch as Syscalls>::syscall4(sysno(191, 8), path as i64, name as i64, value as i64, size as i64)) as isize
19623}
19624
19625#[no_mangle]
19626pub unsafe extern "C" fn lgetxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
19627    syscall_ret(<Arch as Syscalls>::syscall4(sysno(192, 9), path as i64, name as i64, value as i64, size as i64)) as isize
19628}
19629
19630#[no_mangle]
19631pub unsafe extern "C" fn fgetxattr(fd: i32, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
19632    syscall_ret(<Arch as Syscalls>::syscall4(sysno(193, 10), fd as i64, name as i64, value as i64, size as i64)) as isize
19633}
19634
19635#[no_mangle]
19636pub unsafe extern "C" fn listxattr(path: *const core::ffi::c_char, list: *mut u8, size: usize) -> isize {
19637    syscall_ret(<Arch as Syscalls>::syscall3(sysno(194, 11), path as i64, list as i64, size as i64)) as isize
19638}
19639
19640#[no_mangle]
19641pub unsafe extern "C" fn llistxattr(path: *const core::ffi::c_char, list: *mut u8, size: usize) -> isize {
19642    syscall_ret(<Arch as Syscalls>::syscall3(sysno(195, 12), path as i64, list as i64, size as i64)) as isize
19643}
19644
19645#[no_mangle]
19646pub unsafe extern "C" fn flistxattr(fd: i32, list: *mut u8, size: usize) -> isize {
19647    syscall_ret(<Arch as Syscalls>::syscall3(sysno(196, 13), fd as i64, list as i64, size as i64)) as isize
19648}
19649
19650#[no_mangle]
19651pub 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 {
19652    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
19653}
19654
19655#[no_mangle]
19656pub 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 {
19657    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
19658}
19659
19660#[no_mangle]
19661pub unsafe extern "C" fn fsetxattr(fd: i32, name: *const core::ffi::c_char, value: *const u8, size: usize, flags: i32) -> i32 {
19662    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
19663}
19664
19665#[no_mangle]
19666pub unsafe extern "C" fn removexattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char) -> i32 {
19667    syscall_ret(<Arch as Syscalls>::syscall2(sysno(197, 14), path as i64, name as i64)) as i32
19668}
19669
19670#[no_mangle]
19671pub unsafe extern "C" fn lremovexattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char) -> i32 {
19672    syscall_ret(<Arch as Syscalls>::syscall2(sysno(198, 15), path as i64, name as i64)) as i32
19673}
19674
19675#[no_mangle]
19676pub unsafe extern "C" fn fremovexattr(fd: i32, name: *const core::ffi::c_char) -> i32 {
19677    syscall_ret(<Arch as Syscalls>::syscall2(sysno(199, 16), fd as i64, name as i64)) as i32
19678}
19679
19680// ============================================================
19681// adjtime functions
19682// ============================================================
19683
19684#[no_mangle]
19685pub unsafe extern "C" fn adjtime(_delta: *const core::ffi::c_void, olddelta: *mut core::ffi::c_void) -> i32 {
19686    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ADJTIMEX, olddelta as i64)) as i32
19687}
19688
19689#[no_mangle]
19690pub unsafe extern "C" fn adjtimex(buf: *mut core::ffi::c_void) -> i32 {
19691    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ADJTIMEX, buf as i64)) as i32
19692}
19693
19694// ============================================================
19695// pty functions
19696// ============================================================
19697
19698// Linux devpts ioctls (asm-generic/ioctls.h): TIOCGPTN = _IOR('T', 0x30, int),
19699// TIOCSPTLCK = _IOW('T', 0x31, int). The old 0x541x values are the window-size
19700// and process-group requests, which both return the wrong data and write more
19701// bytes than the int the caller supplied.
19702const TIOCGPTN: i64 = 0x80045430;
19703const TIOCSPTLCK: i64 = 0x40045431;
19704
19705#[no_mangle]
19706pub unsafe extern "C" fn grantpt(_fd: i32) -> i32 {
19707    // devpts creates the slave already owned by the caller.
19708    0
19709}
19710
19711#[no_mangle]
19712pub unsafe extern "C" fn unlockpt(fd: i32) -> i32 {
19713    let mut unlock: i32 = 0;
19714    let r = <Arch as Syscalls>::syscall3(
19715        SYS_IOCTL,
19716        fd as i64,
19717        TIOCSPTLCK,
19718        &mut unlock as *mut i32 as i64,
19719    );
19720    if r < 0 { -1 } else { 0 }
19721}
19722
19723#[no_mangle]
19724pub unsafe extern "C" fn ptsname(fd: i32) -> *mut core::ffi::c_char {
19725    static mut BUF: [core::ffi::c_char; 32] = [0; 32];
19726    let mut pty_nr: i32 = 0;
19727    if <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, TIOCGPTN, &mut pty_nr as *mut i32 as i64) < 0 {
19728        return core::ptr::null_mut();
19729    }
19730    // Format /dev/pts/N
19731    BUF[0] = '/' as c_char; BUF[1] = 'd' as c_char; BUF[2] = 'e' as c_char; BUF[3] = 'v' as c_char;
19732    BUF[4] = '/' as c_char; BUF[5] = 'p' as c_char; BUF[6] = 't' as c_char; BUF[7] = 's' as c_char;
19733    BUF[8] = '/' as c_char;
19734    let mut n = pty_nr as usize;
19735    let mut i = 9;
19736    if n == 0 { BUF[i] = '0' as c_char; i += 1; }
19737    while n > 0 && i < 31 {
19738        BUF[i] = (b'0' + (n % 10) as u8) as c_char;
19739        n /= 10;
19740        i += 1;
19741    }
19742    BUF[i] = 0;
19743    BUF.as_mut_ptr()
19744}
19745
19746// ============================================================
19747// fpclassify functions
19748// ============================================================
19749
19750#[no_mangle]
19751pub unsafe extern "C" fn finite(x: f64) -> i32 {
19752    (!x.is_nan() && !x.is_infinite()) as i32
19753}
19754
19755#[no_mangle]
19756pub unsafe extern "C" fn finitef(x: f32) -> i32 {
19757    (!x.is_nan() && !x.is_infinite()) as i32
19758}
19759
19760#[no_mangle]
19761pub unsafe extern "C" fn __fpclassifyl(x: f64) -> i32 {
19762    __fpclassify(x)
19763}
19764
19765#[no_mangle]
19766pub unsafe extern "C" fn __signbitl(x: f64) -> i32 {
19767    __signbit(x)
19768}
19769
19770// ============================================================
19771// ftw functions
19772// ============================================================
19773
19774// ============================================================
19775// Bessel functions
19776// ============================================================
19777
19778#[no_mangle]
19779pub unsafe extern "C" fn j0(x: f64) -> f64 {
19780    j0_impl(x)
19781}
19782
19783#[no_mangle]
19784pub unsafe extern "C" fn j0f(x: f32) -> f32 {
19785    libm::j0f(x)
19786}
19787
19788#[no_mangle]
19789pub unsafe extern "C" fn j1(x: f64) -> f64 {
19790    libm::j1(x)
19791}
19792
19793#[no_mangle]
19794pub unsafe extern "C" fn j1f(x: f32) -> f32 {
19795    libm::j1f(x)
19796}
19797
19798#[no_mangle]
19799pub unsafe extern "C" fn jn(n: i32, x: f64) -> f64 {
19800    libm::jn(n, x)
19801}
19802
19803#[no_mangle]
19804pub unsafe extern "C" fn jnf(n: i32, x: f32) -> f32 {
19805    libm::jnf(n, x)
19806}
19807
19808#[no_mangle]
19809pub unsafe extern "C" fn y0(x: f64) -> f64 {
19810    y0_impl(x)
19811}
19812
19813#[no_mangle]
19814pub unsafe extern "C" fn y0f(x: f32) -> f32 {
19815    if x.is_nan() { return x; }
19816    if x < 0.0 { return __math_invalidf(x); }
19817    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f32::NEG_INFINITY; }
19818    libm::y0f(x)
19819}
19820
19821#[no_mangle]
19822pub unsafe extern "C" fn y1(x: f64) -> f64 {
19823    if x.is_nan() { return x; }
19824    if x < 0.0 { return __math_invalid(x); }
19825    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f64::NEG_INFINITY; }
19826    libm::y1(x)
19827}
19828
19829#[no_mangle]
19830pub unsafe extern "C" fn y1f(x: f32) -> f32 {
19831    if x.is_nan() { return x; }
19832    if x < 0.0 { return __math_invalidf(x); }
19833    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f32::NEG_INFINITY; }
19834    libm::y1f(x)
19835}
19836
19837#[no_mangle]
19838pub unsafe extern "C" fn yn(n: i32, x: f64) -> f64 {
19839    if x.is_nan() { return x; }
19840    if x < 0.0 { return __math_invalid(x); }
19841    if x == 0.0 {
19842        feraiseexcept(FE_DIVBYZERO);
19843        if n >= 0 { return f64::NEG_INFINITY; }
19844    }
19845    libm::yn(n, x)
19846}
19847
19848#[no_mangle]
19849pub unsafe extern "C" fn ynf(n: i32, x: f32) -> f32 {
19850    if x.is_nan() { return x; }
19851    if x < 0.0 { return __math_invalidf(x); }
19852    if x == 0.0 {
19853        feraiseexcept(FE_DIVBYZERO);
19854        if n >= 0 { return f32::NEG_INFINITY; }
19855    }
19856    libm::ynf(n, x)
19857}
19858
19859// ============================================================
19860// ctype locale functions
19861// ============================================================
19862
19863#[no_mangle]
19864pub unsafe extern "C" fn __ctype_b_loc() -> *mut *const u16 {
19865    static mut TABLE: *const u16 = core::ptr::null();
19866    &mut TABLE
19867}
19868
19869#[no_mangle]
19870pub unsafe extern "C" fn __ctype_tolower_loc() -> *mut *const i32 {
19871    static mut TABLE: *const i32 = core::ptr::null();
19872    &mut TABLE
19873}
19874
19875#[no_mangle]
19876pub unsafe extern "C" fn __ctype_toupper_loc() -> *mut *const i32 {
19877    static mut TABLE: *const i32 = core::ptr::null();
19878    &mut TABLE
19879}
19880
19881#[no_mangle]
19882pub unsafe extern "C" fn __isalnum_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19883    (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
19884}
19885
19886#[no_mangle]
19887pub unsafe extern "C" fn __isalpha_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19888    (c >= 'A' as i32 && c <= 'Z' as i32 || c >= 'a' as i32 && c <= 'z' as i32) as i32
19889}
19890
19891#[no_mangle]
19892pub unsafe extern "C" fn __isblank_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19893    (c == ' ' as i32 || c == '\t' as i32) as i32
19894}
19895
19896#[no_mangle]
19897pub unsafe extern "C" fn __iscntrl_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19898    (c < 0x20 || c == 0x7f) as i32
19899}
19900
19901#[no_mangle]
19902pub unsafe extern "C" fn __isdigit_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19903    (c >= '0' as i32 && c <= '9' as i32) as i32
19904}
19905
19906#[no_mangle]
19907pub unsafe extern "C" fn __isgraph_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19908    (c > 0x20 && c < 0x7f) as i32
19909}
19910
19911#[no_mangle]
19912pub unsafe extern "C" fn __islower_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19913    (c >= 'a' as i32 && c <= 'z' as i32) as i32
19914}
19915
19916#[no_mangle]
19917pub unsafe extern "C" fn __isprint_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19918    (c >= 0x20 && c < 0x7f) as i32
19919}
19920
19921#[no_mangle]
19922pub unsafe extern "C" fn __ispunct_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19923    (c >= 0x21 && c <= 0x2f || c >= 0x3a && c <= 0x40 || c >= 0x5b && c <= 0x60 || c >= 0x7b && c <= 0x7e) as i32
19924}
19925
19926#[no_mangle]
19927pub unsafe extern "C" fn __isspace_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19928    (c == ' ' as i32 || c >= 0x09 && c <= 0x0d) as i32
19929}
19930
19931#[no_mangle]
19932pub unsafe extern "C" fn __isupper_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19933    (c >= 'A' as i32 && c <= 'Z' as i32) as i32
19934}
19935
19936#[no_mangle]
19937pub unsafe extern "C" fn __isxdigit_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
19938    (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
19939}
19940
19941// ============================================================
19942// wide char locale functions
19943// ============================================================
19944
19945#[no_mangle]
19946pub unsafe extern "C" fn __iswalnum_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19947    (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
19948}
19949
19950#[no_mangle]
19951pub unsafe extern "C" fn __iswalpha_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19952    (c >= 'A' as u32 && c <= 'Z' as u32 || c >= 'a' as u32 && c <= 'z' as u32) as i32
19953}
19954
19955#[no_mangle]
19956pub unsafe extern "C" fn __iswblank_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19957    (c == ' ' as u32 || c == '\t' as u32) as i32
19958}
19959
19960#[no_mangle]
19961pub unsafe extern "C" fn __iswcntrl_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19962    (c < 0x20 || c == 0x7f) as i32
19963}
19964
19965#[no_mangle]
19966pub unsafe extern "C" fn __iswdigit_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19967    (c >= '0' as u32 && c <= '9' as u32) as i32
19968}
19969
19970#[no_mangle]
19971pub unsafe extern "C" fn __iswgraph_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19972    (c > 0x20 && c < 0x7f) as i32
19973}
19974
19975#[no_mangle]
19976pub unsafe extern "C" fn __iswlower_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19977    (c >= 'a' as u32 && c <= 'z' as u32) as i32
19978}
19979
19980#[no_mangle]
19981pub unsafe extern "C" fn __iswprint_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19982    (c >= 0x20 && c < 0x7f) as i32
19983}
19984
19985#[no_mangle]
19986pub unsafe extern "C" fn __iswpunct_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19987    (c >= 0x21 && c <= 0x2f || c >= 0x3a && c <= 0x40 || c >= 0x5b && c <= 0x60 || c >= 0x7b && c <= 0x7e) as i32
19988}
19989
19990#[no_mangle]
19991pub unsafe extern "C" fn __iswspace_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19992    (c == ' ' as u32 || c >= 0x09 && c <= 0x0d) as i32
19993}
19994
19995#[no_mangle]
19996pub unsafe extern "C" fn __iswupper_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
19997    (c >= 'A' as u32 && c <= 'Z' as u32) as i32
19998}
19999
20000#[no_mangle]
20001pub unsafe extern "C" fn __iswxdigit_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20002    (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
20003}
20004
20005#[no_mangle]
20006pub unsafe extern "C" fn __iswctype_l(c: u32, ctype: u32, _loc: *mut core::ffi::c_void) -> i32 {
20007    crate::iswctype(c as wint_t, ctype as wctype_t)
20008}
20009
20010#[no_mangle]
20011pub unsafe extern "C" fn __towlower_l(c: u32, _loc: *mut core::ffi::c_void) -> u32 {
20012    crate::towlower(c)
20013}
20014
20015#[no_mangle]
20016pub unsafe extern "C" fn __towupper_l(c: u32, _loc: *mut core::ffi::c_void) -> u32 {
20017    crate::towupper(c)
20018}
20019
20020#[no_mangle]
20021pub unsafe extern "C" fn __towctrans_l(c: u32, _trans: u32, _loc: *mut core::ffi::c_void) -> u32 {
20022    c
20023}
20024
20025// ============================================================
20026// _r functions
20027// ============================================================
20028
20029// ============================================================
20030// stdio internal functions
20031// ============================================================
20032
20033// ============================================================
20034// Misc functions
20035// ============================================================
20036
20037#[no_mangle]
20038pub 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) {
20039    crate::write(2, b"Assertion failed: ".as_ptr() as *const core::ffi::c_void, 18);
20040    if !expr.is_null() { crate::write(2, expr as *const core::ffi::c_void, crate::strlen(expr)); }
20041    crate::write(2, b" (".as_ptr() as *const core::ffi::c_void, 2);
20042    if !file.is_null() { crate::write(2, file as *const core::ffi::c_void, crate::strlen(file)); }
20043    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20044    let mut n = line as usize;
20045    let mut digits: [u8; 32] = [0; 32];
20046    let mut di = 0;
20047    if n == 0 { digits[0] = 0; di = 1; }
20048    while n > 0 && di < 32 { digits[di] = (n % 10) as u8; n /= 10; di += 1; }
20049    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); }
20050    crate::write(2, b")".as_ptr() as *const core::ffi::c_void, 1);
20051    if !func.is_null() { crate::write(2, func as *const core::ffi::c_void, crate::strlen(func)); }
20052    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20053    crate::abort()
20054}
20055
20056#[no_mangle]
20057pub unsafe extern "C" fn at_quick_exit(_func: Option<unsafe extern "C" fn()>) -> i32 {
20058    // Register for quick exit - simplified
20059    0
20060}
20061
20062#[no_mangle]
20063pub unsafe extern "C" fn brk(addr: *mut u8) -> i32 {
20064    syscall_ret(<Arch as Syscalls>::syscall1(sysno(12, 214), addr as i64)) as i32
20065}
20066
20067#[no_mangle]
20068pub 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 {
20069    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
20070}
20071
20072#[no_mangle]
20073pub unsafe extern "C" fn ctermid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
20074    static mut BUF: [core::ffi::c_char; 20] = [0; 20];
20075    let dst = if s.is_null() { BUF.as_mut_ptr() } else { s };
20076    let src = b"/dev/tty\0".as_ptr() as *const core::ffi::c_char;
20077    let mut i = 0;
20078    while i < 9 { *dst.add(i) = *src.add(i); i += 1; }
20079    dst
20080}
20081
20082#[no_mangle]
20083pub unsafe extern "C" fn delete_module(name: *const core::ffi::c_char, flags: u32) -> i32 {
20084    syscall_ret(<Arch as Syscalls>::syscall2(SYS_DELETE_MODULE, name as i64, flags as i64)) as i32
20085}
20086
20087
20088
20089
20090
20091#[no_mangle]
20092pub unsafe extern "C" fn __duplocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
20093    loc
20094}
20095
20096#[no_mangle]
20097pub unsafe extern "C" fn euidaccess(pathname: *const core::ffi::c_char, mode: i32) -> i32 {
20098    faccessat(AT_FDCWD, pathname, mode, 0x200)
20099}
20100
20101#[no_mangle]
20102pub unsafe extern "C" fn fgetln(f: *mut core::ffi::c_void, lenp: *mut usize) -> *mut core::ffi::c_char {
20103    static mut BUF: *mut core::ffi::c_char = core::ptr::null_mut();
20104    static mut CAP: usize = 0;
20105    let n = getline(&raw mut BUF, &raw mut CAP, f as *mut FILE);
20106    if n <= 0 {
20107        if !lenp.is_null() { *lenp = 0; }
20108        return core::ptr::null_mut();
20109    }
20110    if !lenp.is_null() { *lenp = n as usize; }
20111    BUF
20112}
20113
20114#[no_mangle]
20115pub unsafe extern "C" fn fgetws(ws: *mut u32, n: i32, f: *mut core::ffi::c_void) -> *mut u32 {
20116    let mut i = 0;
20117    while i < n - 1 {
20118        let c = getwc(f as *mut core::ffi::c_void);
20119        if c == 0 { break; }
20120        *ws.add(i as usize) = c;
20121        i += 1;
20122        if c == '\n' as u32 { break; }
20123    }
20124    *ws.add(i as usize) = 0;
20125    if i == 0 { core::ptr::null_mut() } else { ws }
20126}
20127
20128#[no_mangle]
20129pub 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 {
20130    if !label.is_null() { crate::write(2, label as *const core::ffi::c_void, crate::strlen(label)); }
20131    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20132    if !text.is_null() { crate::write(2, text as *const core::ffi::c_void, crate::strlen(text)); }
20133    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20134    0
20135}
20136
20137#[no_mangle]
20138pub unsafe extern "C" fn ftime(tp: *mut core::ffi::c_void) -> i32 {
20139    let mut tv: timeval = core::mem::zeroed();
20140    if gettimeofday(&mut tv, core::ptr::null_mut()) == 0 {
20141        let tb = tp as *mut Timeb;
20142        (*tb).time = tv.tv_sec;
20143        (*tb).millitm = (tv.tv_usec / 1000) as u16;
20144        (*tb).timezone = 0;
20145        (*tb).dstflag = 0;
20146        0
20147    } else {
20148        -1
20149    }
20150}
20151
20152#[no_mangle]
20153pub unsafe extern "C" fn getdents(fd: i32, dirp: *mut u8, count: usize) -> isize {
20154    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, dirp as i64, count as i64)) as isize
20155}
20156
20157#[no_mangle]
20158pub unsafe extern "C" fn gethostid() -> i64 {
20159    // Read from /proc/sys/kernel/random/boot_id or similar
20160    let fd = crate::open(b"/proc/sys/kernel/random/boot_id\0".as_ptr() as *const core::ffi::c_char, 0, 0);
20161    if fd < 0 { return 0; }
20162    let mut buf: [u8; 64] = [0; 64];
20163    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
20164    crate::close(fd);
20165    if n <= 0 { return 0; }
20166    buf[n as usize] = 0;
20167    crate::strtol(buf.as_ptr() as *const core::ffi::c_char, core::ptr::null_mut(), 16)
20168}
20169
20170#[no_mangle]
20171pub unsafe extern "C" fn getpass(prompt: *const core::ffi::c_char) -> *mut core::ffi::c_char {
20172    static mut BUF: [core::ffi::c_char; 256] = [0; 256];
20173    // Write prompt
20174    crate::write(2, prompt as *const core::ffi::c_void, crate::strlen(prompt));
20175    // Read password (simplified - no echo disable)
20176    let n = crate::read(0, BUF.as_mut_ptr() as *mut core::ffi::c_void, 255);
20177    if n > 0 {
20178        let end = if BUF[(n - 1) as usize] == '\n' as c_char { n - 1 } else { n };
20179        BUF[end as usize] = 0;
20180    } else {
20181        BUF[0] = 0;
20182    }
20183    BUF.as_mut_ptr()
20184}
20185
20186#[no_mangle]
20187pub 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 {
20188    let s = *optionp;
20189    if s.is_null() { return -1; }
20190    // Find end of suboption
20191    let mut end = s;
20192    while *end != 0 && *end != ',' as c_char && *end != '=' as c_char { end = end.add(1); }
20193    let eq = *end == '=' as c_char;
20194    if eq { *end = 0; *valuep = end.add(1); }
20195    // Find matching token
20196    let mut i = 0;
20197    loop {
20198        let tok = *tokens.add(i);
20199        if tok.is_null() { break; }
20200        if crate::strcmp(s as *const u8, tok as *const u8) == 0 {
20201            // Skip to next option
20202    while *end != 0 && *end != ',' as c_char { end = end.add(1); }
20203            if *end == ',' as c_char { end = end.add(1); }
20204            *optionp = end;
20205            return i as i32;
20206        }
20207        i += 1;
20208    }
20209    -1
20210}
20211
20212#[no_mangle]
20213pub unsafe extern "C" fn getw(f: *mut core::ffi::c_void) -> i32 {
20214    let c0 = getc(f as *mut FILE);
20215    if c0 < 0 { return -1; }
20216    let c1 = getc(f as *mut FILE);
20217    if c1 < 0 { return -1; }
20218    let c2 = getc(f as *mut FILE);
20219    if c2 < 0 { return -1; }
20220    let c3 = getc(f as *mut FILE);
20221    if c3 < 0 { return -1; }
20222    (c0 | (c1 << 8) | (c2 << 16) | (c3 << 24)) as i32
20223}
20224
20225#[no_mangle]
20226pub unsafe extern "C" fn getwc(f: *mut core::ffi::c_void) -> u32 {
20227    getc(f as *mut FILE) as u32
20228}
20229
20230#[no_mangle]
20231pub unsafe extern "C" fn init_module(module_image: *mut u8, len: usize, param_values: *const core::ffi::c_char) -> i32 {
20232    syscall_ret(<Arch as Syscalls>::syscall3(SYS_INIT_MODULE, module_image as i64, len as i64, param_values as i64)) as i32
20233}
20234
20235
20236
20237#[no_mangle]
20238pub unsafe extern "C" fn issetugid() -> i32 {
20239    let ruid = crate::getuid();
20240    let euid = crate::geteuid();
20241    let rgid = crate::getgid();
20242    let egid = crate::getegid();
20243    (ruid != euid || rgid != egid) as i32
20244}
20245
20246// ============================================================
20247// poll functions
20248// ============================================================
20249
20250#[repr(C)]
20251struct PollTimespec {
20252    tv_sec: i64,
20253    tv_nsec: i64,
20254}
20255
20256#[no_mangle]
20257pub unsafe extern "C" fn poll(fds: *mut core::ffi::c_void, nfds: u32, timeout: i32) -> i32 {
20258    #[cfg(target_arch = "x86_64")]
20259    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_POLL, fds as i64, nfds as i64, timeout as i64)) as i32 }
20260    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
20261    {
20262        // poll(2) does not exist on these architectures.  ppoll(2) takes a
20263        // struct timespec, not a millisecond count; passing the integer
20264        // directly made poll(..., 0) wait forever.
20265        let mut ts = PollTimespec { tv_sec: 0, tv_nsec: 0 };
20266        let ts_ptr = if timeout < 0 {
20267            core::ptr::null()
20268        } else {
20269            ts.tv_sec = (timeout / 1000) as i64;
20270            ts.tv_nsec = ((timeout % 1000) as i64) * 1_000_000;
20271            &ts as *const PollTimespec as *const core::ffi::c_void
20272        };
20273        syscall_ret(<Arch as Syscalls>::syscall5(
20274            SYS_PPOLL,
20275            fds as i64,
20276            nfds as i64,
20277            ts_ptr as i64,
20278            0,
20279            8,
20280        )) as i32
20281    }
20282}
20283
20284#[no_mangle]
20285pub unsafe extern "C" fn ppoll(fds: *mut core::ffi::c_void, nfds: u32, timeout: *const core::ffi::c_void, sigmask: *const u64) -> i32 {
20286    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PPOLL, fds as i64, nfds as i64, timeout as i64, sigmask as i64, 8)) as i32
20287}
20288
20289#[repr(C)]
20290struct PselectSigmask {
20291    ss: *const u64,
20292    ss_len: usize,
20293}
20294
20295#[no_mangle]
20296pub 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 {
20297    // pselect6 takes a { sigset_t *, size_t } pair, not the sigset pointer.
20298    // GNU make blocks SIGCHLD and depends on this temporary mask, so passing
20299    // the pointer directly deadlocks parallel builds.
20300    let arg = PselectSigmask {
20301        ss: sigmask,
20302        ss_len: core::mem::size_of::<SigSetT>(),
20303    };
20304    let arg_ptr = if sigmask.is_null() {
20305        0
20306    } else {
20307        &arg as *const PselectSigmask as i64
20308    };
20309    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
20310}
20311
20312// ============================================================
20313// realpath function
20314// ============================================================
20315
20316// ============================================================
20317// quick_exit function
20318// ============================================================
20319
20320#[no_mangle]
20321pub unsafe extern "C" fn quick_exit(status: i32) -> ! {
20322    crate::_exit(status)
20323}
20324
20325// ============================================================
20326// stat functions
20327// ============================================================
20328
20329#[no_mangle]
20330pub unsafe extern "C" fn lstat(path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
20331    let r = <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, buf as i64, 0x100);
20332    if r < 0 {
20333        ERRNO!() = (-r) as c_int;
20334        -1
20335    } else {
20336        0
20337    }
20338}
20339
20340#[no_mangle]
20341pub unsafe extern "C" fn __xstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
20342    crate::stat(path, buf as *mut Stat)
20343}
20344
20345#[no_mangle]
20346pub unsafe extern "C" fn __lxstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
20347    crate::lstat(path, buf)
20348}
20349
20350#[no_mangle]
20351pub unsafe extern "C" fn __fxstat(_ver: i32, fd: i32, buf: *mut core::ffi::c_void) -> i32 {
20352    crate::fstat(fd, buf as *mut Stat)
20353}
20354
20355#[no_mangle]
20356pub unsafe extern "C" fn __fxstatat(_ver: i32, _dirfd: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void, _flags: i32) -> i32 {
20357    crate::stat(path, buf as *mut Stat)
20358}
20359
20360// ============================================================
20361// mempcpy function
20362// ============================================================
20363
20364#[no_mangle]
20365pub unsafe extern "C" fn mempcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8 {
20366    core::ptr::copy_nonoverlapping(src, dest, n);
20367    dest.add(n)
20368}
20369
20370// ============================================================
20371// mktemp functions
20372// ============================================================
20373
20374#[no_mangle]
20375pub unsafe extern "C" fn mkostemp(template: *mut core::ffi::c_char, _flags: i32) -> i32 {
20376    mkstemp(template)
20377}
20378
20379#[no_mangle]
20380pub unsafe extern "C" fn mkstemps(template: *mut core::ffi::c_char, suffixlen: i32) -> i32 {
20381    mkstemps_impl(template, suffixlen)
20382}
20383
20384// ============================================================
20385// system functions
20386// ============================================================
20387
20388#[no_mangle]
20389pub unsafe extern "C" fn ptrace(request: i32, mut args: ...) -> i64 {
20390    let pid = args.next_arg::<c_long>();
20391    let addr = args.next_arg::<c_long>();
20392    let data = args.next_arg::<c_long>();
20393    // PEEKTEXT/PEEKDATA/PEEKUSER write the result through the data pointer
20394    // (the kernel returns EFAULT for a NULL pointer), so supply a local slot.
20395    if (1..=3).contains(&request) {
20396        let mut result: c_long = 0;
20397        let r = <Arch as Syscalls>::syscall4(
20398            sysno(101, 117),
20399            request as i64,
20400            pid,
20401            addr,
20402            &mut result as *mut c_long as i64,
20403        );
20404        if r < 0 {
20405            ERRNO!() = (-r) as c_int;
20406            return -1;
20407        }
20408        return result;
20409    }
20410    syscall_ret(<Arch as Syscalls>::syscall4(sysno(101, 117), request as i64, pid, addr, data))
20411}
20412
20413#[no_mangle]
20414pub unsafe extern "C" fn personality(persona: u64) -> i64 {
20415    <Arch as Syscalls>::syscall1(sysno(135, 92), persona as i64)
20416}
20417
20418#[no_mangle]
20419pub unsafe extern "C" fn reboot(cmd: c_int) -> i32 {
20420    // musl's public API is reboot(cmd), not the four-argument syscall.
20421    syscall_ret(<Arch as Syscalls>::syscall3(
20422        SYS_REBOOT,
20423        0xfee1dead,
20424        672274793,
20425        cmd as i64,
20426    )) as i32
20427}
20428
20429#[no_mangle]
20430pub unsafe extern "C" fn pivot_root(new_root: *const core::ffi::c_char, put_old: *const core::ffi::c_char) -> i32 {
20431    syscall_ret(<Arch as Syscalls>::syscall2(SYS_PIVOT_ROOT, new_root as i64, put_old as i64)) as i32
20432}
20433
20434#[no_mangle]
20435pub 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 {
20436    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
20437}
20438
20439#[no_mangle]
20440pub unsafe extern "C" fn umount(target: *const core::ffi::c_char) -> i32 {
20441    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, 0)) as i32
20442}
20443
20444#[no_mangle]
20445pub unsafe extern "C" fn umount2(target: *const core::ffi::c_char, flags: i32) -> i32 {
20446    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, flags as i64)) as i32
20447}
20448
20449// ============================================================
20450// resolver functions
20451// ============================================================
20452
20453
20454// ============================================================
20455// signal/error functions
20456// ============================================================
20457
20458#[no_mangle]
20459pub unsafe extern "C" fn psiginfo(_pinfo: *const core::ffi::c_void, s: *const core::ffi::c_char) {
20460    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
20461    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20462}
20463
20464#[no_mangle]
20465pub unsafe extern "C" fn psignal(sig: i32, s: *const core::ffi::c_char) {
20466    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
20467    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20468    crate::write(2, strsignal(sig) as *const core::ffi::c_void, crate::strlen(strsignal(sig)));
20469    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20470}
20471
20472#[no_mangle]
20473pub unsafe extern "C" fn strsignal(sig: c_int) -> *const c_char {
20474    static NAMES: [&[u8]; 32] = [
20475        b"Unknown signal\0",
20476        b"Hangup\0",
20477        b"Interrupt\0",
20478        b"Quit\0",
20479        b"Illegal instruction\0",
20480        b"Trace/breakpoint trap\0",
20481        b"Aborted\0",
20482        b"Bus error\0",
20483        b"Floating point exception\0",
20484        b"Killed\0",
20485        b"User defined signal 1\0",
20486        b"Segmentation fault\0",
20487        b"User defined signal 2\0",
20488        b"Broken pipe\0",
20489        b"Alarm clock\0",
20490        b"Terminated\0",
20491        b"Stack fault\0",
20492        b"Child process status\0",
20493        b"Continued\0",
20494        b"Stopped (signal)\0",
20495        b"Stopped\0",
20496        b"Stopped (tty input)\0",
20497        b"Stopped (tty output)\0",
20498        b"Urgent I/O condition\0",
20499        b"CPU time limit exceeded\0",
20500        b"File size limit exceeded\0",
20501        b"Virtual timer expired\0",
20502        b"Profiling timer expired\0",
20503        b"Window changed\0",
20504        b"I/O possible\0",
20505        b"Power failure\0",
20506        b"Bad system call\0",
20507    ];
20508    static mut RT_BUF: [c_char; 32] = [0; 32];
20509    if sig > 0 && sig < 32 {
20510        return NAMES[sig as usize].as_ptr() as *const c_char;
20511    }
20512    if sig >= 32 && sig < 65 {
20513        let mut o = 0usize;
20514        for &c in b"Real-time signal \0" {
20515            if c == 0 { break; }
20516            RT_BUF[o] = c as c_char;
20517            o += 1;
20518        }
20519        let mut v = (sig - 32) as u32;
20520        let mut digits = [0u8; 10];
20521        let mut d = 0usize;
20522        if v == 0 { digits[0] = b'0'; d = 1; }
20523        while v > 0 { digits[d] = b'0' + (v % 10) as u8; v /= 10; d += 1; }
20524        while d > 0 { d -= 1; RT_BUF[o] = digits[d] as c_char; o += 1; }
20525        RT_BUF[o] = 0;
20526        return RT_BUF.as_ptr();
20527    }
20528    b"Unknown signal\0".as_ptr() as *const c_char
20529}
20530
20531#[no_mangle]
20532pub unsafe extern "C" fn __strerror_l(errnum: i32, _loc: *mut core::ffi::c_void) -> *const core::ffi::c_char {
20533    crate::strerror(errnum)
20534}
20535
20536// ============================================================
20537// preadv functions
20538// ============================================================
20539
20540#[no_mangle]
20541pub unsafe extern "C" fn preadv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
20542    // preadv takes a 64-bit offset split into pos_l/pos_h on x86_64 and the
20543    // generic ABI; passing only pos_l leaves the high half undefined.
20544    syscall_ret(<Arch as Syscalls>::syscall5(
20545        sysno(295, 69),
20546        fd as i64,
20547        iov as i64,
20548        iovcnt as i64,
20549        offset,
20550        offset >> 32,
20551    )) as isize
20552}
20553
20554#[no_mangle]
20555pub unsafe extern "C" fn pwritev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
20556    syscall_ret(<Arch as Syscalls>::syscall5(
20557        sysno(296, 70),
20558        fd as i64,
20559        iov as i64,
20560        iovcnt as i64,
20561        offset,
20562        offset >> 32,
20563    )) as isize
20564}
20565
20566#[no_mangle]
20567pub unsafe extern "C" fn preadv2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
20568    // x86_64/generic preadv2 split the 64-bit offset into pos_l/pos_h and
20569    // take the flags as the sixth argument.
20570    syscall_ret(<Arch as Syscalls>::syscall6(
20571        sysno(327, 286),
20572        fd as i64,
20573        iov as i64,
20574        iovcnt as i64,
20575        offset,
20576        offset >> 32,
20577        flags as i64,
20578    )) as isize
20579}
20580
20581#[no_mangle]
20582pub unsafe extern "C" fn pwritev2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
20583    syscall_ret(<Arch as Syscalls>::syscall6(
20584        sysno(328, 287),
20585        fd as i64,
20586        iov as i64,
20587        iovcnt as i64,
20588        offset,
20589        offset >> 32,
20590        flags as i64,
20591    )) as isize
20592}
20593
20594// ============================================================
20595// nice function
20596// ============================================================
20597
20598#[no_mangle]
20599pub unsafe extern "C" fn nice(inc: i32) -> i32 {
20600    let mut prio = inc;
20601    if inc > -40 && inc < 40 {
20602        prio += getpriority(0, 0);
20603    }
20604    if prio > 19 { prio = 19; }
20605    if prio < -20 { prio = -20; }
20606    if setpriority(0, 0, prio) != 0 {
20607        if ERRNO!() == 13 { ERRNO!() = 1; } // EACCES -> EPERM, as musl does
20608        return -1;
20609    }
20610    prio
20611}
20612
20613// ============================================================
20614// misc functions
20615// ============================================================
20616
20617#[no_mangle]
20618pub unsafe extern "C" fn l64a(value: i64) -> *mut core::ffi::c_char {
20619    static mut BUF: [core::ffi::c_char; 7] = [0; 7];
20620    let mut v = value as u64;
20621    let mut i = 0;
20622    while v > 0 && i < 6 {
20623        let c = (v & 0x3f) as u8;
20624        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;
20625        v >>= 6;
20626        i += 1;
20627    }
20628    BUF[i] = 0;
20629    BUF.as_mut_ptr()
20630}
20631
20632#[no_mangle]
20633pub unsafe extern "C" fn lchmod(path: *const core::ffi::c_char, mode: u32) -> i32 {
20634    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FCHMODAT, AT_FDCWD as i64, path as i64, mode as i64, 0x100)) as i32
20635}
20636
20637#[no_mangle]
20638pub unsafe extern "C" fn lutimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
20639    utimensat(AT_FDCWD, filename, times as *const timespec, 0x100)
20640}
20641
20642#[no_mangle]
20643pub unsafe extern "C" fn mknod(pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
20644    #[cfg(target_arch = "x86_64")]
20645    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKNOD, pathname as i64, mode as i64, dev as i64)) as i32 }
20646    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
20647    {
20648        syscall_ret(<Arch as Syscalls>::syscall4(SYS_MKNODAT, AT_FDCWD as i64, pathname as i64, mode as i64, dev as i64)) as i32
20649    }
20650}
20651
20652#[no_mangle]
20653pub unsafe extern "C" fn memfd_create(name: *const core::ffi::c_char, flags: u32) -> i32 {
20654    syscall_ret(<Arch as Syscalls>::syscall2(sysno(319, 279), name as i64, flags as i64)) as i32
20655}
20656
20657#[no_mangle]
20658pub unsafe extern "C" fn mlock2(addr: *const core::ffi::c_void, len: usize, flags: u32) -> i32 {
20659    syscall_ret(<Arch as Syscalls>::syscall3(sysno(325, 284), addr as i64, len as i64, flags as i64)) as i32
20660}
20661
20662
20663
20664#[no_mangle]
20665pub unsafe extern "C" fn remap_file_pages(addr: *mut core::ffi::c_void, size: usize, prot: i32, pgoff: usize, flags: u32) -> i32 {
20666    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
20667}
20668
20669// ============================================================
20670// nan functions
20671// ============================================================
20672
20673#[no_mangle]
20674pub unsafe extern "C" fn nan(_tagp: *const core::ffi::c_char) -> f64 {
20675    f64::NAN
20676}
20677
20678#[no_mangle]
20679pub unsafe extern "C" fn nanf(_tagp: *const core::ffi::c_char) -> f32 {
20680    f32::NAN
20681}
20682
20683// ============================================================
20684// Remaining symbols - batch 1
20685// ============================================================
20686
20687#[no_mangle]
20688pub unsafe extern "C" fn __lgammal_r(x: f64, signgamp: *mut i32) -> f64 {
20689    *signgamp = 1;
20690    lgamma(x)
20691}
20692
20693#[no_mangle]
20694pub unsafe extern "C" fn __libc_current_sigrtmax() -> i32 {
20695    64
20696}
20697
20698#[no_mangle]
20699pub unsafe extern "C" fn _longjmp(env: *mut core::ffi::c_void, val: i32) {
20700    crate::longjmp(env as *mut u64, val)
20701}
20702
20703#[no_mangle]
20704pub unsafe extern "C" fn __newlocale(_mask: i32, _name: *const core::ffi::c_char, base: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
20705    base
20706}
20707
20708#[no_mangle]
20709pub unsafe extern "C" fn __nl_langinfo(_item: i32) -> *mut core::ffi::c_char {
20710    b"\0".as_ptr() as *mut core::ffi::c_char
20711}
20712
20713#[no_mangle]
20714pub unsafe extern "C" fn __nl_langinfo_l(_item: i32, _loc: *mut core::ffi::c_void) -> *mut core::ffi::c_char {
20715    b"\0".as_ptr() as *mut core::ffi::c_char
20716}
20717
20718#[no_mangle]
20719pub unsafe extern "C" fn ns_get16(cp: *const u8) -> u16 {
20720    ((*cp.add(0) as u16) << 8) | *cp.add(1) as u16
20721}
20722
20723#[no_mangle]
20724pub unsafe extern "C" fn ns_get32(cp: *const u8) -> u32 {
20725    ((*cp.add(0) as u32) << 24) | ((*cp.add(1) as u32) << 16) | ((*cp.add(2) as u32) << 8) | *cp.add(3) as u32
20726}
20727
20728#[no_mangle]
20729pub unsafe extern "C" fn ns_put16(s: u16, dst: *mut u8) {
20730    *dst.add(0) = (s >> 8) as u8;
20731    *dst.add(1) = (s & 0xff) as u8;
20732}
20733
20734#[no_mangle]
20735pub unsafe extern "C" fn ns_put32(l: u32, dst: *mut u8) {
20736    *dst.add(0) = (l >> 24) as u8;
20737    *dst.add(1) = ((l >> 16) & 0xff) as u8;
20738    *dst.add(2) = ((l >> 8) & 0xff) as u8;
20739    *dst.add(3) = (l & 0xff) as u8;
20740}
20741
20742#[no_mangle]
20743pub unsafe extern "C" fn posix_close(fd: i32) -> i32 {
20744    crate::close(fd)
20745}
20746
20747#[no_mangle]
20748pub unsafe extern "C" fn posix_openpt(flags: i32) -> i32 {
20749    crate::open(b"/dev/ptmx\0".as_ptr() as *const core::ffi::c_char, flags, 0)
20750}
20751
20752#[no_mangle]
20753pub unsafe extern "C" fn putw(w: i32, f: *mut core::ffi::c_void) {
20754    putc((w & 0xff) as i32, f as *mut FILE);
20755    putc(((w >> 8) & 0xff) as i32, f as *mut FILE);
20756    putc(((w >> 16) & 0xff) as i32, f as *mut FILE);
20757    putc(((w >> 24) & 0xff) as i32, f as *mut FILE);
20758}
20759
20760
20761
20762#[no_mangle]
20763pub unsafe extern "C" fn rand_r(seedp: *mut u32) -> i32 {
20764    let seed = (*seedp).wrapping_mul(1103515245).wrapping_add(12345);
20765    *seedp = seed;
20766    ((seed >> 16) & 0x7fff) as i32
20767}
20768
20769#[no_mangle]
20770pub unsafe extern "C" fn reallocarray(ptr: *mut core::ffi::c_void, nmemb: usize, size: usize) -> *mut core::ffi::c_void {
20771    let total = match nmemb.checked_mul(size) {
20772        Some(v) => v,
20773        None => { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
20774    };
20775    crate::realloc(ptr, total)
20776}
20777
20778#[no_mangle]
20779pub unsafe extern "C" fn __res_state() -> *mut core::ffi::c_void {
20780    static mut STATE: [u8; 512] = [0; 512];
20781    STATE.as_mut_ptr() as *mut core::ffi::c_void
20782}
20783
20784#[no_mangle]
20785pub unsafe extern "C" fn sbrk(increment: isize) -> *mut u8 {
20786    // musl does not support growing the break directly (malloc uses mmap);
20787    // sbrk(nonzero) always fails with ENOMEM.
20788    if increment != 0 {
20789        ERRNO!() = ENOMEM;
20790        return -1isize as usize as *mut u8;
20791    }
20792    <Arch as Syscalls>::syscall1(sysno(12, 214), 0) as *mut u8
20793}
20794
20795#[no_mangle]
20796pub unsafe extern "C" fn scalb(x: f64, exp: f64) -> f64 {
20797    if x.is_nan() || exp.is_nan() { return x * exp; }
20798    if !exp.is_finite() {
20799        let r = if exp > 0.0 { x * exp } else { x / (-exp) };
20800        if r.is_nan() && !x.is_nan() {
20801            feraiseexcept(FE_INVALID);
20802        }
20803        return r;
20804    }
20805    if libm::rint(exp) != exp {
20806        return __math_invalid(exp);
20807    }
20808    if exp > 65000.0 { return libm::scalbn(x, 65000); }
20809    if -exp > 65000.0 { return libm::scalbn(x, -65000); }
20810    libm::scalbn(x, exp as i32)
20811}
20812
20813#[no_mangle]
20814pub unsafe extern "C" fn scalbf(x: f32, exp: f32) -> f32 {
20815    if x.is_nan() || exp.is_nan() { return x * exp; }
20816    if !exp.is_finite() {
20817        let r = if exp > 0.0 { x * exp } else { x / (-exp) };
20818        if r.is_nan() && !x.is_nan() {
20819            feraiseexcept(FE_INVALID);
20820        }
20821        return r;
20822    }
20823    if libm::rintf(exp) != exp {
20824        return __math_invalidf(exp);
20825    }
20826    if exp > 65000.0 { return libm::scalbnf(x, 65000); }
20827    if -exp > 65000.0 { return libm::scalbnf(x, -65000); }
20828    libm::scalbnf(x, exp as i32)
20829}
20830
20831#[no_mangle]
20832pub unsafe extern "C" fn __sched_cpucount(setsize: usize, setp: *const u8) -> i32 {
20833    let mut count = 0;
20834    let mut i = 0;
20835    while i < setsize * 8 {
20836        if (*setp.add(i / 8) >> (i % 8)) & 1 != 0 { count += 1; }
20837        i += 1;
20838    }
20839    count
20840}
20841
20842
20843
20844#[no_mangle]
20845pub unsafe extern "C" fn select(nfds: i32, readfds: *mut u8, writefds: *mut u8, exceptfds: *mut u8, timeout: *mut core::ffi::c_void) -> i32 {
20846    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
20847}
20848
20849
20850
20851#[no_mangle]
20852pub unsafe extern "C" fn sendfile(out_fd: i32, in_fd: i32, offset: *mut i64, count: usize) -> isize {
20853    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
20854}
20855
20856
20857
20858
20859
20860#[no_mangle]
20861pub unsafe extern "C" fn __setjmp(env: *mut core::ffi::c_void) -> i32 {
20862    crate::setjmp(env as *mut u64)
20863}
20864
20865#[no_mangle]
20866pub unsafe extern "C" fn _setjmp(env: *mut core::ffi::c_void) -> i32 {
20867    crate::setjmp(env as *mut u64)
20868}
20869
20870#[no_mangle]
20871pub unsafe extern "C" fn setlinebuf(stream: *mut core::ffi::c_void) {
20872    setvbuf(stream as *mut FILE, core::ptr::null_mut(), 1, 0);
20873}
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889#[no_mangle]
20890pub unsafe extern "C" fn significand(x: f64) -> f64 {
20891    let bits = x.to_bits();
20892    let exp = ((bits >> 52) & 0x7ff) as i32;
20893    if exp == 0 || exp == 0x7ff { return x; }
20894    f64::from_bits((bits & 0x000fffffffffffff) | (1023u64 << 52))
20895}
20896
20897#[no_mangle]
20898pub unsafe extern "C" fn significandf(x: f32) -> f32 {
20899    let bits = x.to_bits();
20900    let exp = ((bits >> 23) & 0xff) as i32;
20901    if exp == 0 || exp == 0xff { return x; }
20902    f32::from_bits((bits & 0x007fffff) | (127u32 << 23))
20903}
20904
20905
20906
20907
20908
20909#[no_mangle]
20910pub unsafe extern "C" fn sigset(sig: i32, handler: usize) -> usize {
20911    // BSD/glibc-compatible sigset() is an alias for signal().
20912    signal(sig, handler)
20913}
20914
20915#[no_mangle]
20916pub unsafe extern "C" fn sincos(x: f64, sin: *mut f64, cos: *mut f64) {
20917    *sin = libm::sin(x);
20918    *cos = libm::cos(x);
20919}
20920
20921#[no_mangle]
20922pub unsafe extern "C" fn sincosf(x: f32, sin: *mut f32, cos: *mut f32) {
20923    *sin = libm::sinf(x);
20924    *cos = libm::cosf(x);
20925}
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935unsafe fn nd_ascii_lower(c: c_char) -> c_int {
20936    let b = c as u8;
20937    if b >= b'A' && b <= b'Z' { (b + 32) as c_int } else { b as c_int }
20938}
20939
20940unsafe fn nd_strncasecmp(s1: *const c_char, s2: *const c_char, n: usize) -> c_int {
20941    let mut i = 0usize;
20942    while i < n {
20943        let c1 = nd_ascii_lower(*s1.add(i));
20944        let c2 = nd_ascii_lower(*s2.add(i));
20945        if c1 != c2 || c1 == 0 { return c1 - c2; }
20946        i += 1;
20947    }
20948    0
20949}
20950
20951#[no_mangle]
20952pub unsafe extern "C" fn strcasecmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> i32 {
20953    nd_strncasecmp(s1, s2, usize::MAX)
20954}
20955
20956#[no_mangle]
20957pub 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 {
20958    nd_strncasecmp(s1, s2, usize::MAX)
20959}
20960
20961#[no_mangle]
20962pub unsafe extern "C" fn strcasestr(haystack: *const core::ffi::c_char, needle: *const core::ffi::c_char) -> *mut core::ffi::c_char {
20963    let nlen = crate::strlen(needle);
20964    if nlen == 0 { return haystack as *mut core::ffi::c_char; }
20965    let mut i = 0;
20966    loop {
20967        let h = haystack.add(i);
20968        if *h == 0 { return core::ptr::null_mut(); }
20969        if crate::strncasecmp(h, needle, nlen) == 0 { return h as *mut core::ffi::c_char; }
20970        i += 1;
20971    }
20972}
20973
20974#[no_mangle]
20975pub 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 {
20976    crate::strcmp(s1 as *const u8, s2 as *const u8)
20977}
20978
20979#[no_mangle]
20980pub unsafe extern "C" fn strncasecmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char, n: usize) -> i32 {
20981    nd_strncasecmp(s1, s2, n)
20982}
20983
20984#[no_mangle]
20985pub 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 {
20986    nd_strncasecmp(s1, s2, n)
20987}
20988
20989#[no_mangle]
20990pub unsafe extern "C" fn strsep(stringp: *mut *mut core::ffi::c_char, delim: *const core::ffi::c_char) -> *mut core::ffi::c_char {
20991    let s = *stringp;
20992    if s.is_null() { return core::ptr::null_mut(); }
20993    let mut p = s;
20994    while *p != 0 {
20995        let mut d = delim;
20996        while *d != 0 {
20997            if *p == *d { *p = 0; *stringp = p.add(1); return s; }
20998            d = d.add(1);
20999        }
21000        p = p.add(1);
21001    }
21002    *stringp = core::ptr::null_mut();
21003    s
21004}
21005
21006#[no_mangle]
21007pub unsafe extern "C" fn strtoimax(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, base: i32) -> i64 {
21008    crate::strtol(nptr, endptr, base)
21009}
21010
21011#[no_mangle]
21012pub 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 {
21013    let mut s = if s.is_null() { *saveptr } else { s };
21014    if s.is_null() { return core::ptr::null_mut(); }
21015    // Skip leading delimiters
21016    while *s != 0 {
21017        let mut d = delim;
21018        let mut found = false;
21019        while *d != 0 {
21020            if *s == *d { found = true; break; }
21021            d = d.add(1);
21022        }
21023        if !found { break; }
21024        s = s.add(1);
21025    }
21026    if *s == 0 { *saveptr = s; return core::ptr::null_mut(); }
21027    let start = s;
21028    // Find end of token
21029    while *s != 0 {
21030        let mut d = delim;
21031        while *d != 0 {
21032            if *s == *d { *s = 0; *saveptr = s.add(1); return start; }
21033            d = d.add(1);
21034        }
21035        s = s.add(1);
21036    }
21037    *saveptr = s;
21038    start
21039}
21040
21041#[no_mangle]
21042pub unsafe extern "C" fn strtoumax(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, base: i32) -> u64 {
21043    crate::strtoul(nptr, endptr, base) as u64
21044}
21045
21046#[no_mangle]
21047pub 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 {
21048    crate::strlcpy(dest as *mut u8, src as *const u8, n)
21049}
21050
21051#[no_mangle]
21052pub unsafe extern "C" fn swab(src: *const u8, dest: *mut u8, nbytes: isize) {
21053    let mut i = 0;
21054    while i + 1 < nbytes {
21055        let a = *src.add(i as usize);
21056        let b = *src.add(i as usize + 1);
21057        *dest.add(i as usize) = b;
21058        *dest.add(i as usize + 1) = a;
21059        i += 2;
21060    }
21061}
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073#[no_mangle]
21074pub unsafe extern "C" fn __tolower_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
21075    if c >= 'A' as i32 && c <= 'Z' as i32 { c + 32 } else { c }
21076}
21077
21078#[no_mangle]
21079pub unsafe extern "C" fn __toupper_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
21080    if c >= 'a' as i32 && c <= 'z' as i32 { c - 32 } else { c }
21081}
21082
21083#[no_mangle]
21084pub unsafe extern "C" fn ulimit(cmd: c_int, mut args: ...) -> c_long {
21085    let mut rl: Rlimit = core::mem::zeroed();
21086    if getrlimit(RLIMIT_FSIZE, &mut rl) != 0 { return -1; }
21087    if cmd == 2 {
21088        let val = args.next_arg::<c_long>();
21089        rl.rlim_cur = 512u64.wrapping_mul(val as u64);
21090        if setrlimit(RLIMIT_FSIZE, &rl) != 0 { return -1; }
21091    }
21092    (rl.rlim_cur / 512) as c_long
21093}
21094
21095#[repr(C)]
21096struct UtsName {
21097    sysname: [u8; 65],
21098    nodename: [u8; 65],
21099    release: [u8; 65],
21100    version: [u8; 65],
21101    machine: [u8; 65],
21102    domainname: [u8; 65],
21103}
21104
21105#[no_mangle]
21106pub unsafe extern "C" fn uname(buf: *mut c_void) -> c_int {
21107    // Let the kernel validate the user pointer: an invalid but non-null
21108    // address must produce EFAULT instead of a fault in a local copy.
21109    let r = <Arch as Syscalls>::syscall1(SYS_UNAME, buf as i64);
21110    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
21111    0
21112}
21113
21114#[no_mangle]
21115pub unsafe extern "C" fn unshare(flags: i32) -> i32 {
21116    let r = <Arch as Syscalls>::syscall1(SYS_UNSHARE, flags as i64);
21117    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21118}
21119
21120#[no_mangle]
21121pub unsafe extern "C" fn updwtmpx(wtmpx_file: *const core::ffi::c_char, utx: *const core::ffi::c_void) {
21122    updwtmp(wtmpx_file, utx)
21123}
21124
21125#[no_mangle]
21126pub unsafe extern "C" fn __uselocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
21127    loc
21128}
21129
21130#[repr(C)]
21131pub struct Utimbuf { actime: i64, modtime: i64 }
21132
21133#[no_mangle]
21134pub unsafe extern "C" fn utime(filename: *const c_char, times: *const Utimbuf) -> c_int {
21135    if times.is_null() {
21136        return utimensat(AT_FDCWD, filename, core::ptr::null(), 0);
21137    }
21138    let ts = [
21139        timespec { tv_sec: (*times).actime, tv_nsec: 0 },
21140        timespec { tv_sec: (*times).modtime, tv_nsec: 0 },
21141    ];
21142    utimensat(AT_FDCWD, filename, ts.as_ptr(), 0)
21143}
21144
21145#[no_mangle]
21146pub unsafe extern "C" fn vhangup() -> c_int {
21147    let r = <Arch as Syscalls>::syscall0(SYS_VHANGUP);
21148    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21149}
21150
21151#[no_mangle]
21152pub unsafe extern "C" fn vmsplice(fd: i32, iov: *const c_void, nr_segs: usize, flags: u32) -> isize {
21153    let r = <Arch as Syscalls>::syscall4(SYS_VMSPLICE, fd as i64, iov as i64, nr_segs as i64, flags as i64);
21154    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
21155}
21156
21157
21158
21159#[no_mangle]
21160pub unsafe extern "C" fn wait4(pid: i32, wstatus: *mut i32, options: i32, rusage: *mut core::ffi::c_void) -> i32 {
21161    syscall_ret(<Arch as Syscalls>::syscall4(SYS_WAIT4, pid as i64, wstatus as i64, options as i64, rusage as i64)) as i32
21162}
21163
21164#[no_mangle]
21165pub unsafe extern "C" fn waitid(idtype: i32, id: u32, infop: *mut core::ffi::c_void, options: i32) -> i32 {
21166    // The kernel takes a fifth rusage pointer; it must be NULL, not whatever
21167    // happens to be in r10.
21168    syscall_ret(<Arch as Syscalls>::syscall5(
21169        sysno(247, 95),
21170        idtype as i64,
21171        id as i64,
21172        infop as i64,
21173        options as i64,
21174        0,
21175    )) as i32
21176}
21177
21178#[no_mangle]
21179pub unsafe extern "C" fn __wcscoll_l(s1: *const u32, s2: *const u32, _loc: *mut core::ffi::c_void) -> i32 {
21180    crate::wcscmp(s1 as *const i32, s2 as *const i32)
21181}
21182
21183#[no_mangle]
21184pub unsafe extern "C" fn __wcsxfrm_l(dest: *mut u32, src: *const u32, n: usize, _loc: *mut core::ffi::c_void) -> usize {
21185    crate::wcscpy(dest as *mut i32, src as *const i32);
21186    n
21187}
21188
21189#[no_mangle]
21190pub unsafe extern "C" fn wcwidth(c: u32) -> i32 {
21191    if c == 0 { return 0; }
21192    if c < 32 || (c >= 0x7f && c < 0xa0) { return -1; }
21193    1
21194}
21195
21196
21197
21198
21199
21200// ============================================================
21201// Final missing symbols
21202// ============================================================
21203
21204
21205
21206#[no_mangle]
21207pub 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 {
21208    crate::strtod(nptr, endptr)
21209}
21210
21211#[no_mangle]
21212pub 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 {
21213    crate::strtof(nptr, endptr)
21214}
21215
21216#[no_mangle]
21217pub 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 {
21218    crate::strtod(nptr, endptr)
21219}
21220
21221// ============================================================
21222// Directory operations - real implementations
21223// ============================================================
21224
21225#[repr(C)]
21226struct linux_dirent64 {
21227    d_ino: u64,
21228    d_off: i64,
21229    d_reclen: u16,
21230    d_type: u8,
21231    d_name: [u8; 0], // flexible array
21232}
21233
21234// Directory streams used to be a process-wide singleton, which broke any
21235// nested opendir/readdir sequence (git, find, glob, ...). Each DIR now owns
21236// its fd and read buffer, like musl's __dirstream.
21237const DIR_BUF_SIZE: usize = 4096;
21238
21239#[repr(C)]
21240struct DirStream {
21241    fd: i32,
21242    pos: usize,
21243    len: usize,
21244    last_off: i64,
21245    buf: [u8; DIR_BUF_SIZE],
21246}
21247
21248unsafe fn dir_stream_new(fd: i32) -> *mut core::ffi::c_void {
21249    let ds = malloc(core::mem::size_of::<DirStream>()) as *mut DirStream;
21250    if ds.is_null() {
21251        crate::close(fd);
21252        ERRNO!() = ENOMEM;
21253        return core::ptr::null_mut();
21254    }
21255    core::ptr::write_bytes(ds, 0, 1);
21256    (*ds).fd = fd;
21257    ds as *mut core::ffi::c_void
21258}
21259
21260#[no_mangle]
21261pub unsafe extern "C" fn opendir(dirname: *const core::ffi::c_char) -> *mut core::ffi::c_void {
21262    let fd = openat(AT_FDCWD, dirname, O_DIRECTORY, 0); // O_RDONLY | O_DIRECTORY
21263    if fd < 0 { return core::ptr::null_mut(); }
21264    dir_stream_new(fd)
21265}
21266
21267#[no_mangle]
21268pub unsafe extern "C" fn closedir(dirp: *mut core::ffi::c_void) -> i32 {
21269    if dirp.is_null() { ERRNO!() = 22; return -1; }
21270    let ds = dirp as *mut DirStream;
21271    let r = crate::close((*ds).fd);
21272    free(dirp);
21273    r
21274}
21275
21276#[no_mangle]
21277pub unsafe extern "C" fn readdir(dirp: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
21278    if dirp.is_null() { ERRNO!() = 22; return core::ptr::null_mut(); }
21279    let ds = &mut *(dirp as *mut DirStream);
21280
21281    loop {
21282        if ds.pos >= ds.len {
21283            let nread = syscall_ret(<Arch as Syscalls>::syscall3(
21284                SYS_GETDENTS64,
21285                ds.fd as i64,
21286                ds.buf.as_mut_ptr() as i64,
21287                DIR_BUF_SIZE as i64,
21288            )) as isize;
21289            if nread <= 0 { return core::ptr::null_mut(); }
21290            ds.len = nread as usize;
21291            ds.pos = 0;
21292        }
21293
21294        let ent = ds.buf.as_ptr().add(ds.pos) as *const linux_dirent64;
21295        let ent_ref = &*ent;
21296        if ent_ref.d_reclen as usize == 0 {
21297            ds.len = 0;
21298            return core::ptr::null_mut();
21299        }
21300        ds.pos += ent_ref.d_reclen as usize;
21301        ds.last_off = ent_ref.d_off;
21302
21303        // Return a pointer into this stream's buffer (valid until next call).
21304        return ent as *mut core::ffi::c_void;
21305    }
21306}
21307
21308#[no_mangle]
21309pub 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 {
21310    let ent = readdir(dirp);
21311    if ent.is_null() {
21312        *result = core::ptr::null_mut();
21313    } else {
21314        *result = ent;
21315    }
21316    0
21317}
21318
21319#[no_mangle]
21320pub unsafe extern "C" fn seekdir(dirp: *mut core::ffi::c_void, loc: i64) {
21321    if dirp.is_null() { return; }
21322    let ds = &mut *(dirp as *mut DirStream);
21323    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, loc, 0);
21324    ds.pos = 0;
21325    ds.len = 0;
21326}
21327
21328#[no_mangle]
21329pub unsafe extern "C" fn telldir(dirp: *mut core::ffi::c_void) -> i64 {
21330    if dirp.is_null() { return -1; }
21331    (*(dirp as *mut DirStream)).last_off
21332}
21333
21334#[no_mangle]
21335pub unsafe extern "C" fn rewinddir(dirp: *mut core::ffi::c_void) {
21336    if dirp.is_null() { return; }
21337    let ds = &mut *(dirp as *mut DirStream);
21338    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, 0, 0);
21339    ds.pos = 0;
21340    ds.len = 0;
21341    ds.last_off = 0;
21342}
21343
21344#[no_mangle]
21345pub unsafe extern "C" fn dirfd(dirp: *mut core::ffi::c_void) -> i32 {
21346    if dirp.is_null() { ERRNO!() = 22; return -1; }
21347    (*(dirp as *mut DirStream)).fd
21348}
21349
21350// ============================================================
21351// Memory management - real implementations
21352// ============================================================
21353
21354#[no_mangle]
21355pub unsafe extern "C" fn mprotect(addr: *mut u8, len: usize, prot: i32) -> i32 {
21356    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MPROTECT, addr as i64, len as i64, prot as i64)) as i32
21357}
21358
21359#[no_mangle]
21360pub unsafe extern "C" fn msync(addr: *mut u8, len: usize, flags: i32) -> i32 {
21361    syscall_ret(<Arch as Syscalls>::syscall3(sysno(26, 227), addr as i64, len as i64, flags as i64)) as i32
21362}
21363
21364#[no_mangle]
21365pub unsafe extern "C" fn mlock(addr: *const u8, len: usize) -> i32 {
21366    syscall_ret(<Arch as Syscalls>::syscall2(sysno(149, 228), addr as i64, len as i64)) as i32
21367}
21368
21369#[no_mangle]
21370pub unsafe extern "C" fn munlock(addr: *const u8, len: usize) -> i32 {
21371    syscall_ret(<Arch as Syscalls>::syscall2(sysno(150, 229), addr as i64, len as i64)) as i32
21372}
21373
21374#[no_mangle]
21375pub unsafe extern "C" fn mlockall(flags: i32) -> i32 {
21376    syscall_ret(<Arch as Syscalls>::syscall1(sysno(151, 230), flags as i64)) as i32
21377}
21378
21379#[no_mangle]
21380pub unsafe extern "C" fn munlockall() -> i32 {
21381    syscall_ret(<Arch as Syscalls>::syscall0(sysno(152, 231))) as i32
21382}
21383
21384#[no_mangle]
21385pub unsafe extern "C" fn madvise(addr: *mut u8, len: usize, advice: i32) -> i32 {
21386    syscall_ret(<Arch as Syscalls>::syscall3(sysno(28, 233), addr as i64, len as i64, advice as i64)) as i32
21387}
21388
21389#[no_mangle]
21390pub unsafe extern "C" fn mincore(addr: *mut u8, len: usize, vec: *mut u8) -> i32 {
21391    syscall_ret(<Arch as Syscalls>::syscall3(sysno(27, 232), addr as i64, len as i64, vec as i64)) as i32
21392}
21393
21394// ============================================================
21395
21396// ============================================================
21397// Missing math functions
21398// ============================================================
21399
21400#[no_mangle]
21401pub unsafe extern "C" fn drem(x: f64, y: f64) -> f64 {
21402    remainder(x, y)
21403}
21404
21405#[no_mangle]
21406pub unsafe extern "C" fn dremf(x: f32, y: f32) -> f32 {
21407    remainderf(x, y)
21408}
21409
21410#[no_mangle]
21411pub unsafe extern "C" fn pow10(x: f64) -> f64 {
21412    libm::pow(10.0, x)
21413}
21414
21415#[no_mangle]
21416pub unsafe extern "C" fn pow10f(x: f32) -> f32 {
21417    libm::powf(10.0, x)
21418}
21419
21420#[no_mangle]
21421pub unsafe extern "C" fn pow10l(x: f64) -> f64 {
21422    libm::pow(10.0, x)
21423}
21424
21425#[no_mangle]
21426pub unsafe extern "C" fn isless(x: f64, y: f64) -> i32 {
21427    if x.is_nan() || y.is_nan() { 0 } else { (x < y) as i32 }
21428}
21429
21430#[no_mangle]
21431pub unsafe extern "C" fn islessf(x: f32, y: f32) -> i32 {
21432    if x.is_nan() || y.is_nan() { 0 } else { (x < y) as i32 }
21433}
21434
21435#[no_mangle]
21436pub unsafe extern "C" fn lgamma_r(x: f64, signgamp: *mut i32) -> f64 {
21437    lgamma_r_impl(x, signgamp)
21438}
21439
21440#[no_mangle]
21441pub unsafe extern "C" fn lgammaf_r(x: f32, signgamp: *mut i32) -> f32 {
21442    if x.is_nan() {
21443        if !signgamp.is_null() { *signgamp = 1; }
21444        return x;
21445    }
21446    if x == 0.0 {
21447        if !signgamp.is_null() { *signgamp = if x.is_sign_negative() { -1 } else { 1 }; }
21448        feraiseexcept(FE_DIVBYZERO);
21449        return f32::INFINITY;
21450    }
21451    let (r, sign) = libm::lgammaf_r(x);
21452    if !signgamp.is_null() { *signgamp = sign; }
21453    r
21454}
21455
21456#[no_mangle]
21457pub unsafe extern "C" fn lgammal_r(x: f64, signgamp: *mut i32) -> f64 {
21458    lgamma_r(x, signgamp)
21459}
21460
21461// ============================================================
21462// Comparison macros
21463// ============================================================
21464
21465#[no_mangle]
21466pub unsafe extern "C" fn islessequal(x: f64, y: f64) -> i32 {
21467    if x.is_nan() || y.is_nan() { 0 } else { (x <= y) as i32 }
21468}
21469
21470#[no_mangle]
21471pub unsafe extern "C" fn islessequalf(x: f32, y: f32) -> i32 {
21472    if x.is_nan() || y.is_nan() { 0 } else { (x <= y) as i32 }
21473}
21474
21475#[no_mangle]
21476pub unsafe extern "C" fn islessgreater(x: f64, y: f64) -> i32 {
21477    if x.is_nan() || y.is_nan() { 0 } else { (x < y || x > y) as i32 }
21478}
21479
21480#[no_mangle]
21481pub unsafe extern "C" fn islessgreaterf(x: f32, y: f32) -> i32 {
21482    if x.is_nan() || y.is_nan() { 0 } else { (x < y || x > y) as i32 }
21483}
21484
21485#[no_mangle]
21486pub unsafe extern "C" fn isgreater(x: f64, y: f64) -> i32 {
21487    if x.is_nan() || y.is_nan() { 0 } else { (x > y) as i32 }
21488}
21489
21490#[no_mangle]
21491pub unsafe extern "C" fn isgreaterf(x: f32, y: f32) -> i32 {
21492    if x.is_nan() || y.is_nan() { 0 } else { (x > y) as i32 }
21493}
21494
21495#[no_mangle]
21496pub unsafe extern "C" fn isgreaterequal(x: f64, y: f64) -> i32 {
21497    if x.is_nan() || y.is_nan() { 0 } else { (x >= y) as i32 }
21498}
21499
21500#[no_mangle]
21501pub unsafe extern "C" fn isgreaterequalf(x: f32, y: f32) -> i32 {
21502    if x.is_nan() || y.is_nan() { 0 } else { (x >= y) as i32 }
21503}
21504
21505// ============================================================
21506// musl ABI compatibility helpers
21507// ============================================================
21508
21509#[no_mangle]
21510pub unsafe extern "C" fn stpcpy(dest: *mut c_char, src: *const c_char) -> *mut c_char {
21511    let mut d = dest;
21512    let mut s = src;
21513    while *s != 0 {
21514        *d = *s;
21515        d = d.add(1);
21516        s = s.add(1);
21517    }
21518    *d = 0;
21519    d
21520}
21521
21522#[no_mangle]
21523pub unsafe extern "C" fn stpncpy(dest: *mut c_char, src: *const c_char, n: usize) -> *mut c_char {
21524    let mut i = 0;
21525    while i < n && *src.add(i) != 0 {
21526        *dest.add(i) = *src.add(i);
21527        i += 1;
21528    }
21529    let end = dest.add(i);
21530    while i < n {
21531        *dest.add(i) = 0;
21532        i += 1;
21533    }
21534    end
21535}
21536
21537#[no_mangle]
21538pub unsafe extern "C" fn strchrnul(s: *const c_char, c: c_int) -> *mut c_char {
21539    let mut p = s;
21540    while *p != 0 && *p as c_int != c {
21541        p = p.add(1);
21542    }
21543    p as *mut c_char
21544}
21545
21546#[no_mangle]
21547pub unsafe extern "C" fn fstatat(dirfd: c_int, path: *const c_char, buf: *mut Stat, flags: c_int) -> c_int {
21548    let r = sys_newfstatat(dirfd, path, buf as *mut u8, flags);
21549    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21550}
21551
21552#[no_mangle]
21553pub unsafe extern "C" fn execvpe(
21554    file: *const c_char,
21555    argv: *const *const c_char,
21556    envp: *const *const c_char,
21557) -> c_int {
21558    ERRNO!() = ENOENT_VAL;
21559    if file.is_null() || *file == 0 {
21560        return -1;
21561    }
21562    let mut p = file;
21563    while *p != 0 {
21564        if *p == b'/' as c_char {
21565            return execve(file, argv, envp);
21566        }
21567        p = p.add(1);
21568    }
21569    let file_len = crate::strlen(file);
21570    let path = crate::getenv(b"PATH\0".as_ptr() as *const c_char);
21571    let default_path = b"/usr/local/bin:/bin:/usr/bin\0";
21572    let path = if path.is_null() { default_path.as_ptr() as *const c_char } else { path };
21573
21574    let mut seen_eacces = false;
21575    let mut buf = [0 as c_char; 4096];
21576    let mut dir = path;
21577    loop {
21578        let mut end = dir;
21579        while *end != 0 && *end != b':' as c_char { end = end.add(1); }
21580        let dlen = end.offset_from(dir) as usize;
21581        // An empty PATH component means the current directory (no slash).
21582        let need_slash = dlen > 0;
21583        let total = dlen + need_slash as usize + file_len;
21584        if total < buf.len() {
21585            let mut i = 0;
21586            while i < dlen { buf[i] = *dir.add(i); i += 1; }
21587            if need_slash { buf[i] = b'/' as c_char; i += 1; }
21588            let mut j = 0;
21589            while j < file_len { buf[i + j] = *file.add(j); j += 1; }
21590            buf[i + j] = 0;
21591            execve(buf.as_ptr(), argv, envp);
21592            match ERRNO!() {
21593                13 => seen_eacces = true, // EACCES
21594                2 | 20 => {}              // ENOENT, ENOTDIR: try next
21595                _ => return -1,
21596            }
21597        }
21598        if *end == 0 { break; }
21599        dir = end.add(1);
21600    }
21601    ERRNO!() = if seen_eacces { 13 } else { 2 };
21602    -1
21603}
21604
21605// Locale-aware entry points. keel currently has a single global locale,
21606// so these are source/ABI-compatible wrappers around the normal functions.
21607#[no_mangle]
21608pub unsafe extern "C" fn strcoll_l(s1: *const c_char, s2: *const c_char, _loc: locale_t) -> c_int {
21609    strcoll(s1, s2)
21610}
21611
21612#[no_mangle]
21613pub unsafe extern "C" fn strxfrm_l(dest: *mut c_char, src: *const c_char, n: usize, _loc: locale_t) -> usize {
21614    strxfrm(dest, src, n)
21615}
21616
21617#[no_mangle]
21618pub unsafe extern "C" fn strerror_l(errnum: c_int, _loc: locale_t) -> *mut c_char {
21619    strerror(errnum)
21620}
21621
21622#[no_mangle]
21623pub unsafe extern "C" fn strcasecmp_l(s1: *const c_char, s2: *const c_char, _loc: locale_t) -> c_int {
21624    strcasecmp(s1, s2)
21625}
21626
21627#[no_mangle]
21628pub unsafe extern "C" fn strncasecmp_l(s1: *const c_char, s2: *const c_char, n: usize, _loc: locale_t) -> c_int {
21629    strncasecmp(s1, s2, n)
21630}
21631
21632#[no_mangle]
21633pub unsafe extern "C" fn strftime_l(s: *mut c_char, max: usize, fmt: *const c_char, tm: *const tm, _loc: locale_t) -> usize {
21634    strftime(s, max, fmt, tm)
21635}
21636
21637#[no_mangle]
21638pub unsafe extern "C" fn nl_langinfo_l(item: c_int, _loc: locale_t) -> *mut c_char {
21639    nl_langinfo(item)
21640}
21641
21642#[no_mangle]
21643pub unsafe extern "C" fn wcscoll_l(s1: *const u32, s2: *const u32, _loc: locale_t) -> c_int {
21644    wcscoll(s1, s2)
21645}
21646
21647#[no_mangle]
21648pub unsafe extern "C" fn wcsxfrm_l(dst: *mut wchar_t, src: *const wchar_t, n: usize, _loc: locale_t) -> usize {
21649    wcsxfrm(dst, src, n)
21650}
21651
21652#[no_mangle]
21653pub unsafe extern "C" fn wcsftime_l(s: *mut u32, max: usize, fmt: *const u32, tm: *const c_void, _loc: locale_t) -> usize {
21654    wcsftime(s, max, fmt, tm)
21655}
21656
21657#[no_mangle]
21658pub unsafe extern "C" fn wctype_l(name: *const c_char, _loc: locale_t) -> wctype_t {
21659    wctype(name)
21660}
21661
21662#[no_mangle]
21663pub unsafe extern "C" fn wctrans_l(name: *const c_char, _loc: locale_t) -> wctrans_t {
21664    wctrans(name)
21665}
21666
21667#[no_mangle]
21668pub unsafe extern "C" fn towlower_l(c: wint_t, _loc: locale_t) -> wint_t {
21669    towlower(c)
21670}
21671
21672#[no_mangle]
21673pub unsafe extern "C" fn towupper_l(c: wint_t, _loc: locale_t) -> wint_t {
21674    towupper(c)
21675}
21676
21677#[no_mangle]
21678pub unsafe extern "C" fn towctrans_l(c: wint_t, desc: wctrans_t, _loc: locale_t) -> wint_t {
21679    towctrans(c, desc)
21680}
21681
21682#[no_mangle] pub unsafe extern "C" fn iswalnum_l(c: wint_t, _l: locale_t) -> c_int { iswalnum(c) }
21683#[no_mangle] pub unsafe extern "C" fn iswalpha_l(c: wint_t, _l: locale_t) -> c_int { iswalpha(c) }
21684#[no_mangle] pub unsafe extern "C" fn iswblank_l(c: wint_t, _l: locale_t) -> c_int { iswblank(c) }
21685#[no_mangle] pub unsafe extern "C" fn iswcntrl_l(c: wint_t, _l: locale_t) -> c_int { iswcntrl(c) }
21686#[no_mangle] pub unsafe extern "C" fn iswdigit_l(c: wint_t, _l: locale_t) -> c_int { iswdigit(c) }
21687#[no_mangle] pub unsafe extern "C" fn iswgraph_l(c: wint_t, _l: locale_t) -> c_int { iswgraph(c) }
21688#[no_mangle] pub unsafe extern "C" fn iswlower_l(c: wint_t, _l: locale_t) -> c_int { iswlower(c) }
21689#[no_mangle] pub unsafe extern "C" fn iswprint_l(c: wint_t, _l: locale_t) -> c_int { iswprint(c) }
21690#[no_mangle] pub unsafe extern "C" fn iswpunct_l(c: wint_t, _l: locale_t) -> c_int { iswpunct(c) }
21691#[no_mangle] pub unsafe extern "C" fn iswspace_l(c: wint_t, _l: locale_t) -> c_int { iswspace(c) }
21692#[no_mangle] pub unsafe extern "C" fn iswupper_l(c: wint_t, _l: locale_t) -> c_int { iswupper(c) }
21693#[no_mangle] pub unsafe extern "C" fn iswxdigit_l(c: wint_t, _l: locale_t) -> c_int { iswxdigit(c) }
21694#[no_mangle] pub unsafe extern "C" fn iswctype_l(c: wint_t, desc: wctype_t, _l: locale_t) -> c_int { iswctype(c, desc) }
21695
21696// ISO C99 scanf ABI aliases expected by musl binaries.
21697#[no_mangle] pub unsafe extern "C" fn __isoc99_scanf(fmt: *const c_char, args: ...) -> c_int { vfscanf(stdin, fmt, args) }
21698#[no_mangle] pub unsafe extern "C" fn __isoc99_fscanf(f: *mut FILE, fmt: *const c_char, args: ...) -> c_int { vfscanf(f, fmt, args) }
21699#[no_mangle] pub unsafe extern "C" fn __isoc99_sscanf(s: *const c_char, fmt: *const c_char, args: ...) -> c_int { vsscanf(s, fmt, args) }
21700#[no_mangle] pub unsafe extern "C" fn __isoc99_vscanf(fmt: *const c_char, args: VaList) -> c_int { vfscanf(stdin, fmt, args) }
21701#[no_mangle] pub unsafe extern "C" fn __isoc99_vfscanf(f: *mut FILE, fmt: *const c_char, args: VaList) -> c_int { vfscanf(f, fmt, args) }
21702#[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) }
21703#[no_mangle] pub unsafe extern "C" fn __isoc99_wscanf(fmt: *const wchar_t, args: ...) -> c_int { vfwscanf(stdin, fmt, args) }
21704#[no_mangle] pub unsafe extern "C" fn __isoc99_fwscanf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int { vfwscanf(f, fmt, args) }
21705#[no_mangle] pub unsafe extern "C" fn __isoc99_swscanf(s: *const wchar_t, fmt: *const wchar_t, args: ...) -> c_int { vswscanf(s, fmt, args) }
21706#[no_mangle] pub unsafe extern "C" fn __isoc99_vwscanf(fmt: *const wchar_t, args: VaList) -> c_int { vfwscanf(stdin, fmt, args) }
21707#[no_mangle] pub unsafe extern "C" fn __isoc99_vfwscanf(f: *mut FILE, fmt: *const wchar_t, args: VaList) -> c_int { vfwscanf(f, fmt, args) }
21708#[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) }
21709
21710// Unlocked stdio entry points. The current stdio implementation is not
21711// thread-safe anyway, so these are aliases for the normal entry points.
21712#[no_mangle] pub unsafe extern "C" fn clearerr_unlocked(f: *mut FILE) { clearerr(f) }
21713#[no_mangle] pub unsafe extern "C" fn feof_unlocked(f: *mut FILE) -> c_int { feof(f) }
21714#[no_mangle] pub unsafe extern "C" fn ferror_unlocked(f: *mut FILE) -> c_int { ferror(f) }
21715#[no_mangle] pub unsafe extern "C" fn fileno_unlocked(f: *mut FILE) -> c_int { fileno(f) }
21716#[no_mangle] pub unsafe extern "C" fn fflush_unlocked(f: *mut FILE) -> c_int { fflush(f) }
21717#[no_mangle] pub unsafe extern "C" fn fgetc_unlocked(f: *mut FILE) -> c_int { fgetc(f) }
21718#[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) }
21719#[no_mangle] pub unsafe extern "C" fn fputc_unlocked(c: c_int, f: *mut FILE) -> c_int { fputc(c, f) }
21720#[no_mangle] pub unsafe extern "C" fn fputs_unlocked(s: *const c_char, f: *mut FILE) -> c_int { fputs(s, f) }
21721#[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) }
21722#[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) }
21723#[no_mangle] pub unsafe extern "C" fn fgetwc_unlocked(f: *mut FILE) -> wint_t { fgetwc(f) }
21724#[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) }
21725#[no_mangle] pub unsafe extern "C" fn fputwc_unlocked(c: wchar_t, f: *mut FILE) -> wint_t { fputwc(c, f) }
21726#[no_mangle] pub unsafe extern "C" fn fputws_unlocked(s: *const wchar_t, f: *mut FILE) -> c_int { fputws(s, f) }
21727#[no_mangle] pub unsafe extern "C" fn getwc_unlocked(f: *mut c_void) -> wint_t { getwc(f) }
21728#[no_mangle] pub unsafe extern "C" fn putwc_unlocked(c: u32, f: *mut c_void) -> wint_t { putwc(c, f) }
21729#[no_mangle] pub unsafe extern "C" fn getwchar_unlocked() -> wint_t { getwchar() }
21730#[no_mangle] pub unsafe extern "C" fn putwchar_unlocked(c: wchar_t) -> wint_t { putwchar(c) }
21731#[no_mangle] pub unsafe extern "C" fn fpurge(f: *mut FILE) { clearerr(f) }
21732#[no_mangle] pub unsafe extern "C" fn _IO_getc(f: *mut FILE) -> c_int { getc(f) }
21733#[no_mangle] pub unsafe extern "C" fn _IO_putc(c: c_int, f: *mut FILE) -> c_int { putc(c, f) }
21734#[no_mangle] pub unsafe extern "C" fn _IO_getc_unlocked(f: *mut FILE) -> c_int { getc(f) }
21735#[no_mangle] pub unsafe extern "C" fn _IO_putc_unlocked(c: c_int, f: *mut FILE) -> c_int { putc(c, f) }
21736#[no_mangle] pub unsafe extern "C" fn _IO_feof_unlocked(f: *mut FILE) -> c_int { feof(f) }
21737#[no_mangle] pub unsafe extern "C" fn _IO_ferror_unlocked(f: *mut FILE) -> c_int { ferror(f) }
21738
21739// ABI aliases used by musl and older C libraries.
21740#[no_mangle] pub unsafe extern "C" fn __getauxval(t: c_ulong) -> c_ulong { getauxval(t) }
21741#[no_mangle] pub unsafe extern "C" fn __longjmp(env: *const c_ulong, val: c_int) -> ! { longjmp(env, val) }
21742#[no_mangle] pub unsafe extern "C" fn bsd_signal(sig: c_int, handler: usize) -> usize { signal(sig, handler) }
21743#[no_mangle] pub unsafe extern "C" fn __sysv_signal(sig: c_int, handler: usize) -> usize { signal(sig, handler) }
21744#[no_mangle] pub unsafe extern "C" fn eaccess(path: *const c_char, mode: c_int) -> c_int { access(path, mode) }
21745#[no_mangle] pub unsafe extern "C" fn __xpg_basename(path: *mut c_char) -> *mut c_char { basename(path) }
21746#[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) }
21747#[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) }
21748
21749// ============================================================
21750// Remaining musl ABI entry points
21751// ============================================================
21752
21753#[no_mangle]
21754pub unsafe extern "C" fn cfsetspeed(termios_p: *mut c_void, speed: u32) -> c_int {
21755    let r = cfsetispeed(termios_p, speed);
21756    if r != 0 { return r; }
21757    cfsetospeed(termios_p, speed)
21758}
21759
21760#[no_mangle]
21761pub unsafe extern "C" fn futimesat(dirfd: c_int, path: *const c_char, times: *const timeval) -> c_int {
21762    if times.is_null() {
21763        return utimensat(dirfd, path, core::ptr::null(), 0);
21764    }
21765    let tv = times as *const [timeval; 2];
21766    let mut ts: [timespec; 2] = [
21767        timespec { tv_sec: (*tv)[0].tv_sec, tv_nsec: (*tv)[0].tv_usec * 1000 },
21768        timespec { tv_sec: (*tv)[1].tv_sec, tv_nsec: (*tv)[1].tv_usec * 1000 },
21769    ];
21770    for t in &mut ts {
21771        if t.tv_nsec < 0 || t.tv_nsec >= 1_000_000_000 {
21772            ERRNO!() = EINVAL;
21773            return -1;
21774        }
21775    }
21776    utimensat(dirfd, path, ts.as_ptr(), 0)
21777}
21778
21779#[no_mangle]
21780pub unsafe extern "C" fn membarrier(cmd: c_int, flags: c_int, cpu_id: c_int) -> c_int {
21781    <Arch as Syscalls>::syscall3(SYS_MEMBARRIER, cmd as i64, flags as i64, cpu_id as i64) as c_int
21782}
21783
21784#[no_mangle]
21785pub unsafe extern "C" fn mremap(
21786    old_address: *mut c_void,
21787    old_size: usize,
21788    new_size: usize,
21789    flags: c_int,
21790    mut args: ...
21791) -> *mut c_void {
21792    let new_address = if flags & 2 != 0 { args.next_arg::<*mut c_void>() } else { core::ptr::null_mut() };
21793    let r = <Arch as Syscalls>::syscall5(
21794        SYS_MREMAP,
21795        old_address as i64,
21796        old_size as i64,
21797        new_size as i64,
21798        flags as i64,
21799        new_address as i64,
21800    );
21801    if r < 0 {
21802        ERRNO!() = (-r) as c_int;
21803        return (-1isize) as *mut c_void;
21804    }
21805    r as *mut c_void
21806}
21807
21808#[no_mangle]
21809pub unsafe extern "C" fn ptsname_r(fd: c_int, buf: *mut c_char, buflen: usize) -> c_int {
21810    let name = ptsname(fd);
21811    if name.is_null() { return -1; }
21812    let n = crate::strlen(name);
21813    if n + 1 > buflen {
21814        ERRNO!() = ERANGE_VAL;
21815        return ERANGE_VAL;
21816    }
21817    core::ptr::copy_nonoverlapping(name, buf, n + 1);
21818    0
21819}
21820
21821#[no_mangle]
21822pub unsafe extern "C" fn posix_getdents(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize {
21823    if flags != 0 {
21824        ERRNO!() = EINVAL;
21825        return -1;
21826    }
21827    let r = <Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, buf as i64, len as i64);
21828    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
21829}
21830
21831#[no_mangle]
21832pub unsafe extern "C" fn riscv_flush_icache(start: *mut c_void, end: *mut c_void, flags: c_ulong) -> c_int {
21833    #[cfg(target_arch = "riscv64")]
21834    {
21835        let r = <Arch as Syscalls>::syscall3(259, start as i64, end as i64, flags as i64);
21836        if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21837    }
21838    #[cfg(not(target_arch = "riscv64"))]
21839    {
21840        let _ = (start, end, flags);
21841        0
21842    }
21843}
21844
21845#[no_mangle]
21846pub unsafe extern "C" fn __riscv_flush_icache(start: *mut c_void, end: *mut c_void, flags: c_ulong) -> c_int {
21847    riscv_flush_icache(start, end, flags)
21848}
21849
21850#[no_mangle]
21851pub unsafe extern "C" fn mkostemps(template: *mut c_char, suffixlen: c_int, flags: c_int) -> c_int {
21852    let fd = mkstemps(template, suffixlen);
21853    if fd >= 0 && flags & O_CLOEXEC != 0 {
21854        sys_fcntl(fd, F_SETFD, FD_CLOEXEC as i64);
21855    }
21856    fd
21857}
21858
21859#[no_mangle]
21860pub unsafe extern "C" fn statfs(path: *const c_char, buf: *mut c_void) -> c_int {
21861    let r = <Arch as Syscalls>::syscall2(SYS_STATFS, path as i64, buf as i64);
21862    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21863}
21864
21865#[no_mangle]
21866pub unsafe extern "C" fn fstatfs(fd: c_int, buf: *mut c_void) -> c_int {
21867    let r = <Arch as Syscalls>::syscall2(SYS_FSTATFS, fd as i64, buf as i64);
21868    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21869}
21870
21871#[no_mangle]
21872pub unsafe extern "C" fn sysinfo(info: *mut c_void) -> c_int {
21873    let r = <Arch as Syscalls>::syscall1(SYS_SYSINFO, info as i64);
21874    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
21875}
21876
21877#[no_mangle]
21878pub unsafe extern "C" fn pthread_tryjoin_np(thread: PthreadT, retval: *mut *mut c_void) -> c_int {
21879    let slot = thread as *mut Thread;
21880    if slot.is_null() { return EINVAL; }
21881    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
21882    let tid = core::ptr::read_volatile(&raw const (*slot).tid);
21883    if tid > 0 { return EBUSY; }
21884    if tid < 0 { return EINVAL; }
21885    pthread_join(thread, retval)
21886}
21887
21888#[no_mangle]
21889pub unsafe extern "C" fn pthread_timedjoin_np(thread: PthreadT, retval: *mut *mut c_void, abstime: *const timespec) -> c_int {
21890    let slot = thread as *mut Thread;
21891    if slot.is_null() { return EINVAL; }
21892    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
21893    loop {
21894        let r = pthread_tryjoin_np(thread, retval);
21895        if r != EBUSY { return r; }
21896        let tid = core::ptr::read_volatile(&raw const (*slot).tid);
21897        if tid <= 0 { continue; }
21898        let e = futex_timedwait(&raw mut (*slot).tid, tid, abstime);
21899        if e == ETIMEDOUT { return ETIMEDOUT; }
21900    }
21901}
21902
21903
21904// utmp/utmpx are backed by the classic /var/run/utmp file.  musl itself
21905// leaves these as no-ops; keel provides the real file-backed API.
21906#[repr(C)]
21907pub struct UtmpExit {
21908    pub e_termination: i16,
21909    pub e_exit: i16,
21910}
21911
21912#[repr(C)]
21913pub struct Utmpx {
21914    pub ut_type: i16,
21915    pub __ut_pad1: i16,
21916    pub ut_pid: i32,
21917    pub ut_line: [c_char; 32],
21918    pub ut_id: [c_char; 4],
21919    pub ut_user: [c_char; 32],
21920    pub ut_host: [c_char; 256],
21921    pub ut_exit: UtmpExit,
21922    pub ut_session: i32,
21923    pub __ut_pad2: i32,
21924    pub ut_tv: timeval,
21925    pub ut_addr_v6: [u32; 4],
21926    pub __unused: [u8; 20],
21927}
21928
21929const UTMP_SIZE: usize = 400;
21930const _: [(); UTMP_SIZE] = [(); core::mem::size_of::<Utmpx>()];
21931
21932static mut UTMP_FD: c_int = -1;
21933static mut UTMP_PATH: [u8; 256] = [0; 256];
21934static mut UTMP_PATH_SET: bool = false;
21935#[repr(align(8))]
21936struct UtmpBuf([u8; UTMP_SIZE]);
21937static mut UTMP_BUF: UtmpBuf = UtmpBuf([0; UTMP_SIZE]);
21938
21939unsafe fn utmp_path_ptr() -> *const c_char {
21940    if !UTMP_PATH_SET {
21941        let default = b"/var/run/utmp\0";
21942        let mut i = 0;
21943        while i < default.len() && i < UTMP_PATH.len() {
21944            UTMP_PATH[i] = default[i];
21945            i += 1;
21946        }
21947        UTMP_PATH_SET = true;
21948    }
21949    UTMP_PATH.as_ptr() as *const c_char
21950}
21951
21952unsafe fn utmp_open_read() -> c_int {
21953    if UTMP_FD >= 0 {
21954        crate::close(UTMP_FD);
21955    }
21956    UTMP_FD = crate::open(utmp_path_ptr(), 0, 0);
21957    UTMP_FD
21958}
21959
21960unsafe fn utmp_open_append() -> c_int {
21961    crate::open(utmp_path_ptr(), 1 | 64 | 1024, 0o644)
21962}
21963
21964#[no_mangle]
21965pub unsafe extern "C" fn setutent() {
21966    let _ = utmp_open_read();
21967}
21968
21969#[no_mangle]
21970pub unsafe extern "C" fn endutent() {
21971    if UTMP_FD >= 0 {
21972        crate::close(UTMP_FD);
21973        UTMP_FD = -1;
21974    }
21975}
21976
21977#[no_mangle]
21978pub unsafe extern "C" fn getutent() -> *mut c_void {
21979    if UTMP_FD < 0 && utmp_open_read() < 0 {
21980        return core::ptr::null_mut();
21981    }
21982    let n = crate::read(UTMP_FD, UTMP_BUF.0.as_mut_ptr() as *mut c_void, UTMP_SIZE);
21983    if n == UTMP_SIZE as isize {
21984        UTMP_BUF.0.as_mut_ptr() as *mut c_void
21985    } else {
21986        core::ptr::null_mut()
21987    }
21988}
21989
21990unsafe fn utmp_id_eq(a: &[c_char; 4], b: &[c_char; 4]) -> bool {
21991    a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3]
21992}
21993
21994unsafe fn utmp_line_eq(a: &[c_char; 32], b: &[c_char; 32]) -> bool {
21995    let mut i = 0;
21996    while i < 32 {
21997        if a[i] != b[i] { return false; }
21998        if a[i] == 0 { return true; }
21999        i += 1;
22000    }
22001    true
22002}
22003
22004#[no_mangle]
22005pub unsafe extern "C" fn getutid(ut: *const c_void) -> *mut c_void {
22006    if ut.is_null() { return core::ptr::null_mut(); }
22007    let want = &*(ut as *const Utmpx);
22008    loop {
22009        let p = getutent();
22010        if p.is_null() { return p; }
22011        let cur = &*(p as *const Utmpx);
22012        let matched = match want.ut_type {
22013            1 | 2 | 3 | 4 => cur.ut_type == want.ut_type,
22014            _ => utmp_id_eq(&cur.ut_id, &want.ut_id)
22015                && (want.ut_type == 0 || cur.ut_type == want.ut_type),
22016        };
22017        if matched { return p; }
22018    }
22019}
22020
22021#[no_mangle]
22022pub unsafe extern "C" fn getutline(ut: *const c_void) -> *mut c_void {
22023    if ut.is_null() { return core::ptr::null_mut(); }
22024    let want = &*(ut as *const Utmpx);
22025    loop {
22026        let p = getutent();
22027        if p.is_null() { return p; }
22028        if utmp_line_eq(&(*(p as *const Utmpx)).ut_line, &want.ut_line) {
22029            return p;
22030        }
22031    }
22032}
22033
22034#[no_mangle]
22035pub unsafe extern "C" fn pututline(ut: *const c_void) -> *mut c_void {
22036    if ut.is_null() { return core::ptr::null_mut(); }
22037    let fd = utmp_open_append();
22038    if fd < 0 { return core::ptr::null_mut(); }
22039    let n = crate::write(fd, ut, UTMP_SIZE);
22040    crate::close(fd);
22041    if n == UTMP_SIZE as isize { ut as *mut c_void } else { core::ptr::null_mut() }
22042}
22043
22044#[no_mangle]
22045pub unsafe extern "C" fn updwtmp(file: *const c_char, ut: *const c_void) {
22046    if file.is_null() || ut.is_null() { return; }
22047    let fd = crate::open(file, 1 | 64 | 1024, 0o644);
22048    if fd >= 0 {
22049        let _ = crate::write(fd, ut, UTMP_SIZE);
22050        crate::close(fd);
22051    }
22052}
22053
22054unsafe fn utmp_set_name(file: *const c_char) -> c_int {
22055    if file.is_null() { return -1; }
22056    let len = crate::strlen(file);
22057    if len + 1 > UTMP_PATH.len() { return -1; }
22058    if UTMP_FD >= 0 {
22059        crate::close(UTMP_FD);
22060        UTMP_FD = -1;
22061    }
22062    core::ptr::copy_nonoverlapping(file, UTMP_PATH.as_mut_ptr() as *mut c_char, len + 1);
22063    UTMP_PATH_SET = true;
22064    0
22065}
22066
22067#[no_mangle]
22068pub unsafe extern "C" fn utmpname(file: *const c_char) -> c_int { utmp_set_name(file) }
22069
22070#[no_mangle]
22071pub unsafe extern "C" fn utmpxname(file: *const c_char) -> c_int { utmp_set_name(file) }
22072
22073
22074// Data symbols and internal aliases still referenced by some musl binaries.
22075#[no_mangle] pub static mut ___environ: *mut *mut c_char = core::ptr::null_mut();
22076#[no_mangle] pub static mut _environ: *mut *mut c_char = core::ptr::null_mut();
22077#[no_mangle] pub unsafe extern "C" fn __freelocale(loc: locale_t) { freelocale(loc) }
22078#[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) }
22079#[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) }
22080#[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) }
22081#[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) }
22082
22083#[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) }
22084#[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) }
22085#[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) }
22086#[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) }
22087#[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) }
22088#[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) }
22089
22090// ============================================================
22091// Resolver (UDP DNS)
22092// ============================================================
22093
22094const MAX_NS: usize = 3;
22095const MAX_SEARCH: usize = 6;
22096const HOST_NOT_FOUND: c_int = 1;
22097const TRY_AGAIN: c_int = 2;
22098const NO_RECOVERY: c_int = 3;
22099const NO_DATA: c_int = 4;
22100
22101static mut NS_COUNT: usize = 0;
22102static mut NS_ADDRS: [u32; MAX_NS] = [0; MAX_NS];
22103static mut SEARCH_COUNT: usize = 0;
22104static mut SEARCH_DOMAINS: [[u8; 256]; MAX_SEARCH] = [[0; 256]; MAX_SEARCH];
22105static mut RESOLV_INITIALIZED: bool = false;
22106
22107#[repr(C)]
22108struct SockAddrIn {
22109    sin_family: u16,
22110    sin_port: u16,
22111    sin_addr: u32,
22112    sin_zero: [u8; 8],
22113}
22114
22115#[repr(C)]
22116struct PollFd {
22117    fd: c_int,
22118    events: i16,
22119    revents: i16,
22120}
22121
22122unsafe fn resolv_skip_ws(line: &[u8], mut i: usize) -> usize {
22123    while i < line.len() && (line[i] == b' ' || line[i] == b'\t') { i += 1; }
22124    i
22125}
22126
22127unsafe fn resolv_token<'a>(line: &'a [u8], mut i: usize) -> (&'a [u8], usize) {
22128    let start = i;
22129    while i < line.len() && line[i] != b' ' && line[i] != b'\t' && line[i] != b'#' { i += 1; }
22130    (&line[start..i], i)
22131}
22132
22133unsafe fn resolv_parse_config() -> c_int {
22134    RESOLV_INITIALIZED = true;
22135    NS_COUNT = 0;
22136    SEARCH_COUNT = 0;
22137    let path = b"/etc/resolv.conf\0";
22138    let fd = crate::open(path.as_ptr() as *const c_char, 0, 0);
22139    if fd < 0 { return -1; }
22140    let mut buf = [0u8; 4096];
22141    let n = crate::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len());
22142    crate::close(fd);
22143    if n <= 0 { return -1; }
22144    let len = n as usize;
22145    let mut i = 0;
22146    while i < len {
22147        let start = i;
22148        while i < len && buf[i] != b'\n' { i += 1; }
22149        let line = &buf[start..i];
22150        i += 1;
22151        let mut j = resolv_skip_ws(line, 0);
22152        if j >= line.len() || line[j] == b'#' { continue; }
22153        let (key, next) = resolv_token(line, j);
22154        j = next;
22155        if key == b"nameserver" {
22156            j = resolv_skip_ws(line, j);
22157            let (tok, _) = resolv_token(line, j);
22158            if !tok.is_empty() && NS_COUNT < MAX_NS {
22159                let mut name = [0u8; 64];
22160                let l = core::cmp::min(tok.len(), 63);
22161                name[..l].copy_from_slice(&tok[..l]);
22162                let addr = crate::inet_addr(name.as_ptr() as *const c_char);
22163                if addr != u32::MAX {
22164                    NS_ADDRS[NS_COUNT] = addr;
22165                    NS_COUNT += 1;
22166                }
22167            }
22168        } else if key == b"search" || key == b"domain" {
22169            loop {
22170                j = resolv_skip_ws(line, j);
22171                if j >= line.len() || line[j] == b'#' { break; }
22172                let (tok, next) = resolv_token(line, j);
22173                j = next;
22174                if tok.is_empty() { break; }
22175                if SEARCH_COUNT < MAX_SEARCH {
22176                    let l = core::cmp::min(tok.len(), 255);
22177                    SEARCH_DOMAINS[SEARCH_COUNT][..l].copy_from_slice(&tok[..l]);
22178                    SEARCH_DOMAINS[SEARCH_COUNT][l] = 0;
22179                    SEARCH_COUNT += 1;
22180                }
22181                if key == b"domain" { break; }
22182            }
22183        }
22184    }
22185    0
22186}
22187
22188#[no_mangle]
22189pub unsafe extern "C" fn res_init() -> c_int {
22190    let _ = resolv_parse_config();
22191    0
22192}
22193
22194#[no_mangle]
22195pub unsafe extern "C" fn res_mkquery(
22196    op: c_int,
22197    dname: *const c_char,
22198    class: c_int,
22199    type_: c_int,
22200    _data: *const u8,
22201    _datalen: c_int,
22202    _newrr: *const u8,
22203    buf: *mut u8,
22204    buflen: c_int,
22205) -> c_int {
22206    if dname.is_null() || buf.is_null() { return -1; }
22207    let mut l = crate::strnlen(dname as *const u8, 255);
22208    if l > 0 && *dname.add(l - 1) == b'.' as c_char { l -= 1; }
22209    if l > 0 && *dname.add(l - 1) == b'.' as c_char { return -1; }
22210    let n = 17 + l + if l != 0 { 1 } else { 0 };
22211    if l > 253 || buflen < n as c_int || op < 0 || op > 15 || class < 0 || class > 255 || type_ < 0 || type_ > 255 {
22212        return -1;
22213    }
22214    let mut q = [0u8; 280];
22215    crate::memset(q.as_mut_ptr() as *mut c_void, 0, n);
22216    q[2] = (op * 8 + 1) as u8;
22217    q[3] = 32;
22218    q[5] = 1;
22219    core::ptr::copy_nonoverlapping(dname as *const u8, q.as_mut_ptr().add(13), l);
22220    let mut i = 13;
22221    while q[i] != 0 {
22222        let mut j = i;
22223        while q[j] != 0 && q[j] != b'.' { j += 1; }
22224        if j - i - 1 > 62 { return -1; }
22225        q[i - 1] = (j - i) as u8;
22226        i = j + 1;
22227    }
22228    q[i + 1] = type_ as u8;
22229    q[i + 3] = class as u8;
22230    let mut ts = timespec { tv_sec: 0, tv_nsec: 0 };
22231    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
22232    let id = (((ts.tv_nsec as u64) + (ts.tv_nsec as u64) / 65536) & 0xffff) as u16;
22233    q[0] = (id >> 8) as u8;
22234    q[1] = id as u8;
22235    core::ptr::copy_nonoverlapping(q.as_ptr(), buf, n);
22236    n as c_int
22237}
22238
22239unsafe fn res_send_inner(msg: *const u8, msglen: c_int, answer: *mut u8, anslen: c_int) -> c_int {
22240    if msg.is_null() || answer.is_null() || msglen < 12 || anslen < 12 { return -1; }
22241    if !RESOLV_INITIALIZED { let _ = resolv_parse_config(); }
22242    if NS_COUNT == 0 {
22243        h_errno = TRY_AGAIN;
22244        return -1;
22245    }
22246    for n in 0..NS_COUNT {
22247        let fd = crate::socket(AF_INET, SOCK_DGRAM, 0);
22248        if fd < 0 { continue; }
22249        let sa = SockAddrIn {
22250            sin_family: AF_INET as u16,
22251            sin_port: 53u16.to_be(),
22252            sin_addr: NS_ADDRS[n],
22253            sin_zero: [0; 8],
22254        };
22255        let sent = crate::sendto(fd, msg as *const c_void, msglen as usize, 0, &sa as *const SockAddrIn as *const crate::sockaddr, 16);
22256        if sent != msglen as isize {
22257            crate::close(fd);
22258            continue;
22259        }
22260        let mut pfd = PollFd { fd, events: 1, revents: 0 };
22261        let pr = crate::poll(&mut pfd as *mut PollFd as *mut c_void, 1, 5000);
22262        if pr <= 0 {
22263            crate::close(fd);
22264            continue;
22265        }
22266        let r = crate::recvfrom(fd, answer as *mut c_void, anslen as usize, 0, core::ptr::null_mut(), core::ptr::null_mut());
22267        crate::close(fd);
22268        if r >= 12 {
22269            let id_ok = *answer == *msg && *answer.add(1) == *msg.add(1);
22270            let qr = (*answer.add(2) & 0x80) != 0;
22271            if id_ok && qr {
22272                return r as c_int;
22273            }
22274        }
22275    }
22276    h_errno = TRY_AGAIN;
22277    -1
22278}
22279
22280#[no_mangle]
22281pub unsafe extern "C" fn res_send(msg: *const u8, msglen: c_int, answer: *mut u8, anslen: c_int) -> c_int {
22282    if anslen < 512 {
22283        let mut buf = [0u8; 512];
22284        let r = res_send_inner(msg, msglen, buf.as_mut_ptr(), 512);
22285        if r >= 0 {
22286            let copy = core::cmp::min(r, anslen) as usize;
22287            if copy > 0 { core::ptr::copy_nonoverlapping(buf.as_ptr(), answer, copy); }
22288        }
22289        return r;
22290    }
22291    res_send_inner(msg, msglen, answer, anslen)
22292}
22293
22294#[no_mangle]
22295pub unsafe extern "C" fn res_query(
22296    dname: *const c_char,
22297    class: c_int,
22298    type_: c_int,
22299    answer: *mut u8,
22300    anslen: c_int,
22301) -> c_int {
22302    let mut q = [0u8; 280];
22303    let ql = res_mkquery(0, dname, class, type_, core::ptr::null(), 0, core::ptr::null(), q.as_mut_ptr(), q.len() as c_int);
22304    if ql < 0 { return ql; }
22305    let r = res_send(q.as_ptr(), ql, answer, anslen);
22306    if r < 12 {
22307        h_errno = TRY_AGAIN;
22308        return -1;
22309    }
22310    let rcode = answer.add(3).read() & 0x0f;
22311    if rcode == 3 {
22312        h_errno = HOST_NOT_FOUND;
22313        return -1;
22314    }
22315    if rcode == 0 && *answer.add(6) == 0 && *answer.add(7) == 0 {
22316        h_errno = NO_DATA;
22317        return -1;
22318    }
22319    if rcode != 0 {
22320        h_errno = NO_RECOVERY;
22321        return -1;
22322    }
22323    r
22324}
22325
22326#[no_mangle]
22327pub unsafe extern "C" fn res_querydomain(
22328    name: *const c_char,
22329    domain: *const c_char,
22330    class: c_int,
22331    type_: c_int,
22332    answer: *mut u8,
22333    anslen: c_int,
22334) -> c_int {
22335    if domain.is_null() || *domain == 0 { return res_query(name, class, type_, answer, anslen); }
22336    let mut buf = [0u8; 512];
22337    let nl = crate::strlen(name);
22338    let dl = crate::strlen(domain);
22339    if nl + 1 + dl >= buf.len() { return -1; }
22340    core::ptr::copy_nonoverlapping(name, buf.as_mut_ptr() as *mut c_char, nl);
22341    buf[nl] = b'.';
22342    core::ptr::copy_nonoverlapping(domain, buf.as_mut_ptr().add(nl + 1) as *mut c_char, dl);
22343    buf[nl + 1 + dl] = 0;
22344    res_query(buf.as_ptr() as *const c_char, class, type_, answer, anslen)
22345}
22346
22347#[no_mangle]
22348pub unsafe extern "C" fn res_search(
22349    name: *const c_char,
22350    class: c_int,
22351    type_: c_int,
22352    answer: *mut u8,
22353    anslen: c_int,
22354) -> c_int {
22355    if name.is_null() { return -1; }
22356    if !RESOLV_INITIALIZED { let _ = resolv_parse_config(); }
22357    let len = crate::strlen(name);
22358    let mut dots = 0;
22359    for i in 0..len {
22360        if *name.add(i) == b'.' as c_char { dots += 1; }
22361    }
22362    let trailing_dot = len > 0 && *name.add(len - 1) == b'.' as c_char;
22363    if trailing_dot || dots >= 1 {
22364        let r = res_query(name, class, type_, answer, anslen);
22365        if r >= 0 { return r; }
22366        if trailing_dot { return -1; }
22367    }
22368    for i in 0..SEARCH_COUNT {
22369        let dom = SEARCH_DOMAINS[i].as_ptr() as *const c_char;
22370        let r = res_querydomain(name, dom, class, type_, answer, anslen);
22371        if r >= 0 { return r; }
22372        if h_errno != HOST_NOT_FOUND && h_errno != NO_DATA { return -1; }
22373    }
22374    if dots == 0 {
22375        return res_query(name, class, type_, answer, anslen);
22376    }
22377    -1
22378}
22379
22380// ============================================================
22381// Host and address resolution
22382// ============================================================
22383
22384#[repr(C)]
22385pub struct HostEnt {
22386    pub h_name: *mut c_char,
22387    pub h_aliases: *mut *mut c_char,
22388    pub h_addrtype: c_int,
22389    pub h_length: c_int,
22390    pub h_addr_list: *mut *mut c_char,
22391}
22392
22393#[repr(C)]
22394pub struct AddrInfo {
22395    pub ai_flags: c_int,
22396    pub ai_family: c_int,
22397    pub ai_socktype: c_int,
22398    pub ai_protocol: c_int,
22399    pub ai_addrlen: u32,
22400    pub ai_addr: *mut c_void,
22401    pub ai_canonname: *mut c_char,
22402    pub ai_next: *mut AddrInfo,
22403}
22404
22405static mut HOST_ENT: HostEnt = HostEnt {
22406    h_name: core::ptr::null_mut(),
22407    h_aliases: core::ptr::null_mut(),
22408    h_addrtype: 0,
22409    h_length: 0,
22410    h_addr_list: core::ptr::null_mut(),
22411};
22412static mut HOST_NAME: [c_char; 256] = [0; 256];
22413static mut HOST_ALIASES: [*mut c_char; 8] = [core::ptr::null_mut(); 8];
22414static mut HOST_ADDR: [u8; 16] = [0; 16];
22415static mut HOST_ADDR_PTRS: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
22416
22417unsafe fn dns_skip_name(p: *const u8, end: *const u8) -> *const u8 {
22418    let mut q = p;
22419    while q < end {
22420        let c = *q;
22421        if c == 0 { return q.add(1); }
22422        if c & 0xc0 == 0xc0 { return q.add(2); }
22423        q = q.add(1 + c as usize);
22424    }
22425    end
22426}
22427
22428unsafe fn dns_read_u16(p: *const u8) -> u16 {
22429    ((*p as u16) << 8) | *p.add(1) as u16
22430}
22431
22432unsafe fn dns_expand_name(p: *const u8, msg: *const u8, out: *mut c_char, outlen: usize) -> bool {
22433    let mut q = p;
22434    let mut o = 0usize;
22435    let mut jumps = 0;
22436    loop {
22437        let c = *q;
22438        if c == 0 {
22439            if o < outlen { *out.add(o) = 0; }
22440            return true;
22441        }
22442        if c & 0xc0 == 0xc0 {
22443            let off = (((c & 0x3f) as usize) << 8) | *q.add(1) as usize;
22444            q = msg.add(off);
22445            jumps += 1;
22446            if jumps > 16 { return false; }
22447            continue;
22448        }
22449        let l = c as usize;
22450        if l > 63 { return false; }
22451        if o + l + 1 >= outlen { return false; }
22452        core::ptr::copy_nonoverlapping(q.add(1), out.add(o) as *mut u8, l);
22453        o += l;
22454        *out.add(o) = b'.' as c_char;
22455        o += 1;
22456        q = q.add(1 + l);
22457    }
22458}
22459
22460unsafe fn host_from_answer(answer: *const u8, len: c_int, af: c_int) -> *mut HostEnt {
22461    if len < 12 { return core::ptr::null_mut(); }
22462    let end = answer.add(len as usize);
22463    let qd = dns_read_u16(answer.add(4)) as usize;
22464    let an = dns_read_u16(answer.add(6)) as usize;
22465    let mut p = answer.add(12);
22466    for _ in 0..qd {
22467        p = dns_skip_name(p, end);
22468        p = p.add(4);
22469    }
22470    let want_type: u16 = if af == AF_INET6 { 28 } else { 1 };
22471    let want_len = if af == AF_INET6 { 16 } else { 4 };
22472    for _ in 0..an {
22473        p = dns_skip_name(p, end);
22474        if p.add(10) > end { break; }
22475        let typ = dns_read_u16(p);
22476        let class = dns_read_u16(p.add(2));
22477        let rdlen = dns_read_u16(p.add(8)) as usize;
22478        let rdata = p.add(10);
22479        if rdata.add(rdlen) > end { break; }
22480        if typ == want_type && class == 1 && rdlen == want_len {
22481            core::ptr::copy_nonoverlapping(rdata, HOST_ADDR.as_mut_ptr(), want_len);
22482            HOST_ENT.h_addrtype = af;
22483            HOST_ENT.h_length = want_len as c_int;
22484            HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
22485            HOST_ADDR_PTRS[1] = core::ptr::null_mut();
22486            HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
22487            HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
22488            HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
22489            h_errno = 0;
22490            return &raw mut HOST_ENT;
22491        }
22492        p = rdata.add(rdlen);
22493    }
22494    core::ptr::null_mut()
22495}
22496
22497#[no_mangle]
22498pub unsafe extern "C" fn gethostbyname(name: *const c_char) -> *mut HostEnt {
22499    gethostbyname2(name, AF_INET)
22500}
22501
22502#[no_mangle]
22503pub unsafe extern "C" fn gethostbyname2(name: *const c_char, af: c_int) -> *mut HostEnt {
22504    if name.is_null() { h_errno = HOST_NOT_FOUND; return core::ptr::null_mut(); }
22505    let mut addr = [0u8; 16];
22506    let addrlen = if af == AF_INET6 { 16 } else { 4 };
22507    if inet_pton(af, name, addr.as_mut_ptr() as *mut c_void) == 1 {
22508        core::ptr::copy_nonoverlapping(addr.as_ptr(), HOST_ADDR.as_mut_ptr(), addrlen);
22509        let n = crate::strlen(name);
22510        let l = core::cmp::min(n, 255);
22511        core::ptr::copy_nonoverlapping(name, HOST_NAME.as_mut_ptr(), l);
22512        HOST_NAME[l] = 0;
22513        HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
22514        HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
22515        HOST_ENT.h_addrtype = af;
22516        HOST_ENT.h_length = addrlen as c_int;
22517        HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
22518        HOST_ADDR_PTRS[1] = core::ptr::null_mut();
22519        HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
22520        h_errno = 0;
22521        return &raw mut HOST_ENT;
22522    }
22523    let mut answer = [0u8; 512];
22524    let qtype = if af == AF_INET6 { 28 } else { 1 };
22525    let r = res_query(name, 1, qtype, answer.as_mut_ptr(), answer.len() as c_int);
22526    if r < 0 {
22527        if h_errno == 0 { h_errno = TRY_AGAIN; }
22528        return core::ptr::null_mut();
22529    }
22530    let ent = host_from_answer(answer.as_ptr(), r, af);
22531    if !ent.is_null() {
22532        let n = crate::strlen(name);
22533        let l = core::cmp::min(n, 255);
22534        core::ptr::copy_nonoverlapping(name, HOST_NAME.as_mut_ptr(), l);
22535        HOST_NAME[l] = 0;
22536    } else {
22537        h_errno = HOST_NOT_FOUND;
22538    }
22539    ent
22540}
22541
22542#[no_mangle]
22543pub unsafe extern "C" fn gethostbyaddr(addr: *const c_void, len: u32, type_: c_int) -> *mut HostEnt {
22544    // musl implements gethostbyaddr() on top of getnameinfo(), so /etc/hosts
22545    // and the DNS reverse path behave identically for both APIs.
22546    let (addr_len, salen) = match type_ {
22547        AF_INET => (4usize, 16u32),
22548        AF_INET6 => (16usize, 28u32),
22549        _ => {
22550            h_errno = HOST_NOT_FOUND;
22551            return core::ptr::null_mut();
22552        }
22553    };
22554    if addr.is_null() || len as usize != addr_len {
22555        h_errno = HOST_NOT_FOUND;
22556        return core::ptr::null_mut();
22557    }
22558    let mut sa = [0u8; 28];
22559    *(sa.as_mut_ptr() as *mut u16) = type_ as u16;
22560    if type_ == AF_INET {
22561        core::ptr::copy_nonoverlapping(addr as *const u8, sa.as_mut_ptr().add(4), 4);
22562    } else {
22563        core::ptr::copy_nonoverlapping(addr as *const u8, sa.as_mut_ptr().add(8), 16);
22564    }
22565    let mut name = [0 as c_char; 256];
22566    let rc = getnameinfo(
22567        sa.as_ptr() as *const c_void,
22568        salen,
22569        name.as_mut_ptr(),
22570        name.len() as u32,
22571        core::ptr::null_mut(),
22572        0,
22573        0,
22574    );
22575    if rc != 0 {
22576        h_errno = match rc {
22577            EAI_AGAIN_V => TRY_AGAIN,
22578            EAI_NONAME_V => HOST_NOT_FOUND,
22579            _ => NO_RECOVERY,
22580        };
22581        return core::ptr::null_mut();
22582    }
22583    let l = crate::strlen(name.as_ptr());
22584    if l >= HOST_NAME.len() {
22585        h_errno = NO_RECOVERY;
22586        return core::ptr::null_mut();
22587    }
22588    core::ptr::copy_nonoverlapping(name.as_ptr(), HOST_NAME.as_mut_ptr(), l + 1);
22589    core::ptr::copy_nonoverlapping(addr as *const u8, HOST_ADDR.as_mut_ptr(), addr_len);
22590    HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
22591    HOST_ALIASES[0] = HOST_NAME.as_mut_ptr();
22592    HOST_ALIASES[1] = core::ptr::null_mut();
22593    HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
22594    HOST_ENT.h_addrtype = type_;
22595    HOST_ENT.h_length = addr_len as c_int;
22596    HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
22597    HOST_ADDR_PTRS[1] = core::ptr::null_mut();
22598    HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
22599    h_errno = 0;
22600    &raw mut HOST_ENT
22601}
22602
22603// ============================================================
22604// Legacy syscall/stdio/signal compatibility
22605// ============================================================
22606
22607#[inline]
22608fn sysno(x86_64: i64, generic: i64) -> i64 {
22609    if cfg!(target_arch = "x86_64") { x86_64 } else { generic }
22610}
22611
22612#[no_mangle]
22613pub unsafe extern "C" fn settimeofday(tv: *const c_void, tz: *const c_void) -> c_int {
22614    let r = <Arch as Syscalls>::syscall2(sysno(164, 170), tv as i64, tz as i64);
22615    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22616}
22617
22618#[no_mangle]
22619pub unsafe extern "C" fn stime(t: *const i64) -> c_int {
22620    if t.is_null() { ERRNO!() = EINVAL; return -1; }
22621    let tv = timeval { tv_sec: *t, tv_usec: 0 };
22622    settimeofday(&tv as *const timeval as *const c_void, core::ptr::null())
22623}
22624
22625#[no_mangle]
22626pub unsafe extern "C" fn times(buf: *mut c_void) -> c_long {
22627    let r = <Arch as Syscalls>::syscall1(sysno(100, 153), buf as i64);
22628    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_long }
22629}
22630
22631#[no_mangle]
22632pub 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 {
22633    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);
22634    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22635}
22636
22637#[no_mangle]
22638pub unsafe extern "C" fn tee(fd_in: c_int, fd_out: c_int, len: usize, flags: u32) -> isize {
22639    let r = <Arch as Syscalls>::syscall4(sysno(276, 77), fd_in as i64, fd_out as i64, len as i64, flags as i64);
22640    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22641}
22642
22643#[no_mangle]
22644pub unsafe extern "C" fn statx(dirfd: c_int, path: *const c_char, flags: c_int, mask: u32, buf: *mut c_void) -> c_int {
22645    let r = <Arch as Syscalls>::syscall5(sysno(332, 291), dirfd as i64, path as i64, flags as i64, mask as i64, buf as i64);
22646    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22647}
22648
22649#[no_mangle]
22650pub unsafe extern "C" fn setns(fd: c_int, nstype: c_int) -> c_int {
22651    let r = <Arch as Syscalls>::syscall2(SYS_SETNS, fd as i64, nstype as i64);
22652    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22653}
22654
22655#[no_mangle]
22656pub unsafe extern "C" fn setfsuid(uid: u32) -> c_int {
22657    <Arch as Syscalls>::syscall1(sysno(122, 151), uid as i64) as c_int
22658}
22659
22660#[no_mangle]
22661pub unsafe extern "C" fn setfsgid(gid: u32) -> c_int {
22662    <Arch as Syscalls>::syscall1(sysno(123, 152), gid as i64) as c_int
22663}
22664
22665#[no_mangle]
22666pub unsafe extern "C" fn setregid(rgid: u32, egid: u32) -> c_int {
22667    let r = <Arch as Syscalls>::syscall2(sysno(114, 143), rgid as i64, egid as i64);
22668    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22669}
22670
22671#[no_mangle]
22672pub 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 {
22673    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);
22674    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22675}
22676
22677#[no_mangle]
22678pub 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 {
22679    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);
22680    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22681}
22682
22683#[no_mangle]
22684pub unsafe extern "C" fn tcgetwinsize(fd: c_int, ws: *mut c_void) -> c_int {
22685    if fd < 0 || ws.is_null() { ERRNO!() = EINVAL; return -1; }
22686    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5413, ws as i64);
22687    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22688}
22689
22690#[no_mangle]
22691pub unsafe extern "C" fn tcsetwinsize(fd: c_int, ws: *const c_void) -> c_int {
22692    if fd < 0 || ws.is_null() { ERRNO!() = EINVAL; return -1; }
22693    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5414, ws as i64);
22694    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22695}
22696
22697#[no_mangle]
22698pub unsafe extern "C" fn sockatmark(fd: c_int) -> c_int {
22699    let mut at: c_int = 0;
22700    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x8905, &mut at as *mut c_int as i64);
22701    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { at }
22702}
22703
22704#[no_mangle]
22705pub unsafe extern "C" fn isastream(fd: c_int) -> c_int {
22706    let mut buf = [0u8; 64];
22707    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5401, buf.as_mut_ptr() as i64);
22708    if r < 0 { ERRNO!() = (-r) as c_int; 0 } else { 1 }
22709}
22710
22711#[no_mangle]
22712pub unsafe extern "C" fn posix_madvise(addr: *mut c_void, len: usize, advice: c_int) -> c_int {
22713    madvise(addr as *mut u8, len, advice)
22714}
22715
22716#[no_mangle]
22717pub unsafe extern "C" fn secure_getenv(name: *const c_char) -> *mut c_char {
22718    if getauxval(23) != 0 { return core::ptr::null_mut(); }
22719    getenv(name)
22720}
22721
22722#[no_mangle]
22723pub unsafe extern "C" fn sigandset(dest: *mut c_ulong, left: *const c_ulong, right: *const c_ulong) -> c_int {
22724    if dest.is_null() || left.is_null() || right.is_null() { return -1; }
22725    *dest = *left & *right;
22726    0
22727}
22728
22729#[no_mangle]
22730pub unsafe extern "C" fn sigorset(dest: *mut c_ulong, left: *const c_ulong, right: *const c_ulong) -> c_int {
22731    if dest.is_null() || left.is_null() || right.is_null() { return -1; }
22732    *dest = *left | *right;
22733    0
22734}
22735
22736#[no_mangle]
22737pub unsafe extern "C" fn sigisemptyset(set: *const c_ulong) -> c_int {
22738    if set.is_null() { return 1; }
22739    (*set == 0) as c_int
22740}
22741
22742#[no_mangle]
22743pub unsafe extern "C" fn sighold(sig: c_int) -> c_int {
22744    let set: c_ulong = 1u64 << (sig - 1) as u32;
22745    sigprocmask(0, &set, core::ptr::null_mut());
22746    0
22747}
22748
22749#[no_mangle]
22750pub unsafe extern "C" fn sigignore(sig: c_int) -> c_int {
22751    let _ = signal(sig, 1);
22752    0
22753}
22754
22755#[no_mangle]
22756pub unsafe extern "C" fn sigrelse(sig: c_int) -> c_int {
22757    let set: c_ulong = 1u64 << (sig - 1) as u32;
22758    sigprocmask(1, &set, core::ptr::null_mut());
22759    0
22760}
22761
22762#[no_mangle]
22763pub unsafe extern "C" fn siginterrupt(sig: c_int, flag: c_int) -> c_int {
22764    let mut sa: sigaction = core::mem::zeroed();
22765    if sigaction(sig, core::ptr::null(), &mut sa) != 0 { return -1; }
22766    if flag != 0 { sa.sa_flags &= !(SA_RESTART as c_int); } else { sa.sa_flags |= SA_RESTART as c_int; }
22767    sigaction(sig, &sa, core::ptr::null_mut())
22768}
22769
22770#[no_mangle]
22771pub unsafe extern "C" fn sigpause(sig: c_int) -> c_int {
22772    let set: c_ulong = 1u64 << (sig - 1) as u32;
22773    sigsuspend(&set)
22774}
22775
22776#[no_mangle]
22777pub unsafe extern "C" fn semtimedop(semid: c_int, sops: *mut c_void, nsops: usize, timeout: *const timespec) -> c_int {
22778    let r = <Arch as Syscalls>::syscall4(sysno(220, 192), semid as i64, sops as i64, nsops as i64, timeout as i64);
22779    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
22780}
22781
22782#[no_mangle]
22783pub unsafe extern "C" fn wait3(status: *mut c_int, options: c_int, rusage: *mut c_void) -> i32 {
22784    wait4(-1, status, options, rusage) as i32
22785}
22786
22787#[no_mangle]
22788pub unsafe extern "C" fn tempnam(dir: *const c_char, pfx: *const c_char) -> *mut c_char {
22789    let mut path = [0 as c_char; 256];
22790    let mut i = 0;
22791    if !dir.is_null() {
22792        while *dir.add(i) != 0 && i < 200 { path[i] = *dir.add(i); i += 1; }
22793        if i > 0 && path[i-1] != b'/' as c_char { path[i] = b'/' as c_char; i += 1; }
22794    } else {
22795        for &c in b"/tmp/" { path[i] = c as c_char; i += 1; }
22796    }
22797    if !pfx.is_null() {
22798        let mut j = 0;
22799        while *pfx.add(j) != 0 && i < 220 { path[i] = *pfx.add(j); i += 1; j += 1; }
22800    }
22801    for &c in b"XXXXXX" { path[i] = c as c_char; i += 1; }
22802    path[i] = 0;
22803    let fd = mkstemp(path.as_mut_ptr());
22804    if fd < 0 { return core::ptr::null_mut(); }
22805    close(fd);
22806    unlink(path.as_ptr());
22807    let n = strlen(path.as_ptr());
22808    let out = malloc(n + 1) as *mut c_char;
22809    if out.is_null() { return core::ptr::null_mut(); }
22810    core::ptr::copy_nonoverlapping(path.as_ptr(), out, n + 1);
22811    out
22812}
22813
22814#[no_mangle]
22815pub unsafe extern "C" fn putwc(c: u32, f: *mut c_void) -> u32 {
22816    fputwc(c as c_int, f as *mut FILE) as u32
22817}
22818
22819#[no_mangle]
22820pub unsafe extern "C" fn __uflow(f: *mut c_void) -> c_int {
22821    fgetc(f as *mut FILE)
22822}
22823
22824#[no_mangle]
22825pub unsafe extern "C" fn __xmknod(_ver: c_int, path: *const c_char, mode: c_uint, dev: u64) -> c_int {
22826    mknod(path, mode, dev)
22827}
22828
22829#[no_mangle]
22830pub unsafe extern "C" fn __xmknodat(_ver: c_int, dirfd: c_int, path: *const c_char, mode: c_uint, dev: u64) -> c_int {
22831    mknodat(dirfd, path, mode, dev)
22832}
22833
22834#[no_mangle]
22835pub 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 {
22836    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);
22837    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
22838}
22839
22840#[no_mangle]
22841pub unsafe extern "C" fn open_by_handle_at(mount_fd: c_int, handle: *mut c_void, flags: c_int) -> c_int {
22842    let r = <Arch as Syscalls>::syscall3(sysno(304, 265), mount_fd as i64, handle as i64, flags as i64);
22843    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_int }
22844}
22845
22846#[no_mangle]
22847pub unsafe extern "C" fn dn_skipname(comp: *const u8, eom: *const u8) -> c_int {
22848    let p = dns_skip_name(comp, eom);
22849    if p <= eom { (p as isize - comp as isize) as c_int } else { -1 }
22850}
22851
22852#[no_mangle]
22853pub 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 {
22854    if exp.is_null() || dst.is_null() || dstsiz <= 0 { return -1; }
22855    let mut o = 0usize;
22856    let mut p = exp;
22857    loop {
22858        let start = p;
22859        while *p != 0 && *p != b'.' as c_char { p = p.add(1); }
22860        let l = p as usize - start as usize;
22861        if l > 63 || o + l + 2 > dstsiz as usize { return -1; }
22862        *dst.add(o) = l as u8; o += 1;
22863        core::ptr::copy_nonoverlapping(start as *const u8, dst.add(o), l);
22864        o += l;
22865        if *p == 0 { break; }
22866        p = p.add(1);
22867    }
22868    if o + 1 > dstsiz as usize { return -1; }
22869    *dst.add(o) = 0;
22870    (o + 1) as c_int
22871}
22872
22873// ============================================================
22874// Shadow database
22875// ============================================================
22876
22877#[repr(C)]
22878#[derive(Copy, Clone)]
22879pub struct Spwd {
22880    pub sp_namp: *mut c_char,
22881    pub sp_pwdp: *mut c_char,
22882    pub sp_lstchg: c_long,
22883    pub sp_min: c_long,
22884    pub sp_max: c_long,
22885    pub sp_warn: c_long,
22886    pub sp_inact: c_long,
22887    pub sp_expire: c_long,
22888    pub sp_flag: c_ulong,
22889}
22890
22891static mut SPWD_ENT: Spwd = Spwd {
22892    sp_namp: core::ptr::null_mut(), sp_pwdp: core::ptr::null_mut(),
22893    sp_lstchg: 0, sp_min: 0, sp_max: 0, sp_warn: 0, sp_inact: 0,
22894    sp_expire: 0, sp_flag: 0,
22895};
22896static mut SPWD_BUF: [c_char; 1024] = [0; 1024];
22897static mut SPWD_FILE: *mut FILE = core::ptr::null_mut();
22898
22899unsafe fn parse_spwd(line: *const c_char, ent: *mut Spwd, buf: *mut c_char, buflen: usize) -> bool {
22900    let mut src = line;
22901    let mut o = 0usize;
22902    let mut fields: [*mut c_char; 9] = [core::ptr::null_mut(); 9];
22903    let mut n = 0usize;
22904    while n < 9 {
22905        let start = o;
22906        while *src != 0 && *src != b':' as c_char {
22907            if o + 1 >= buflen { return false; }
22908            *buf.add(o) = *src;
22909            o += 1;
22910            src = src.add(1);
22911        }
22912        *buf.add(o) = 0;
22913        o += 1;
22914        fields[n] = buf.add(start);
22915        n += 1;
22916        if *src == 0 { break; }
22917        src = src.add(1);
22918    }
22919    if n < 9 { return false; }
22920    (*ent).sp_namp = fields[0];
22921    (*ent).sp_pwdp = fields[1];
22922    (*ent).sp_lstchg = crate::strtol(fields[2], core::ptr::null_mut(), 10) as c_long;
22923    (*ent).sp_min = crate::strtol(fields[3], core::ptr::null_mut(), 10) as c_long;
22924    (*ent).sp_max = crate::strtol(fields[4], core::ptr::null_mut(), 10) as c_long;
22925    (*ent).sp_warn = crate::strtol(fields[5], core::ptr::null_mut(), 10) as c_long;
22926    (*ent).sp_inact = crate::strtol(fields[6], core::ptr::null_mut(), 10) as c_long;
22927    (*ent).sp_expire = crate::strtol(fields[7], core::ptr::null_mut(), 10) as c_long;
22928    (*ent).sp_flag = crate::strtoul(fields[8], core::ptr::null_mut(), 10) as c_ulong;
22929    true
22930}
22931
22932#[no_mangle]
22933pub unsafe extern "C" fn setspent() {
22934    endspent();
22935    SPWD_FILE = crate::fopen(b"/etc/shadow\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
22936}
22937
22938#[no_mangle]
22939pub unsafe extern "C" fn endspent() {
22940    if !SPWD_FILE.is_null() { crate::fclose(SPWD_FILE); SPWD_FILE = core::ptr::null_mut(); }
22941}
22942
22943#[no_mangle]
22944pub unsafe extern "C" fn getspent() -> *mut Spwd {
22945    if SPWD_FILE.is_null() { setspent(); if SPWD_FILE.is_null() { return core::ptr::null_mut(); } }
22946    let mut line = [0 as c_char; 1024];
22947    loop {
22948        if crate::fgets(line.as_mut_ptr(), 1024, SPWD_FILE).is_null() { return core::ptr::null_mut(); }
22949        if parse_spwd(line.as_ptr(), &raw mut SPWD_ENT, SPWD_BUF.as_mut_ptr(), SPWD_BUF.len()) {
22950            return &raw mut SPWD_ENT;
22951        }
22952    }
22953}
22954
22955#[no_mangle]
22956pub unsafe extern "C" fn fgetspent(f: *mut FILE) -> *mut Spwd {
22957    if f.is_null() { return core::ptr::null_mut(); }
22958    let mut line = [0 as c_char; 1024];
22959    loop {
22960        if crate::fgets(line.as_mut_ptr(), 1024, f).is_null() { return core::ptr::null_mut(); }
22961        if parse_spwd(line.as_ptr(), &raw mut SPWD_ENT, SPWD_BUF.as_mut_ptr(), SPWD_BUF.len()) {
22962            return &raw mut SPWD_ENT;
22963        }
22964    }
22965}
22966
22967#[no_mangle]
22968pub unsafe extern "C" fn getspnam(name: *const c_char) -> *mut Spwd {
22969    if name.is_null() { return core::ptr::null_mut(); }
22970    setspent();
22971    loop {
22972        let sp = getspent();
22973        if sp.is_null() { break; }
22974        if crate::strcmp((*sp).sp_namp as *const u8, name as *const u8) == 0 { endspent(); return sp; }
22975    }
22976    endspent();
22977    core::ptr::null_mut()
22978}
22979
22980#[no_mangle]
22981pub 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 {
22982    if result.is_null() { return EINVAL; }
22983    let p = getspnam(name);
22984    if p.is_null() { *result = core::ptr::null_mut(); 0 } else { *sp = *p; *result = sp; 0 }
22985}
22986
22987#[no_mangle]
22988pub unsafe extern "C" fn putspent(sp: *const Spwd, f: *mut FILE) -> c_int {
22989    if sp.is_null() || f.is_null() { return -1; }
22990    crate::fprintf(f, b"%s:%s:%ld:%ld:%ld:%ld:%ld:%ld:%lu\\n\0".as_ptr() as *const c_char,
22991        (*sp).sp_namp, (*sp).sp_pwdp, (*sp).sp_lstchg, (*sp).sp_min, (*sp).sp_max,
22992        (*sp).sp_warn, (*sp).sp_inact, (*sp).sp_expire, (*sp).sp_flag)
22993}
22994
22995#[no_mangle]
22996pub unsafe extern "C" fn getgrouplist(user: *const c_char, group: u32, groups: *mut u32, ngroups: *mut i32) -> c_int {
22997    if user.is_null() || groups.is_null() || ngroups.is_null() { return -1; }
22998    let max = *ngroups as usize;
22999    let mut n = 0usize;
23000    if n < max { *groups.add(n) = group; }
23001    n += 1;
23002    setgrent();
23003    loop {
23004        let g = getgrent();
23005        if g.is_null() { break; }
23006        if (*g).gr_gid == group { continue; }
23007        let mut found = false;
23008        let mut i = 0;
23009        while !(*(*g).gr_mem.add(i)).is_null() {
23010            if crate::strcmp(*(*g).gr_mem.add(i) as *const u8, user as *const u8) == 0 {
23011                found = true;
23012                break;
23013            }
23014            i += 1;
23015        }
23016        if found {
23017            if n < max { *groups.add(n) = (*g).gr_gid; }
23018            n += 1;
23019        }
23020    }
23021    endgrent();
23022    if n > max { *ngroups = n as i32; return -1; }
23023    *ngroups = n as i32;
23024    n as c_int
23025}