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::{AtomicBool, AtomicI32, AtomicPtr, AtomicU32, AtomicUsize, Ordering};
21
22macro_rules! ERRNO {
23    () => { *errno_ptr() };
24}
25
26// h_errno shares the TCB with errno: 0x30 is errno, 0x34 is the free slot
27// before the vDSO getrandom state at 0x38.  The exported `h_errno` symbol is
28// the fallback for static programs and threads without a TCB, matching musl.
29macro_rules! H_ERRNO {
30    () => { *h_errno_ptr() };
31}
32
33include!("encoding_tables.rs");
34include!("math_helpers.rs");
35include!("math_bitmanip.rs");
36include!("math_sqrtfmod.rs");
37include!("math_trig.rs");
38include!("math_exp.rs");
39include!("math_erf.rs");
40include!("math_lgamma.rs");
41include!("math_tgamma.rs");
42include!("math_bessel.rs");
43include!("alloc.rs");
44include!("math_log.rs");
45include!("math_pow.rs");
46include!("math_hypot.rs");
47include!("math_hyperbolic.rs");
48include!("math_invtrig.rs");
49include!("math_lrint.rs");
50include!("math_long_double.rs");
51include!("string_fast.rs");
52include!("vdso.rs");
53include!("arch.rs");
54
55// ============================================================
56// errno
57// ============================================================
58
59const EILSEQ: c_int = 84;
60const EINVAL: c_int = 22;
61const EFAULT: c_int = 14;
62const E2BIG: c_int = 7;
63const EIO: c_int = 5;
64const ENXIO: c_int = 6;
65const EBADF: c_int = 9;
66const ERANGE: c_int = 34;
67const ENOSYS: c_int = 38;
68const ENOENT: c_int = 2;
69const EEXIST: c_int = 17;
70const ENOTDIR: c_int = 20;
71const EMFILE: c_int = 24;
72const ENOSPC: c_int = 28;
73const ENAMETOOLONG: c_int = 36;
74const ELOOP: c_int = 40;
75const EIDRM: c_int = 43;
76const ENOTSUP: c_int = 95;
77const EAFNOSUPPORT: c_int = 97;
78
79const LC_CTYPE: c_int = 0;
80const LC_NUMERIC: c_int = 1;
81const LC_TIME: c_int = 2;
82const LC_COLLATE: c_int = 3;
83const LC_MONETARY: c_int = 4;
84const LC_MESSAGES: c_int = 5;
85const LC_ALL: c_int = 6;
86const ENOMEM: c_int = 12;
87const EINTR: c_int = 4;
88const EPERM: c_int = 1;
89const EAGAIN: c_int = 11;
90const EBUSY: c_int = 16;
91const EDEADLK: c_int = 35;
92const ETIMEDOUT: c_int = 110;
93const ECANCELED: c_int = 125;
94const EOVERFLOW: c_int = 75;
95const EOWNERDEAD: c_int = 130;
96const ENOTRECOVERABLE: c_int = 131;
97
98// Static executables have no dynamic loader to build a TCB, so they keep the
99// traditional process-global errno. Dynamic programs store it in the TCB, just
100// below the thread pointer. The offset is inside the 256-byte TCB that
101// libc.so allocates for every thread (0x00 self pointer, 0x08 generation,
102// 0x28 stack canary).
103static mut ERRNO_FALLBACK: c_int = 0;
104static ERRNO_TLS_ACTIVE: AtomicUsize = AtomicUsize::new(0);
105const ERRNO_TCB_OFFSET: usize = 0x30;
106
107#[inline]
108unsafe fn errno_ptr() -> *mut c_int {
109    if ERRNO_TLS_ACTIVE.load(Ordering::Relaxed) == 0 {
110        return core::ptr::addr_of_mut!(ERRNO_FALLBACK);
111    }
112    // tcb_slot() performs the TP read and self-pointer validation once.
113    let slot = tcb_slot(ERRNO_TCB_OFFSET);
114    if slot.is_null() {
115        core::ptr::addr_of_mut!(ERRNO_FALLBACK)
116    } else {
117        slot as *mut c_int
118    }
119}
120
121/// Called once from __libc_start_main. The dynamic loader has already set up
122/// a TCB for dynamic programs; static programs leave %fs / TP at zero.
123unsafe fn errno_init() {
124    let tp = arch_get_tp();
125    #[cfg(target_arch = "x86_64")]
126    let tcb = tp;
127    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
128    let tcb = tp.wrapping_sub(256);
129    if tp != 0 && core::ptr::read(tcb as *const usize) == tcb {
130        ERRNO_TLS_ACTIVE.store(1, Ordering::Relaxed);
131    }
132}
133
134/// Normalize a raw syscall result the way musl's `__syscall_ret` does:
135/// turn `-errno` into `-1` and publish the error through `errno`.
136#[inline]
137unsafe fn syscall_ret(r: i64) -> i64 {
138    if r < 0 {
139        *errno_ptr() = (-r) as c_int;
140        -1
141    } else {
142        r
143    }
144}
145
146#[no_mangle]
147pub unsafe extern "C" fn __errno_location() -> *mut c_int {
148    errno_ptr()
149}
150
151unsafe fn h_errno_ptr() -> *mut c_int {
152    if ERRNO_TLS_ACTIVE.load(Ordering::Relaxed) == 0 {
153        return core::ptr::addr_of_mut!(h_errno);
154    }
155    // errno occupies 0x30..0x34; h_errno is the next int in the TCB.
156    errno_ptr().add(1)
157}
158
159#[cfg(not(test))]
160#[panic_handler]
161fn panic(_: &core::panic::PanicInfo) -> ! {
162    // A libc cannot unwind; looping here turns every internal panic into a
163    // permanent CPU spin (and may leave locks held).  Match abort semantics
164    // so the process dies with SIGABRT and the failure is observable.
165    unsafe { abort() }
166}
167
168// Required by the Rust runtime; panic=abort never unwinds.
169#[cfg(not(test))]
170#[no_mangle]
171pub extern "C" fn rust_eh_personality() {}
172
173// ============================================================
174// Constants
175// ============================================================
176
177const PROT_READ: i32 = 1;
178const PROT_WRITE: i32 = 2;
179const MAP_SHARED: i32 = 0x01;
180const MAP_PRIVATE: i32 = 0x02;
181const MAP_ANONYMOUS: i32 = 0x20;
182
183// ============================================================
184// Syscall wrappers (raw, no_std)
185// ============================================================
186
187#[inline]
188unsafe fn sys_write(fd: i64, buf: *const u8, count: usize) -> i64 {
189    <Arch as Syscalls>::syscall3(SYS_WRITE, fd as i64, buf as i64, count as i64)
190}
191
192#[inline]
193unsafe fn sys_read(fd: i64, buf: *mut u8, count: usize) -> i64 {
194    <Arch as Syscalls>::syscall3(SYS_READ, fd as i64, buf as i64, count as i64)
195}
196
197#[inline]
198unsafe fn sys_open(path: *const u8, flags: i64, mode: i64) -> i64 {
199    <Arch as Syscalls>::syscall4(SYS_OPENAT, AT_FDCWD as i64, path as i64, flags as i64, mode as i64)
200}
201
202#[inline]
203unsafe fn sys_close(fd: i64) -> i64 {
204    <Arch as Syscalls>::syscall1(SYS_CLOSE, fd as i64)
205}
206
207#[inline]
208unsafe fn sys_lseek(fd: i64, offset: i64, whence: i64) -> i64 {
209    <Arch as Syscalls>::syscall3(SYS_LSEEK, fd as i64, offset as i64, whence as i64)
210}
211
212unsafe fn sys_mmap(
213    addr: *mut u8,
214    length: usize,
215    prot: i32,
216    flags: i32,
217    fd: i32,
218    offset: i64,
219) -> *mut u8 {
220    let result = <Arch as Syscalls>::syscall6(SYS_MMAP, addr as i64, length as i64, prot as i64, flags as i64, fd as i64, offset);
221    if result < 0 && result > -4096 {
222        ERRNO!() = (-result) as c_int;
223        return MMAP_FAILED;
224    }
225    result as *mut u8
226}
227
228unsafe fn sys_munmap(addr: *mut u8, length: usize) -> i64 {
229    <Arch as Syscalls>::syscall2(SYS_MUNMAP, addr as i64, length as i64)
230}
231
232// ============================================================
233// String/memory functions
234// ============================================================
235
236// strlen, memcpy, memset, memmove and memcmp live in string_fast.rs.
237
238#[no_mangle]
239pub unsafe extern "C" fn bcmp(s1: *const c_void, s2: *const c_void, n: usize) -> c_int {
240    memcmp(s1, s2, n)
241}
242
243// strcmp lives in string_fast.rs.
244
245#[no_mangle]
246pub unsafe extern "C" fn strncmp(s1: *const u8, s2: *const u8, n: usize) -> c_int {
247    let mut i = 0;
248    while i < n {
249        let a = *s1.add(i);
250        let b = *s2.add(i);
251        if a != b {
252            return a as c_int - b as c_int;
253        }
254        if a == 0 {
255            return 0;
256        }
257        i += 1;
258    }
259    0
260}
261
262#[no_mangle]
263pub unsafe extern "C" fn strcpy(dst: *mut u8, src: *const u8) -> *mut u8 {
264    let mut i = 0;
265    loop {
266        let c = *src.add(i);
267        *dst.add(i) = c;
268        if c == 0 {
269            break;
270        }
271        i += 1;
272    }
273    dst
274}
275
276#[no_mangle]
277pub unsafe extern "C" fn strncpy(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 {
278    let mut i = 0;
279    while i < n && *src.add(i) != 0 {
280        *dst.add(i) = *src.add(i);
281        i += 1;
282    }
283    while i < n {
284        *dst.add(i) = 0;
285        i += 1;
286    }
287    dst
288}
289
290#[no_mangle]
291pub unsafe extern "C" fn strcat(dst: *mut u8, src: *const u8) -> *mut u8 {
292    let mut i = 0;
293    while *dst.add(i) != 0 {
294        i += 1;
295    }
296    let mut j = 0;
297    loop {
298        let c = *src.add(j);
299        *dst.add(i + j) = c;
300        if c == 0 {
301            break;
302        }
303        j += 1;
304    }
305    dst
306}
307
308#[no_mangle]
309pub unsafe extern "C" fn strncat(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 {
310    let mut i = 0;
311    while *dst.add(i) != 0 {
312        i += 1;
313    }
314    let mut j = 0;
315    while j < n && *src.add(j) != 0 {
316        *dst.add(i + j) = *src.add(j);
317        j += 1;
318    }
319    *dst.add(i + j) = 0;
320    dst
321}
322
323#[no_mangle]
324pub unsafe extern "C" fn strlcpy(dst: *mut u8, src: *const u8, n: usize) -> usize {
325    let l = strlen(src as *const c_char);
326    if n > 0 {
327        let c = if l < n { l } else { n - 1 };
328        core::ptr::copy_nonoverlapping(src, dst, c);
329        *dst.add(c) = 0;
330    }
331    l
332}
333
334#[no_mangle]
335pub unsafe extern "C" fn strlcat(dst: *mut u8, src: *const u8, n: usize) -> usize {
336    let dl = strlen(dst as *const c_char);
337    let sl = strlen(src as *const c_char);
338    if dl >= n { return n + sl; }
339    let c = if sl < n - dl { sl } else { n - dl - 1 };
340    core::ptr::copy_nonoverlapping(src, dst.add(dl), c);
341    *dst.add(dl + c) = 0;
342    dl + sl
343}
344
345#[no_mangle]
346pub unsafe extern "C" fn bcopy(src: *const c_void, dst: *mut c_void, n: usize) {
347    core::ptr::copy(src as *const u8, dst as *mut u8, n);
348}
349
350#[no_mangle]
351pub unsafe extern "C" fn bzero(s: *mut c_void, n: usize) {
352    core::ptr::write_bytes(s as *mut u8, 0, n);
353}
354
355#[no_mangle]
356pub unsafe extern "C" fn strndup(s: *const c_char, n: usize) -> *mut c_char {
357    let mut len = 0;
358    while len < n && *s.add(len) != 0 {
359        len += 1;
360    }
361    let p = malloc(len + 1) as *mut c_char;
362    if p.is_null() {
363        return core::ptr::null_mut();
364    }
365    core::ptr::copy_nonoverlapping(s, p, len);
366    *p.add(len) = 0;
367    p
368}
369
370#[no_mangle]
371pub unsafe extern "C" fn strchr(s: *const u8, c: c_int) -> *mut u8 {
372    let target = c as u8;
373    let mut i = 0;
374    loop {
375        let ch = *s.add(i);
376        if ch == target {
377            return s.add(i) as *mut u8;
378        }
379        if ch == 0 {
380            return null_mut();
381        }
382        i += 1;
383    }
384}
385
386#[no_mangle]
387pub unsafe extern "C" fn strrchr(s: *const u8, c: c_int) -> *mut u8 {
388    let target = c as u8;
389    let mut i = 0;
390    let mut last: *mut u8 = null_mut();
391    loop {
392        let ch = *s.add(i);
393        if ch == target {
394            last = s.add(i) as *mut u8;
395        }
396        if ch == 0 {
397            return last;
398        }
399        i += 1;
400    }
401}
402
403#[no_mangle]
404pub unsafe extern "C" fn strnlen(s: *const u8, maxlen: usize) -> usize {
405    let mut i = 0;
406    while i < maxlen && *s.add(i) != 0 {
407        i += 1;
408    }
409    i
410}
411
412#[no_mangle]
413pub unsafe extern "C" fn strcspn(s: *const u8, reject: *const u8) -> usize {
414    let mut i = 0;
415    loop {
416        let c = *s.add(i);
417        if c == 0 {
418            return i;
419        }
420        let mut j = 0;
421        loop {
422            let r = *reject.add(j);
423            if r == 0 {
424                break;
425            }
426            if c == r {
427                return i;
428            }
429            j += 1;
430        }
431        i += 1;
432    }
433}
434
435#[no_mangle]
436pub unsafe extern "C" fn strspn(s: *const u8, accept: *const u8) -> usize {
437    let mut i = 0;
438    loop {
439        let c = *s.add(i);
440        if c == 0 {
441            return i;
442        }
443        let mut found = false;
444        let mut j = 0;
445        loop {
446            let a = *accept.add(j);
447            if a == 0 {
448                break;
449            }
450            if c == a {
451                found = true;
452                break;
453            }
454            j += 1;
455        }
456        if !found {
457            return i;
458        }
459        i += 1;
460    }
461}
462
463#[no_mangle]
464pub unsafe extern "C" fn strpbrk(s: *const u8, accept: *const u8) -> *mut u8 {
465    let mut i = 0;
466    loop {
467        let c = *s.add(i);
468        if c == 0 {
469            return null_mut();
470        }
471        let mut j = 0;
472        loop {
473            let a = *accept.add(j);
474            if a == 0 {
475                break;
476            }
477            if c == a {
478                return s.add(i) as *mut u8;
479            }
480            j += 1;
481        }
482        i += 1;
483    }
484}
485
486#[no_mangle]
487pub unsafe extern "C" fn strstr(haystack: *const u8, needle: *const u8) -> *mut u8 {
488    if *needle == 0 {
489        return haystack as *mut u8;
490    }
491    let mut i = 0;
492    loop {
493        let h = *haystack.add(i);
494        if h == 0 {
495            return null_mut();
496        }
497        if h == *needle {
498            let mut j = 0;
499            loop {
500                let n = *needle.add(j);
501                if n == 0 {
502                    return haystack.add(i) as *mut u8;
503                }
504                if *haystack.add(i + j) != n {
505                    break;
506                }
507                j += 1;
508            }
509        }
510        i += 1;
511    }
512}
513
514#[no_mangle]
515pub unsafe extern "C" fn memchr(s: *const u8, c: c_int, n: usize) -> *mut u8 {
516    let target = c as u8;
517    let mut i = 0;
518    while i < n {
519        if *s.add(i) == target {
520            return s.add(i) as *mut u8;
521        }
522        i += 1;
523    }
524    null_mut()
525}
526
527#[no_mangle]
528pub unsafe extern "C" fn memrchr(s: *const u8, c: c_int, n: usize) -> *mut u8 {
529    let target = c as u8;
530    let mut i = n;
531    while i > 0 {
532        i -= 1;
533        if *s.add(i) == target {
534            return s.add(i) as *mut u8;
535        }
536    }
537    null_mut()
538}
539
540#[no_mangle]
541pub unsafe extern "C" fn memmem(
542    haystack: *const c_void, haystacklen: usize,
543    needle: *const c_void, needlelen: usize,
544) -> *mut c_void {
545    if needlelen == 0 { return haystack as *mut c_void; }
546    if haystacklen < needlelen { return null_mut(); }
547    let h = haystack as *const u8;
548    let n = needle as *const u8;
549    let last = haystacklen - needlelen;
550    for i in 0..=last {
551        if *h.add(i) == *n && memcmp(h.add(i) as *const c_void, n as *const c_void, needlelen) == 0 {
552            return h.add(i) as *mut c_void;
553        }
554    }
555    null_mut()
556}
557
558#[no_mangle]
559pub unsafe extern "C" fn strtok(s: *mut u8, delim: *const u8) -> *mut u8 {
560    static mut STATE: *mut u8 = core::ptr::null_mut();
561    let mut p = if s.is_null() { STATE } else { s };
562    if p.is_null() {
563        return core::ptr::null_mut();
564    }
565    loop {
566        let c = *p;
567        if c == 0 {
568            STATE = core::ptr::null_mut();
569            return core::ptr::null_mut();
570        }
571        let mut is_delim = false;
572        let mut i = 0;
573        loop {
574            let d = *delim.add(i);
575            if d == 0 {
576                break;
577            }
578            if c == d {
579                is_delim = true;
580                break;
581            }
582            i += 1;
583        }
584        if !is_delim {
585            break;
586        }
587        p = p.add(1);
588    }
589    let start = p;
590    loop {
591        let c = *p;
592        if c == 0 {
593            STATE = core::ptr::null_mut();
594            return start;
595        }
596        let mut is_delim = false;
597        let mut i = 0;
598        loop {
599            let d = *delim.add(i);
600            if d == 0 {
601                break;
602            }
603            if c == d {
604                is_delim = true;
605                break;
606            }
607            i += 1;
608        }
609        if is_delim {
610            *p = 0;
611            STATE = p.add(1);
612            return start;
613        }
614        p = p.add(1);
615    }
616}
617
618// ============================================================
619// C type aliases
620// ============================================================
621
622type SizeT = usize;
623type SSizeT = isize;
624type mode_t = c_uint;
625type TimeT = c_long;
626type ClockT = c_long;
627type wchar_t = c_int;
628type wint_t = c_uint;
629type wctype_t = *const c_int;
630type wctrans_t = *const c_int;
631
632const WEOF: wint_t = 0xffffffff;
633
634#[repr(C)]
635pub struct tm {
636    pub tm_sec: c_int,
637    pub tm_min: c_int,
638    pub tm_hour: c_int,
639    pub tm_mday: c_int,
640    pub tm_mon: c_int,
641    pub tm_year: c_int,
642    pub tm_wday: c_int,
643    pub tm_yday: c_int,
644    pub tm_isdst: c_int,
645    pub tm_gmtoff: c_long,
646    pub tm_zone: *const c_char,
647}
648
649#[repr(C)]
650pub struct timeval {
651    pub tv_sec: TimeT,
652    pub tv_usec: c_long,
653}
654
655#[repr(C)]
656pub struct Timeb {
657    pub time: TimeT,
658    pub millitm: u16,
659    pub timezone: i16,
660    pub dstflag: u16,
661}
662
663// ============================================================
664// ctype.h
665// ============================================================
666
667const CT_UPPER: u8 = 1 << 0;
668const CT_LOWER: u8 = 1 << 1;
669const CT_DIGIT: u8 = 1 << 2;
670const CT_SPACE: u8 = 1 << 3;
671const CT_PUNCT: u8 = 1 << 4;
672const CT_CNTRL: u8 = 1 << 5;
673const CT_BLANK: u8 = 1 << 6;
674const CT_XDIGIT: u8 = 1 << 7;
675
676const CT_TABLE: [u8; 128] = {
677    let mut t = [0u8; 128];
678    let mut i = 0;
679    while i < 128 {
680        let c = i as u8;
681        let mut flags = 0u8;
682        if c >= b'A' && c <= b'Z' {
683            flags |= CT_UPPER;
684        }
685        if c >= b'a' && c <= b'z' {
686            flags |= CT_LOWER;
687        }
688        if c >= b'0' && c <= b'9' {
689            flags |= CT_DIGIT;
690        }
691        if c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == b'\x0c' || c == b'\x0b' {
692            flags |= CT_SPACE;
693        }
694        if (c >= b'!' && c <= b'/')
695            || (c >= b':' && c <= b'@')
696            || (c >= b'[' && c <= b'`')
697            || (c >= b'{' && c <= b'~')
698        {
699            flags |= CT_PUNCT;
700        }
701        if c < 0x20 || c == 0x7f {
702            flags |= CT_CNTRL;
703        }
704        if c == b' ' || c == b'\t' {
705            flags |= CT_BLANK;
706        }
707        if (c >= b'0' && c <= b'9') || (c >= b'A' && c <= b'F') || (c >= b'a' && c <= b'f') {
708            flags |= CT_XDIGIT;
709        }
710        t[i] = flags;
711        i += 1;
712    }
713    t
714};
715
716#[inline]
717fn ct_flags(c: c_int) -> u8 {
718    if c < 0 || c > 127 {
719        0
720    } else {
721        CT_TABLE[c as usize]
722    }
723}
724
725#[no_mangle]
726pub extern "C" fn isalnum(c: c_int) -> c_int {
727    (ct_flags(c) & (CT_UPPER | CT_LOWER | CT_DIGIT) != 0) as c_int
728}
729
730#[no_mangle]
731pub extern "C" fn isalpha(c: c_int) -> c_int {
732    (ct_flags(c) & (CT_UPPER | CT_LOWER) != 0) as c_int
733}
734
735#[no_mangle]
736pub extern "C" fn isascii(c: c_int) -> c_int {
737    ((c as u32) <= 127) as c_int
738}
739
740#[no_mangle]
741pub extern "C" fn isblank(c: c_int) -> c_int {
742    (ct_flags(c) & CT_BLANK != 0) as c_int
743}
744
745#[no_mangle]
746pub extern "C" fn iscntrl(c: c_int) -> c_int {
747    (ct_flags(c) & CT_CNTRL != 0) as c_int
748}
749
750#[no_mangle]
751pub extern "C" fn isdigit(c: c_int) -> c_int {
752    (ct_flags(c) & CT_DIGIT != 0) as c_int
753}
754
755#[no_mangle]
756pub extern "C" fn isgraph(c: c_int) -> c_int {
757    (ct_flags(c) & (CT_UPPER | CT_LOWER | CT_DIGIT | CT_PUNCT) != 0) as c_int
758}
759
760#[no_mangle]
761pub extern "C" fn islower(c: c_int) -> c_int {
762    (ct_flags(c) & CT_LOWER != 0) as c_int
763}
764
765#[no_mangle]
766pub extern "C" fn isprint(c: c_int) -> c_int {
767    let flags = ct_flags(c);
768    (flags & (CT_UPPER | CT_LOWER | CT_DIGIT | CT_PUNCT | CT_BLANK) != 0) as c_int
769}
770
771#[no_mangle]
772pub extern "C" fn ispunct(c: c_int) -> c_int {
773    (ct_flags(c) & CT_PUNCT != 0) as c_int
774}
775
776#[no_mangle]
777pub extern "C" fn isspace(c: c_int) -> c_int {
778    (ct_flags(c) & CT_SPACE != 0) as c_int
779}
780
781#[no_mangle]
782pub extern "C" fn isupper(c: c_int) -> c_int {
783    (ct_flags(c) & CT_UPPER != 0) as c_int
784}
785
786#[no_mangle]
787pub extern "C" fn isxdigit(c: c_int) -> c_int {
788    (ct_flags(c) & CT_XDIGIT != 0) as c_int
789}
790
791#[no_mangle]
792pub extern "C" fn tolower(c: c_int) -> c_int {
793    if (ct_flags(c) & CT_UPPER) != 0 {
794        c + (b'a' as c_int - b'A' as c_int)
795    } else {
796        c
797    }
798}
799
800#[no_mangle]
801pub extern "C" fn toupper(c: c_int) -> c_int {
802    if (ct_flags(c) & CT_LOWER) != 0 {
803        c - (b'a' as c_int - b'A' as c_int)
804    } else {
805        c
806    }
807}
808
809// ============================================================
810// stdlib.h: integer conversion, abs, rand
811// ============================================================
812
813unsafe fn parse_digit(c: u8, base: c_int) -> Option<u8> {
814    if c == 0 { return None; }
815    let d = if c >= b'0' && c <= b'9' {
816        c - b'0'
817    } else if c >= b'a' && c <= b'z' {
818        c - b'a' + 10
819    } else if c >= b'A' && c <= b'Z' {
820        c - b'A' + 10
821    } else {
822        return None;
823    };
824    if (d as c_int) < base {
825        Some(d)
826    } else {
827        None
828    }
829}
830
831unsafe fn parse_prefix(s: *const u8, base: *mut c_int) -> *const u8 {
832    let mut p = s;
833    if *base == 0 {
834        if *p == b'0' {
835            if (*p.add(1) == b'x' || *p.add(1) == b'X') && parse_digit(*p.add(2), 16).is_some() {
836                *base = 16;
837                p = p.add(2);
838            } else {
839                *base = 8;
840            }
841        } else {
842            *base = 10;
843        }
844    } else if *base == 16 {
845        if *p == b'0' && (*p.add(1) == b'x' || *p.add(1) == b'X') && parse_digit(*p.add(2), 16).is_some() {
846            p = p.add(2);
847        }
848    }
849    p
850}
851
852unsafe fn strtox(
853    s: *const c_char,
854    endptr: *mut *mut c_char,
855    mut base: c_int,
856    pos_limit: u64,
857    neg_limit: u64,
858) -> (u64, bool, bool) {
859    let s0 = s as *const u8;
860    let mut p = s0;
861    while isspace(*p as c_int) != 0 {
862        p = p.add(1);
863    }
864
865    if base < 0 || base == 1 || base > 36 {
866        if !endptr.is_null() {
867            *endptr = s as *mut c_char;
868        }
869        ERRNO!() = EINVAL;
870        return (0, false, false);
871    }
872
873    let mut neg = false;
874    match *p {
875        b'-' => { neg = true; p = p.add(1); }
876        b'+' => p = p.add(1),
877        _ => {}
878    }
879
880    p = parse_prefix(p, &mut base);
881
882    let limit = if neg { neg_limit } else { pos_limit };
883    let mut val: u64 = 0;
884    let mut any = false;
885    while let Some(d) = parse_digit(*p, base) {
886        any = true;
887        if val > (limit - d as u64) / base as u64 {
888            while parse_digit(*p, base).is_some() { p = p.add(1); }
889            if !endptr.is_null() { *endptr = p as *mut c_char; }
890            ERRNO!() = ERANGE;
891            return (limit, true, neg);
892        }
893        val = val * base as u64 + d as u64;
894        p = p.add(1);
895    }
896
897    if !endptr.is_null() {
898        *endptr = if any { p as *mut c_char } else { s as *mut c_char };
899    }
900    (val, false, neg)
901}
902
903#[no_mangle]
904pub unsafe extern "C" fn strtol(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_long {
905    let pos_limit = c_long::MAX as u64;
906    let neg_limit = pos_limit.wrapping_add(1);
907    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
908    if overflow {
909        return if neg { c_long::MIN } else { c_long::MAX };
910    }
911    if neg { val.wrapping_neg() as c_long } else { val as c_long }
912}
913
914#[no_mangle]
915pub unsafe extern "C" fn strtoul(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulong {
916    let limit = c_ulong::MAX as u64;
917    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
918    if overflow {
919        return c_ulong::MAX;
920    }
921    if neg { val.wrapping_neg() as c_ulong } else { val as c_ulong }
922}
923
924#[no_mangle]
925pub unsafe extern "C" fn strtoll(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_longlong {
926    let pos_limit = c_longlong::MAX as u64;
927    let neg_limit = pos_limit.wrapping_add(1);
928    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
929    if overflow {
930        return if neg { c_longlong::MIN } else { c_longlong::MAX };
931    }
932    if neg { val.wrapping_neg() as c_longlong } else { val as c_longlong }
933}
934
935#[no_mangle]
936pub unsafe extern "C" fn strtoull(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulonglong {
937    let limit = c_ulonglong::MAX as u64;
938    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
939    if overflow {
940        return c_ulonglong::MAX;
941    }
942    if neg { val.wrapping_neg() as c_ulonglong } else { val as c_ulonglong }
943}
944
945#[no_mangle]
946pub unsafe extern "C" fn atoi(s: *const c_char) -> c_int {
947    strtol(s, core::ptr::null_mut(), 10) as c_int
948}
949
950#[no_mangle]
951pub unsafe extern "C" fn atol(s: *const c_char) -> c_long {
952    strtol(s, core::ptr::null_mut(), 10)
953}
954
955#[no_mangle]
956pub unsafe extern "C" fn atoll(s: *const c_char) -> c_longlong {
957    strtoll(s, core::ptr::null_mut(), 10)
958}
959
960#[no_mangle]
961pub extern "C" fn abs(n: c_int) -> c_int {
962    if n < 0 {
963        -n
964    } else {
965        n
966    }
967}
968
969#[no_mangle]
970pub extern "C" fn labs(n: c_long) -> c_long {
971    if n < 0 {
972        -n
973    } else {
974        n
975    }
976}
977
978#[no_mangle]
979pub extern "C" fn llabs(n: c_longlong) -> c_longlong {
980    if n < 0 {
981        -n
982    } else {
983        n
984    }
985}
986
987static mut RAND_STATE: c_uint = 1;
988
989#[no_mangle]
990pub extern "C" fn srand(seed: c_uint) {
991    unsafe {
992        RAND_STATE = seed;
993    }
994}
995
996#[no_mangle]
997pub extern "C" fn rand() -> c_int {
998    unsafe {
999        RAND_STATE = RAND_STATE.wrapping_mul(1103515245).wrapping_add(12345);
1000        ((RAND_STATE >> 16) & 0x7fff) as c_int
1001    }
1002}
1003
1004// ============================================================
1005// stdlib.h: div, ldiv, lldiv
1006// ============================================================
1007
1008#[repr(C)]
1009pub struct div_t { pub quot: c_int, pub rem: c_int }
1010#[repr(C)]
1011pub struct ldiv_t { pub quot: c_long, pub rem: c_long }
1012#[repr(C)]
1013pub struct lldiv_t { pub quot: c_longlong, pub rem: c_longlong }
1014
1015#[no_mangle]
1016pub extern "C" fn div(num: c_int, den: c_int) -> div_t {
1017    div_t { quot: num / den, rem: num % den }
1018}
1019
1020#[no_mangle]
1021pub extern "C" fn ldiv(num: c_long, den: c_long) -> ldiv_t {
1022    ldiv_t { quot: num / den, rem: num % den }
1023}
1024
1025#[no_mangle]
1026pub extern "C" fn lldiv(num: c_longlong, den: c_longlong) -> lldiv_t {
1027    lldiv_t { quot: num / den, rem: num % den }
1028}
1029
1030// ============================================================
1031// bsearch
1032// ============================================================
1033
1034type CmpFn = unsafe extern "C" fn(*const c_void, *const c_void) -> c_int;
1035
1036#[no_mangle]
1037pub unsafe extern "C" fn bsearch(
1038    key: *const c_void,
1039    base: *const c_void,
1040    nel: usize,
1041    width: usize,
1042    cmp: CmpFn,
1043) -> *mut c_void {
1044    let mut base = base as *const u8;
1045    let mut nel = nel;
1046    while nel > 0 {
1047        let trial = base.add(width * (nel / 2));
1048        let sign = cmp(key, trial as *const c_void);
1049        if sign < 0 {
1050            nel /= 2;
1051        } else if sign > 0 {
1052            base = trial.add(width);
1053            nel -= nel / 2 + 1;
1054        } else {
1055            return trial as *mut c_void;
1056        }
1057    }
1058    null_mut()
1059}
1060
1061// ============================================================
1062// signal.h
1063// ============================================================
1064
1065pub const SA_RESTORER: c_ulong = 0x04000000;
1066
1067pub const SIG_DFL: usize = 0;
1068pub const SIG_IGN: usize = 1;
1069pub const SIG_ERR: usize = !0usize;
1070
1071pub const SIGHUP: c_int = 1;
1072pub const SIGINT: c_int = 2;
1073pub const SIGQUIT: c_int = 3;
1074pub const SIGILL: c_int = 4;
1075pub const SIGTRAP: c_int = 5;
1076pub const SIGABRT: c_int = 6;
1077pub const SIGIOT: c_int = 6;
1078pub const SIGBUS: c_int = 7;
1079pub const SIGFPE: c_int = 8;
1080pub const SIGKILL: c_int = 9;
1081pub const SIGUSR1: c_int = 10;
1082pub const SIGSEGV: c_int = 11;
1083pub const SIGUSR2: c_int = 12;
1084pub const SIGPIPE: c_int = 13;
1085pub const SIGALRM: c_int = 14;
1086pub const SIGTERM: c_int = 15;
1087pub const SIGSTKFLT: c_int = 16;
1088pub const SIGCHLD: c_int = 17;
1089pub const SIGCONT: c_int = 18;
1090pub const SIGSTOP: c_int = 19;
1091pub const SIGTSTP: c_int = 20;
1092pub const SIGTTIN: c_int = 21;
1093pub const SIGTTOU: c_int = 22;
1094pub const SIGURG: c_int = 23;
1095pub const SIGXCPU: c_int = 24;
1096pub const SIGXFSZ: c_int = 25;
1097pub const SIGVTALRM: c_int = 26;
1098pub const SIGPROF: c_int = 27;
1099pub const SIGWINCH: c_int = 28;
1100pub const SIGIO: c_int = 29;
1101pub const SIGPOLL: c_int = 29;
1102pub const SIGPWR: c_int = 30;
1103pub const SIGSYS: c_int = 31;
1104pub const SIGUNUSED: c_int = 31;
1105pub const _NSIG: c_int = 65;
1106
1107pub const SIG_BLOCK: c_int = 0;
1108pub const SIG_UNBLOCK: c_int = 1;
1109pub const SIG_SETMASK: c_int = 2;
1110
1111pub const SA_NOCLDSTOP: c_ulong = 1;
1112pub const SA_NOCLDWAIT: c_ulong = 2;
1113pub const SA_SIGINFO: c_ulong = 4;
1114pub const SA_ONSTACK: c_ulong = 0x08000000;
1115pub const SA_RESTART: c_ulong = 0x10000000;
1116pub const SA_NODEFER: c_ulong = 0x40000000;
1117pub const SA_RESETHAND: c_ulong = 0x80000000;
1118
1119pub const SS_ONSTACK: c_int = 1;
1120pub const SS_DISABLE: c_int = 2;
1121#[cfg(target_arch = "aarch64")]
1122pub const MINSIGSTKSZ: usize = 6144;
1123#[cfg(target_arch = "aarch64")]
1124pub const SIGSTKSZ: usize = 12288;
1125#[cfg(not(target_arch = "aarch64"))]
1126pub const MINSIGSTKSZ: usize = 2048;
1127#[cfg(not(target_arch = "aarch64"))]
1128pub const SIGSTKSZ: usize = 8192;
1129
1130pub const SI_USER: c_int = 0;
1131pub const SI_TKILL: c_int = -6;
1132
1133#[repr(C)]
1134pub struct timespec {
1135    pub tv_sec: c_long,
1136    pub tv_nsec: c_long,
1137}
1138
1139#[repr(C)]
1140pub struct siginfo_t {
1141    pub si_signo: c_int,
1142    pub si_errno: c_int,
1143    pub si_code: c_int,
1144    // The remaining bytes of the 128-byte siginfo_t are not accessed.
1145    _pad: [u8; 128 - 3 * core::mem::size_of::<c_int>()],
1146}
1147
1148#[repr(C)]
1149pub struct stack_t {
1150    pub ss_sp: *mut c_void,
1151    pub ss_flags: c_int,
1152    pub ss_size: usize,
1153}
1154
1155// Kernel ABI for rt_sigaction (x86_64/riscv64/aarch64 all use the same
1156// handler/flags/restorer/8-byte-mask layout).
1157#[repr(C)]
1158pub struct KSigAction {
1159    pub sa_handler: usize,
1160    pub sa_flags: c_ulong,
1161    pub sa_restorer: usize,
1162    pub sa_mask: [c_ulong; 1],
1163}
1164
1165// musl's public layout: handler, 128-byte sigset_t, flags, restorer.
1166#[repr(C)]
1167pub struct sigaction {
1168    pub sa_handler: usize,
1169    pub sa_mask: [u64; 16],
1170    pub sa_flags: c_int,
1171    pub sa_restorer: usize,
1172}
1173
1174pub type SigSetT = c_ulong;
1175
1176#[cfg(target_arch = "x86_64")]
1177core::arch::global_asm!(
1178    ".global sig_restorer",
1179    ".type sig_restorer, @function",
1180    "sig_restorer:",
1181    "mov eax, 15",
1182    "syscall",
1183);
1184
1185#[cfg(target_arch = "aarch64")]
1186core::arch::global_asm!(
1187    ".global sig_restorer",
1188    ".type sig_restorer, @function",
1189    "sig_restorer:",
1190    "mov x8, #139",
1191    "svc #0",
1192);
1193
1194#[cfg(target_arch = "riscv64")]
1195core::arch::global_asm!(
1196    ".global sig_restorer",
1197    ".type sig_restorer, @function",
1198    "sig_restorer:",
1199    "li a7, 139",
1200    "ecall",
1201);
1202
1203extern "C" {
1204    fn sig_restorer();
1205}
1206
1207#[inline]
1208unsafe fn sys_rt_sigaction(sig: c_int,
1209    act: *const KSigAction,
1210    oldact: *mut KSigAction,
1211    sigsetsize: usize,) -> i64 {
1212    <Arch as Syscalls>::syscall4(SYS_RT_SIGACTION, sig as i64, act as i64, oldact as i64, sigsetsize as i64)
1213}
1214
1215#[inline]
1216unsafe fn sys_rt_sigprocmask(how: c_int,
1217    set: *const SigSetT,
1218    oldset: *mut SigSetT,
1219    sigsetsize: usize,) -> i64 {
1220    <Arch as Syscalls>::syscall4(SYS_RT_SIGPROCMASK, how as i64, set as i64, oldset as i64, sigsetsize as i64)
1221}
1222
1223#[inline]
1224unsafe fn sys_rt_sigpending(set: *mut SigSetT, sigsetsize: usize) -> i64 {
1225    <Arch as Syscalls>::syscall2(SYS_RT_SIGPENDING, set as i64, sigsetsize as i64)
1226}
1227
1228#[inline]
1229unsafe fn sys_rt_sigsuspend(mask: *const SigSetT, sigsetsize: usize) -> i64 {
1230    <Arch as Syscalls>::syscall2(SYS_RT_SIGSUSPEND, mask as i64, sigsetsize as i64)
1231}
1232
1233#[inline]
1234unsafe fn sys_rt_sigtimedwait(set: *const SigSetT,
1235    info: *mut siginfo_t,
1236    timeout: *const timespec,
1237    sigsetsize: usize,) -> i64 {
1238    <Arch as Syscalls>::syscall4(SYS_RT_SIGTIMEDWAIT, set as i64, info as i64, timeout as i64, sigsetsize as i64)
1239}
1240
1241#[inline]
1242unsafe fn sys_sigaltstack(ss: *const stack_t, old_ss: *mut stack_t) -> i64 {
1243    <Arch as Syscalls>::syscall2(SYS_SIGALTSTACK, ss as i64, old_ss as i64)
1244}
1245
1246#[inline]
1247unsafe fn sys_tgkill(tgid: c_int, tid: c_int, sig: c_int) -> i64 {
1248    <Arch as Syscalls>::syscall3(SYS_TGKILL, tgid as i64, tid as i64, sig as i64)
1249}
1250
1251const CLOCK_REALTIME: c_int = 0;
1252const CLOCK_MONOTONIC: c_int = 1;
1253
1254#[inline]
1255unsafe fn sys_clock_gettime(clockid: c_int, ts: *mut timespec) -> i64 {
1256    <Arch as Syscalls>::syscall2(SYS_CLOCK_GETTIME, clockid as i64, ts as i64)
1257}
1258
1259// clock_gettime lives in vdso.rs: it prefers the kernel's vDSO entry point
1260// and only falls back to sys_clock_gettime() there.
1261
1262#[no_mangle]
1263pub unsafe extern "C" fn sigprocmask(
1264    how: c_int,
1265    set: *const SigSetT,
1266    oldset: *mut SigSetT,
1267) -> c_int {
1268    // mask out internal rt signals (32, 33) before touching the kernel
1269    let internal_mask: SigSetT = (1u64 << 31) | (1u64 << 32);
1270    let filtered: SigSetT;
1271    let set_ptr: *const SigSetT = if set.is_null() {
1272        set
1273    } else {
1274        filtered = *set & !internal_mask;
1275        &filtered
1276    };
1277    let r = sys_rt_sigprocmask(how, set_ptr, oldset, core::mem::size_of::<SigSetT>());
1278    if r < 0 {
1279        ERRNO!() = (-r) as c_int;
1280        return -1;
1281    }
1282    if !oldset.is_null() {
1283        *oldset &= !internal_mask;
1284    }
1285    0
1286}
1287
1288#[inline]
1289unsafe fn sys_kill(pid: c_int, sig: c_int) -> i64 {
1290    <Arch as Syscalls>::syscall2(SYS_KILL, pid as i64, sig as i64)
1291}
1292
1293#[inline]
1294unsafe fn sys_getpid() -> i64 {
1295    <Arch as Syscalls>::syscall0(SYS_GETPID)
1296}
1297
1298#[no_mangle]
1299pub unsafe extern "C" fn sigaction(
1300    signum: c_int,
1301    act: *const sigaction,
1302    oldact: *mut sigaction,
1303) -> c_int {
1304    let mut kact: KSigAction = core::mem::zeroed();
1305    let act_ptr = if act.is_null() {
1306        core::ptr::null()
1307    } else {
1308        kact.sa_handler = (*act).sa_handler;
1309        kact.sa_flags = ((*act).sa_flags as c_ulong) | SA_RESTORER;
1310        kact.sa_restorer = if (*act).sa_flags as c_ulong & SA_RESTORER != 0
1311            && (*act).sa_restorer != 0
1312        {
1313            (*act).sa_restorer
1314        } else {
1315            sig_restorer as *const () as usize
1316        };
1317        kact.sa_mask[0] = (*act).sa_mask[0];
1318        &kact
1319    };
1320    let mut kold: KSigAction = core::mem::zeroed();
1321    let old_ptr = if oldact.is_null() { core::ptr::null_mut() } else { &mut kold };
1322    let r = sys_rt_sigaction(signum, act_ptr, old_ptr, 8);
1323    if r < 0 {
1324        ERRNO!() = (-r) as c_int;
1325        return -1;
1326    }
1327    if !oldact.is_null() {
1328        (*oldact).sa_handler = kold.sa_handler;
1329        (*oldact).sa_flags = kold.sa_flags as c_int;
1330        (*oldact).sa_restorer = kold.sa_restorer;
1331        (*oldact).sa_mask = [0; 16];
1332        (*oldact).sa_mask[0] = kold.sa_mask[0];
1333    }
1334    0
1335}
1336
1337#[no_mangle]
1338pub unsafe extern "C" fn signal(signum: c_int, handler: usize) -> usize {
1339    // musl's signal() installs the handler with SA_RESTART, so interrupted
1340    // syscalls (waitpid, read, ...) are restarted automatically.
1341    let act = sigaction {
1342        sa_handler: handler,
1343        sa_mask: [0; 16],
1344        sa_flags: SA_RESTART as c_int,
1345        sa_restorer: 0,
1346    };
1347    let mut old: sigaction = core::mem::zeroed();
1348    if sigaction(signum, &act, &mut old) == -1 {
1349        SIG_ERR
1350    } else {
1351        old.sa_handler
1352    }
1353}
1354
1355#[no_mangle]
1356pub unsafe extern "C" fn kill(pid: c_int, sig: c_int) -> c_int {
1357    let r = sys_kill(pid, sig);
1358    syscall_ret(r) as c_int
1359}
1360
1361#[no_mangle]
1362pub unsafe extern "C" fn tgkill(tgid: c_int, tid: c_int, sig: c_int) -> c_int {
1363    let r = sys_tgkill(tgid, tid, sig);
1364    syscall_ret(r) as c_int
1365}
1366
1367#[no_mangle]
1368pub unsafe extern "C" fn getpid() -> c_int {
1369    sys_getpid() as c_int
1370}
1371
1372#[no_mangle]
1373pub unsafe extern "C" fn raise(sig: c_int) -> c_int {
1374    let r = sys_tgkill(sys_getpid() as c_int, sys_gettid() as c_int, sig);
1375    syscall_ret(r) as c_int
1376}
1377
1378#[no_mangle]
1379pub unsafe extern "C" fn sigemptyset(set: *mut SigSetT) -> c_int {
1380    *set = 0;
1381    0
1382}
1383
1384#[no_mangle]
1385pub unsafe extern "C" fn sigfillset(set: *mut SigSetT) -> c_int {
1386    // musl: all signals except 32 (SIGCANCEL) and 33 (SIGSYNCCALL)
1387    *set = 0xFFFF_FFFC_7FFF_FFFFu64;
1388    0
1389}
1390
1391#[no_mangle]
1392pub unsafe extern "C" fn sigaddset(set: *mut SigSetT, signum: c_int) -> c_int {
1393    let s = (signum as c_uint).wrapping_sub(1);
1394    if s as usize >= 64 {
1395        ERRNO!() = EINVAL;
1396        return -1;
1397    }
1398    // internal rt signals (32, 33) cannot be manipulated
1399    if signum >= 32 && signum < __libc_current_sigrtmin() {
1400        return 0;
1401    }
1402    *set |= 1u64 << s;
1403    0
1404}
1405
1406#[no_mangle]
1407pub unsafe extern "C" fn sigdelset(set: *mut SigSetT, signum: c_int) -> c_int {
1408    let s = (signum as c_uint).wrapping_sub(1);
1409    if s as usize >= 64 {
1410        ERRNO!() = EINVAL;
1411        return -1;
1412    }
1413    // internal rt signals (32, 33) are never members
1414    if signum >= 32 && signum < __libc_current_sigrtmin() {
1415        return 0;
1416    }
1417    *set &= !(1u64 << s);
1418    0
1419}
1420
1421#[no_mangle]
1422pub unsafe extern "C" fn sigismember(set: *const SigSetT, signum: c_int) -> c_int {
1423    let s = (signum as c_uint).wrapping_sub(1);
1424    if s as usize >= 64 { return 0; }
1425    // internal rt signals (32, 33) are never members
1426    if signum >= 32 && signum < __libc_current_sigrtmin() {
1427        return 0;
1428    }
1429    ((*set & (1u64 << s)) != 0) as c_int
1430}
1431
1432#[no_mangle]
1433pub unsafe extern "C" fn sigpending(set: *mut SigSetT) -> c_int {
1434    let r = sys_rt_sigpending(set, core::mem::size_of::<SigSetT>());
1435    syscall_ret(r) as c_int
1436}
1437
1438#[no_mangle]
1439pub unsafe extern "C" fn sigsuspend(mask: *const SigSetT) -> c_int {
1440    let r = sys_rt_sigsuspend(mask, core::mem::size_of::<SigSetT>());
1441    if r < 0 {
1442        ERRNO!() = (-r) as c_int;
1443    }
1444    -1
1445}
1446
1447#[no_mangle]
1448pub unsafe extern "C" fn sigtimedwait(
1449    mask: *const SigSetT,
1450    info: *mut siginfo_t,
1451    timeout: *const timespec,
1452) -> c_int {
1453    loop {
1454        let r = sys_rt_sigtimedwait(mask, info, timeout, core::mem::size_of::<SigSetT>());
1455        if r >= 0 {
1456            return r as c_int;
1457        }
1458        let e = (-r) as c_int;
1459        if e != EINTR {
1460            ERRNO!() = e;
1461            return -1;
1462        }
1463    }
1464}
1465
1466#[no_mangle]
1467pub unsafe extern "C" fn sigwaitinfo(
1468    mask: *const SigSetT,
1469    info: *mut siginfo_t,
1470) -> c_int {
1471    sigtimedwait(mask, info, core::ptr::null())
1472}
1473
1474#[no_mangle]
1475pub unsafe extern "C" fn sigwait(
1476    mask: *const SigSetT,
1477    sig: *mut c_int,
1478) -> c_int {
1479    let mut info: siginfo_t = core::mem::zeroed();
1480    if sigtimedwait(mask, &mut info, core::ptr::null()) < 0 {
1481        return ERRNO!();
1482    }
1483    *sig = info.si_signo;
1484    0
1485}
1486
1487#[no_mangle]
1488pub unsafe extern "C" fn sigaltstack(ss: *const stack_t, old_ss: *mut stack_t) -> c_int {
1489    if !ss.is_null() {
1490        if (*ss).ss_flags & SS_ONSTACK != 0 {
1491            ERRNO!() = EINVAL;
1492            return -1;
1493        }
1494        if (*ss).ss_flags & SS_DISABLE == 0 && (*ss).ss_size < MINSIGSTKSZ {
1495            ERRNO!() = ENOMEM;
1496            return -1;
1497        }
1498    }
1499    let r = sys_sigaltstack(ss, old_ss);
1500    syscall_ret(r) as c_int
1501}
1502
1503// ============================================================
1504// setjmp.h
1505// jmp_buf is unsigned long[8]: rbx, rbp, r12-r15, rsp, rip
1506// ============================================================
1507
1508#[no_mangle]
1509#[inline(never)]
1510#[cfg(target_arch = "x86_64")]
1511pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1512    core::arch::asm!(
1513        "mov rax, [rsp]",
1514        "lea rcx, [rsp + 8]",
1515        "mov [r8], rbx",
1516        "mov [r8 + 8], rbp",
1517        "mov [r8 + 16], r12",
1518        "mov [r8 + 24], r13",
1519        "mov [r8 + 32], r14",
1520        "mov [r8 + 40], r15",
1521        "mov [r8 + 48], rcx",
1522        "mov [r8 + 56], rax",
1523        in("r8") env,
1524        lateout("rax") _,
1525        lateout("rcx") _,
1526        options(nostack),
1527    );
1528    0
1529}
1530
1531#[no_mangle]
1532#[inline(never)]
1533#[cfg(target_arch = "x86_64")]
1534pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1535    let ret = if val == 0 { 1 } else { val } as u32;
1536    core::arch::asm!(
1537        "mov rbx, [r8]",
1538        "mov rbp, [r8 + 8]",
1539        "mov r12, [r8 + 16]",
1540        "mov r13, [r8 + 24]",
1541        "mov r14, [r8 + 32]",
1542        "mov r15, [r8 + 40]",
1543        "mov rsp, [r8 + 48]",
1544        "mov eax, edx",
1545        "jmp [r8 + 56]",
1546        in("r8") env,
1547        in("edx") ret,
1548        options(noreturn),
1549    );
1550}
1551
1552#[no_mangle]
1553#[unsafe(naked)]
1554#[cfg(target_arch = "aarch64")]
1555pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1556    core::arch::naked_asm!(
1557        "stp x19, x20, [x0, #0]",
1558        "stp x21, x22, [x0, #16]",
1559        "stp x23, x24, [x0, #32]",
1560        "stp x25, x26, [x0, #48]",
1561        "stp x27, x28, [x0, #64]",
1562        "stp x29, x30, [x0, #80]",
1563        "mov x2, sp",
1564        "str x2, [x0, #104]",
1565        "stp d8, d9, [x0, #112]",
1566        "stp d10, d11, [x0, #128]",
1567        "stp d12, d13, [x0, #144]",
1568        "stp d14, d15, [x0, #160]",
1569        "mov x0, #0",
1570        "ret",
1571    );
1572}
1573
1574#[no_mangle]
1575#[inline(never)]
1576#[cfg(target_arch = "aarch64")]
1577pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1578    let ret = if val == 0 { 1 } else { val } as u64;
1579    core::arch::asm!(
1580        "ldp x19, x20, [x0]",
1581        "ldp x21, x22, [x0, #16]",
1582        "ldp x23, x24, [x0, #32]",
1583        "ldp x25, x26, [x0, #48]",
1584        "ldp x27, x28, [x0, #64]",
1585        "ldp x29, x30, [x0, #80]",
1586        "ldr x2, [x0, #104]",
1587        "mov sp, x2",
1588        "ldp d8, d9, [x0, #112]",
1589        "ldp d10, d11, [x0, #128]",
1590        "ldp d12, d13, [x0, #144]",
1591        "ldp d14, d15, [x0, #160]",
1592        "mov x0, x1",
1593        "br x30",
1594        in("x0") env,
1595        in("x1") ret,
1596        options(noreturn),
1597    );
1598}
1599
1600#[no_mangle]
1601#[unsafe(naked)]
1602#[cfg(target_arch = "riscv64")]
1603pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1604    core::arch::naked_asm!(
1605        "sd s0, 0(a0)",
1606        "sd s1, 8(a0)",
1607        "sd s2, 16(a0)",
1608        "sd s3, 24(a0)",
1609        "sd s4, 32(a0)",
1610        "sd s5, 40(a0)",
1611        "sd s6, 48(a0)",
1612        "sd s7, 56(a0)",
1613        "sd s8, 64(a0)",
1614        "sd s9, 72(a0)",
1615        "sd s10, 80(a0)",
1616        "sd s11, 88(a0)",
1617        "sd sp, 96(a0)",
1618        "sd ra, 104(a0)",
1619        "li a0, 0",
1620        "ret",
1621    );
1622}
1623
1624#[no_mangle]
1625#[inline(never)]
1626#[cfg(target_arch = "riscv64")]
1627pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1628    let ret = if val == 0 { 1 } else { val } as u64;
1629    core::arch::asm!(
1630        "ld s0, 0(a0)",
1631        "ld s1, 8(a0)",
1632        "ld s2, 16(a0)",
1633        "ld s3, 24(a0)",
1634        "ld s4, 32(a0)",
1635        "ld s5, 40(a0)",
1636        "ld s6, 48(a0)",
1637        "ld s7, 56(a0)",
1638        "ld s8, 64(a0)",
1639        "ld s9, 72(a0)",
1640        "ld s10, 80(a0)",
1641        "ld s11, 88(a0)",
1642        "ld sp, 96(a0)",
1643        "ld ra, 104(a0)",
1644        "mv a0, a1",
1645        "ret",
1646        in("a0") env,
1647        in("a1") ret,
1648        options(noreturn),
1649    );
1650}
1651
1652// sigsetjmp is implemented in raw assembly because the Rust compiler
1653// rewrites naked_asm that touches rbx into incorrect push/pop sequences,
1654// corrupting the caller's rbx across the initial return. The exported wrappers
1655// jump to a local hidden assembly implementation; the layout matches musl:
1656// env[0..7] = __jmp_buf, env[8] = saved return address, env[9] = saved signal
1657// mask, env[10] = saved rbx.
1658
1659#[no_mangle]
1660#[unsafe(naked)]
1661#[cfg(target_arch = "x86_64")]
1662pub unsafe extern "C" fn sigsetjmp(_env: *mut c_ulong, _savemask: c_int) -> c_int {
1663    core::arch::naked_asm!("jmp sigsetjmp_real");
1664}
1665
1666#[no_mangle]
1667#[unsafe(naked)]
1668#[cfg(target_arch = "x86_64")]
1669pub unsafe extern "C" fn __sigsetjmp(_env: *mut c_ulong, _savemask: c_int) -> c_int {
1670    core::arch::naked_asm!("jmp sigsetjmp_real");
1671}
1672
1673#[cfg(target_arch = "x86_64")]
1674core::arch::global_asm!(
1675    ".type sigsetjmp_real, @function",
1676    "sigsetjmp_real:",
1677    "   test esi, esi",
1678    "   jz 1f",
1679    "   pop qword ptr [rdi + 64]",
1680    "   mov qword ptr [rdi + 80], rbx",
1681    // Do not push rbx here: it would move the stack by 8 bytes and make
1682    // setjmp save an rsp that is 8 bytes below the caller's, misaligning the
1683    // caller after longjmp (postgres bootstrap crashes in AVX memset).
1684    "   mov rbx, rdi",
1685    "   call setjmp",
1686    "   push qword ptr [rbx + 64]",
1687    "   mov rdi, rbx",
1688    "   mov esi, eax",
1689    "   mov rbx, qword ptr [rbx + 80]",
1690    "   lea rdx, [rdi + 72]",
1691    "   test esi, esi",
1692    "   jz 2f",
1693    "   mov rsi, rdx",
1694    "   xor rdx, rdx",
1695    "   mov edi, 2",
1696    "   jmp 3f",
1697    "2:",
1698    "   xor rsi, rsi",
1699    "   mov edi, 2",
1700    "3:",
1701    "   mov eax, 14",
1702    "   mov r10d, 8",
1703    "   syscall",
1704    "   test esi, esi",
1705    "   jnz 4f",
1706    "   mov rax, 0xfffffffe7fffffff",
1707    "   and qword ptr [rdx], rax",
1708    "4:",
1709    "   mov eax, esi",
1710    "   ret",
1711    "1:",
1712    "   jmp setjmp",
1713);
1714
1715#[no_mangle]
1716#[inline(never)]
1717#[cfg(target_arch = "x86_64")]
1718pub unsafe extern "C" fn siglongjmp(env: *const c_ulong, val: c_int) -> ! {
1719    longjmp(env, val);
1720}
1721
1722#[no_mangle]
1723#[cfg(target_arch = "aarch64")]
1724pub unsafe extern "C" fn __sigsetjmp_tail(env: *mut c_ulong, ret: c_int) -> c_int {
1725    const SIG_SETMASK: c_int = 2;
1726    let ss = env.add(23) as *mut SigSetT;
1727    let set = if ret != 0 { ss as *const SigSetT } else { core::ptr::null() };
1728    let old = if ret != 0 { core::ptr::null_mut() } else { ss };
1729    let _ = sys_rt_sigprocmask(SIG_SETMASK, set, old, core::mem::size_of::<SigSetT>());
1730    ret
1731}
1732
1733#[no_mangle]
1734#[unsafe(naked)]
1735#[cfg(target_arch = "aarch64")]
1736pub unsafe extern "C" fn sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1737    core::arch::naked_asm!(
1738        "cbz w1, setjmp",
1739        "str x30, [x0, #176]",
1740        "str x19, [x0, #192]",
1741        "mov x19, x0",
1742        "bl setjmp",
1743        "mov w1, w0",
1744        "mov x0, x19",
1745        "ldr x30, [x0, #176]",
1746        "ldr x19, [x0, #192]",
1747        "b __sigsetjmp_tail",
1748    );
1749}
1750
1751#[no_mangle]
1752#[unsafe(naked)]
1753#[cfg(target_arch = "aarch64")]
1754pub unsafe extern "C" fn __sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1755    core::arch::naked_asm!(
1756        "cbz w1, setjmp",
1757        "str x30, [x0, #176]",
1758        "str x19, [x0, #192]",
1759        "mov x19, x0",
1760        "bl setjmp",
1761        "mov w1, w0",
1762        "mov x0, x19",
1763        "ldr x30, [x0, #176]",
1764        "ldr x19, [x0, #192]",
1765        "b __sigsetjmp_tail",
1766    );
1767}
1768
1769#[no_mangle]
1770#[inline(never)]
1771#[cfg(target_arch = "aarch64")]
1772pub unsafe extern "C" fn siglongjmp(env: *const c_ulong, val: c_int) -> ! {
1773    longjmp(env, val);
1774}
1775
1776#[no_mangle]
1777#[cfg(target_arch = "riscv64")]
1778pub unsafe extern "C" fn __sigsetjmp_tail(env: *mut c_ulong, ret: c_int) -> c_int {
1779    const SIG_SETMASK: c_int = 2;
1780    let ss = env.add(27) as *mut SigSetT;
1781    let set = if ret != 0 { ss as *const SigSetT } else { core::ptr::null() };
1782    let old = if ret != 0 { core::ptr::null_mut() } else { ss };
1783    let _ = sys_rt_sigprocmask(SIG_SETMASK, set, old, core::mem::size_of::<SigSetT>());
1784    ret
1785}
1786
1787#[no_mangle]
1788#[unsafe(naked)]
1789#[cfg(target_arch = "riscv64")]
1790pub unsafe extern "C" fn sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1791    core::arch::naked_asm!(
1792        "bnez a1, 1f",
1793        "tail setjmp",
1794        "1:",
1795        "sd ra, 208(a0)",
1796        "sd s0, 224(a0)",
1797        "mv s0, a0",
1798        "call setjmp",
1799        "mv a1, a0",
1800        "mv a0, s0",
1801        "ld s0, 224(a0)",
1802        "ld ra, 208(a0)",
1803        "tail __sigsetjmp_tail",
1804    );
1805}
1806
1807#[no_mangle]
1808#[unsafe(naked)]
1809#[cfg(target_arch = "riscv64")]
1810pub unsafe extern "C" fn __sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1811    core::arch::naked_asm!(
1812        "bnez a1, 1f",
1813        "tail setjmp",
1814        "1:",
1815        "sd ra, 208(a0)",
1816        "sd s0, 224(a0)",
1817        "mv s0, a0",
1818        "call setjmp",
1819        "mv a1, a0",
1820        "mv a0, s0",
1821        "ld s0, 224(a0)",
1822        "ld ra, 208(a0)",
1823        "tail __sigsetjmp_tail",
1824    );
1825}
1826
1827#[no_mangle]
1828#[inline(never)]
1829#[cfg(target_arch = "riscv64")]
1830pub unsafe extern "C" fn siglongjmp(env: *const c_ulong, val: c_int) -> ! {
1831    longjmp(env, val);
1832}
1833
1834// ============================================================
1835// syscall wrappers: fstat/newfstatat/getrlimit/setrlimit/utimensat
1836// ============================================================
1837
1838#[inline]
1839unsafe fn sys_newfstatat(dirfd: i32, path: *const c_char, buf: *mut u8, flags: i32) -> i64 {
1840    <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, dirfd as i64, path as i64, buf as i64, flags as i64)
1841}
1842
1843#[inline]
1844unsafe fn sys_fstat(fd: i32, buf: *mut u8) -> i64 {
1845    <Arch as Syscalls>::syscall2(SYS_FSTAT, fd as i64, buf as i64)
1846}
1847
1848#[inline]
1849unsafe fn sys_getrlimit(resource: i32, rlim: *mut u8) -> i64 {
1850    <Arch as Syscalls>::syscall2(SYS_GETRLIMIT, resource as i64, rlim as i64)
1851}
1852
1853#[inline]
1854unsafe fn sys_setrlimit(resource: i32, rlim: *const u8) -> i64 {
1855    <Arch as Syscalls>::syscall2(SYS_SETRLIMIT, resource as i64, rlim as i64)
1856}
1857
1858#[inline]
1859unsafe fn sys_utimensat(dirfd: i32, path: *const c_char, times: *const u8, flags: i32) -> i64 {
1860    <Arch as Syscalls>::syscall4(SYS_UTIMENSAT, dirfd as i64, path as i64, times as i64, flags as i64)
1861}
1862
1863// ============================================================
1864// unistd.h: process primitives
1865// ============================================================
1866
1867#[inline]
1868unsafe fn sys_fork() -> i64 {
1869    #[cfg(target_arch = "x86_64")]
1870    { <Arch as Syscalls>::syscall0(SYS_FORK) }
1871    #[cfg(target_arch = "aarch64")]
1872    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
1873    #[cfg(target_arch = "riscv64")]
1874    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
1875}
1876
1877
1878#[inline]
1879unsafe fn sys_execve(path: *const c_char, argv: *const *const c_char, envp: *const *const c_char) -> i64 {
1880    <Arch as Syscalls>::syscall3(SYS_EXECVE, path as i64, argv as i64, envp as i64)
1881}
1882
1883#[inline]
1884unsafe fn sys_wait4(pid: c_int, status: *mut c_int, options: c_int, rusage: *mut c_void) -> i64 {
1885    <Arch as Syscalls>::syscall4(SYS_WAIT4, pid as i64, status as i64, options as i64, rusage as i64)
1886}
1887
1888#[inline]
1889unsafe fn sys_getppid() -> i64 {
1890    <Arch as Syscalls>::syscall0(SYS_GETPPID)
1891}
1892
1893#[inline]
1894unsafe fn sys_getuid() -> i64 {
1895    <Arch as Syscalls>::syscall0(SYS_GETUID)
1896}
1897
1898#[inline]
1899unsafe fn sys_getgid() -> i64 {
1900    <Arch as Syscalls>::syscall0(SYS_GETGID)
1901}
1902
1903#[inline]
1904unsafe fn sys_geteuid() -> i64 {
1905    <Arch as Syscalls>::syscall0(SYS_GETEUID)
1906}
1907
1908#[inline]
1909unsafe fn sys_getegid() -> i64 {
1910    <Arch as Syscalls>::syscall0(SYS_GETEGID)
1911}
1912
1913#[no_mangle]
1914pub unsafe extern "C" fn fork() -> c_int {
1915    __fork_handler(-1);
1916    let ret = sys_fork();
1917    // Run the atfork handlers before publishing errno, exactly like musl's
1918    // __syscall_ret: a failing fork must report the kernel's errno even if a
1919    // handler changes errno. RLIMIT_NPROC is enforced by the kernel and does
1920    // not apply to root, so do not second-guess it here.
1921    if ret < 0 {
1922        let err = (-ret) as c_int;
1923        __fork_handler(0);
1924        ERRNO!() = err;
1925        return -1;
1926    }
1927    if ret == 0 {
1928        allocator_after_fork();
1929        thread_allocator_after_fork();
1930        __fork_handler(1);
1931    } else {
1932        __fork_handler(0);
1933    }
1934    ret as c_int
1935}
1936
1937#[no_mangle]
1938pub unsafe extern "C" fn execve(
1939    path: *const c_char,
1940    argv: *const *const c_char,
1941    envp: *const *const c_char,
1942) -> c_int {
1943    let r = sys_execve(path, argv, envp);
1944    syscall_ret(r) as c_int
1945}
1946
1947#[no_mangle]
1948pub unsafe extern "C" fn wait(status: *mut c_int) -> c_int {
1949    let r = sys_wait4(-1, status, 0, core::ptr::null_mut());
1950    syscall_ret(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    syscall_ret(r) as c_int
1957}
1958
1959#[no_mangle]
1960pub unsafe extern "C" fn getppid() -> c_int {
1961    sys_getppid() as c_int
1962}
1963
1964#[no_mangle]
1965pub unsafe extern "C" fn getuid() -> c_uint {
1966    sys_getuid() as c_uint
1967}
1968
1969#[no_mangle]
1970pub unsafe extern "C" fn getgid() -> c_uint {
1971    sys_getgid() as c_uint
1972}
1973
1974#[no_mangle]
1975pub unsafe extern "C" fn geteuid() -> c_uint {
1976    sys_geteuid() as c_uint
1977}
1978
1979#[no_mangle]
1980pub unsafe extern "C" fn getegid() -> c_uint {
1981    sys_getegid() as c_uint
1982}
1983
1984#[no_mangle]
1985pub unsafe extern "C" fn vfork() -> c_int {
1986    // keel uses the portable fork semantics; fork() also runs the atfork
1987    // handlers and resets the allocator/thread caches in the child.
1988    fork()
1989}
1990
1991#[no_mangle]
1992pub unsafe extern "C" fn execl(path: *const c_char, arg: *const c_char, mut args: ...) -> c_int {
1993    let mut cap = 16usize;
1994    let mut argv = malloc(cap * core::mem::size_of::<*const c_char>()) as *mut *const c_char;
1995    if argv.is_null() { ERRNO!() = ENOMEM; return -1; }
1996    *argv.add(0) = arg;
1997    let mut n: usize = 1;
1998    loop {
1999        let a: *const c_char = args.next_arg();
2000        if a.is_null() { break; }
2001        if n + 1 >= cap {
2002            cap = match cap.checked_mul(2) { Some(v) => v, None => { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; } };
2003            let grown = realloc(argv as *mut c_void, cap * core::mem::size_of::<*const c_char>()) as *mut *const c_char;
2004            if grown.is_null() { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; }
2005            argv = grown;
2006        }
2007        *argv.add(n) = a;
2008        n += 1;
2009    }
2010    *argv.add(n) = core::ptr::null();
2011    let r = sys_execve(path, argv, __environ as *const *const c_char);
2012    free(argv as *mut c_void);
2013    syscall_ret(r) as c_int
2014}
2015
2016// ============================================================
2017// spawn.h: posix_spawn family
2018// ============================================================
2019
2020// Matches musl's posix_spawn_file_actions_t layout.  Actions are a growable
2021// linked list; PATH search uses a stack buffer and an O(n) scan per entry.
2022unsafe fn spawn_execvp(file: *const c_char, argv: *const *const c_char, envp: *const *const c_char) -> ! {
2023    let flen = strlen(file as *const c_char);
2024    let f = file as *const u8;
2025    let mut has_slash = false;
2026    for i in 0..flen {
2027        if *f.add(i) == b'/' { has_slash = true; break; }
2028    }
2029    if has_slash {
2030        sys_execve(file, argv, envp);
2031        _exit(127);
2032    }
2033    let path = getenv(b"PATH\0".as_ptr() as *const c_char);
2034    let default_path = b"/usr/local/bin:/usr/bin:/bin\0";
2035    let p = if path.is_null() { default_path.as_ptr() } else { path as *const u8 };
2036    let plen = strlen(p as *const c_char);
2037    let mut buf: [u8; 4096] = [0; 4096];
2038    let mut i: usize = 0;
2039    while i <= plen {
2040        let start = i;
2041        while i < plen && *p.add(i) != b':' { i += 1; }
2042        let dlen = i - start;
2043        if dlen > 0 && dlen + 1 + flen < 4096 {
2044            core::ptr::copy_nonoverlapping(p.add(start), buf.as_mut_ptr(), dlen);
2045            *buf.as_mut_ptr().add(dlen) = b'/';
2046            core::ptr::copy_nonoverlapping(f, buf.as_mut_ptr().add(dlen + 1), flen + 1);
2047            sys_execve(buf.as_ptr() as *const c_char, argv, envp);
2048            // execve failed, try next
2049        }
2050        i += 1; // skip ':'
2051    }
2052    _exit(127);
2053}
2054
2055#[no_mangle]
2056pub unsafe extern "C" fn posix_spawnp(
2057    pid: *mut c_int,
2058    file: *const c_char,
2059    fa: *const posix_spawn_file_actions_t,
2060    attrp: *const posix_spawnattr_t,
2061    argv: *const *const c_char,
2062    envp: *const *const c_char,
2063) -> c_int {
2064    let child = sys_fork();
2065    if child < 0 {
2066        ERRNO!() = EAGAIN;
2067        return -1;
2068    }
2069    if child == 0 {
2070        // child: apply attributes and file actions, then exec
2071        spawn_apply_attr(attrp);
2072        spawn_apply_actions(fa);
2073        let actual_envp = if envp.is_null() { __environ as *const *const c_char } else { envp };
2074        spawn_execvp(file, argv, actual_envp);
2075        // unreachable: spawn_execvp always calls _exit
2076    }
2077    *pid = child as c_int;
2078    0
2079}
2080
2081#[no_mangle]
2082pub unsafe extern "C" fn posix_spawn(
2083    pid: *mut c_int,
2084    path: *const c_char,
2085    fa: *const posix_spawn_file_actions_t,
2086    attrp: *const posix_spawnattr_t,
2087    argv: *const *const c_char,
2088    envp: *const *const c_char,
2089) -> c_int {
2090    // posix_spawnp() skips PATH search when the path contains '/', so it is
2091    // also the correct implementation of posix_spawn().
2092    posix_spawnp(pid, path, fa, attrp, argv, envp)
2093}
2094
2095// ============================================================
2096// sys/stat.h: stat / fstat / utimensat / futimens
2097// ============================================================
2098
2099#[cfg(target_arch = "x86_64")]
2100#[repr(C)]
2101pub struct Stat {
2102    pub st_dev: u64,
2103    pub st_ino: u64,
2104    pub st_nlink: u64,
2105    pub st_mode: u32,
2106    pub st_uid: u32,
2107    pub st_gid: u32,
2108    _pad0: u32,
2109    pub st_rdev: u64,
2110    pub st_size: i64,
2111    pub st_blksize: i64,
2112    pub st_blocks: i64,
2113    pub st_atim: timespec,
2114    pub st_mtim: timespec,
2115    pub st_ctim: timespec,
2116    _unused: [i64; 3],
2117}
2118
2119#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
2120#[repr(C)]
2121pub struct Stat {
2122    pub st_dev: u64,
2123    pub st_ino: u64,
2124    pub st_mode: u32,
2125    pub st_nlink: u32,
2126    pub st_uid: u32,
2127    pub st_gid: u32,
2128    pub st_rdev: u64,
2129    __pad1: u64,
2130    pub st_size: i64,
2131    pub st_blksize: i32,
2132    __pad2: i32,
2133    pub st_blocks: i64,
2134    pub st_atim: timespec,
2135    pub st_mtim: timespec,
2136    pub st_ctim: timespec,
2137    __unused4: u32,
2138    __unused5: u32,
2139}
2140
2141pub const S_IFMT: u32 = 0o170000;
2142pub const S_IFDIR: u32 = 0o040000;
2143pub const S_IFCHR: u32 = 0o020000;
2144pub const S_IFBLK: u32 = 0o060000;
2145pub const S_IFREG: u32 = 0o100000;
2146pub const S_IFLNK: u32 = 0o120000;
2147pub const S_IFIFO: u32 = 0o010000;
2148pub const S_IFSOCK: u32 = 0o140000;
2149
2150pub const AT_FDCWD: i32 = -100;
2151
2152#[no_mangle]
2153pub unsafe extern "C" fn stat(path: *const c_char, buf: *mut Stat) -> c_int {
2154    let r = sys_newfstatat(AT_FDCWD, path, buf as *mut u8, 0);
2155    syscall_ret(r) as c_int
2156}
2157
2158#[no_mangle]
2159pub unsafe extern "C" fn fstat(fd: c_int, buf: *mut Stat) -> c_int {
2160    let r = sys_fstat(fd, buf as *mut u8);
2161    syscall_ret(r) as c_int
2162}
2163
2164// ============================================================
2165// sys/resource.h: getrlimit / setrlimit
2166// ============================================================
2167
2168#[repr(C)]
2169pub struct Rlimit {
2170    pub rlim_cur: u64,
2171    pub rlim_max: u64,
2172}
2173
2174pub const RLIMIT_NOFILE: c_int = 7;
2175pub const RLIMIT_STACK: c_int = 3;
2176pub const RLIMIT_DATA: c_int = 2;
2177pub const RLIMIT_AS: c_int = 9;
2178pub const RLIMIT_CPU: c_int = 0;
2179pub const RLIMIT_FSIZE: c_int = 1;
2180pub const RLIMIT_CORE: c_int = 4;
2181pub const RLIMIT_RSS: c_int = 5;
2182pub const RLIMIT_NPROC: c_int = 6;
2183pub const RLIMIT_MEMLOCK: c_int = 8;
2184pub const RLIMIT_LOCKS: c_int = 10;
2185pub const RLIMIT_SIGPENDING: c_int = 11;
2186pub const RLIMIT_MSGQUEUE: c_int = 12;
2187pub const RLIMIT_NICE: c_int = 13;
2188pub const RLIMIT_RTPRIO: c_int = 14;
2189pub const RLIMIT_RTTIME: c_int = 15;
2190pub const RLIM_INFINITY: u64 = !0u64;
2191
2192#[no_mangle]
2193pub unsafe extern "C" fn getrlimit(resource: c_int, rlim: *mut Rlimit) -> c_int {
2194    let r = sys_getrlimit(resource, rlim as *mut u8);
2195    syscall_ret(r) as c_int
2196}
2197
2198#[no_mangle]
2199pub unsafe extern "C" fn setrlimit(resource: c_int, rlim: *const Rlimit) -> c_int {
2200    let r = sys_setrlimit(resource, rlim as *const u8);
2201    syscall_ret(r) as c_int
2202}
2203
2204// ============================================================
2205// utimensat / futimens
2206// ============================================================
2207
2208#[no_mangle]
2209pub unsafe extern "C" fn utimensat(dirfd: c_int, path: *const c_char, times: *const timespec, flags: c_int) -> c_int {
2210    let r = sys_utimensat(dirfd, path, times as *const u8, flags);
2211    syscall_ret(r) as c_int
2212}
2213
2214#[no_mangle]
2215pub unsafe extern "C" fn futimens(fd: c_int, times: *const timespec) -> c_int {
2216    let r = sys_utimensat(fd, core::ptr::null(), times as *const u8, 0);
2217    syscall_ret(r) as c_int
2218}
2219
2220// ============================================================
2221// sys/socket.h
2222// ============================================================
2223
2224pub const AF_UNIX: c_int = 1;
2225pub const AF_INET: c_int = 2;
2226pub const AF_INET6: c_int = 10;
2227
2228pub const SOCK_STREAM: c_int = 1;
2229pub const SOCK_DGRAM: c_int = 2;
2230
2231pub const SHUT_RD: c_int = 0;
2232pub const SHUT_WR: c_int = 1;
2233pub const SHUT_RDWR: c_int = 2;
2234
2235pub const SOL_SOCKET: c_int = 1;
2236pub const SO_REUSEADDR: c_int = 2;
2237
2238#[repr(C)]
2239pub struct sockaddr {
2240    pub sa_family: u16,
2241    pub sa_data: [u8; 14],
2242}
2243
2244#[inline]
2245unsafe fn sys_socket(domain: c_int, ty: c_int, protocol: c_int) -> i64 {
2246    <Arch as Syscalls>::syscall3(SYS_SOCKET, domain as i64, ty as i64, protocol as i64)
2247}
2248
2249#[inline]
2250unsafe fn sys_socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_int) -> i64 {
2251    <Arch as Syscalls>::syscall4(SYS_SOCKETPAIR, domain as i64, ty as i64, protocol as i64, sv as i64)
2252}
2253
2254#[inline]
2255unsafe fn sys_bind(fd: c_int, addr: *const sockaddr, len: c_uint) -> i64 {
2256    <Arch as Syscalls>::syscall3(SYS_BIND, fd as i64, addr as i64, len as i64)
2257}
2258
2259#[inline]
2260unsafe fn sys_listen(fd: c_int, backlog: c_int) -> i64 {
2261    <Arch as Syscalls>::syscall2(SYS_LISTEN, fd as i64, backlog as i64)
2262}
2263
2264#[inline]
2265unsafe fn sys_accept(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> i64 {
2266    <Arch as Syscalls>::syscall3(SYS_ACCEPT, fd as i64, addr as i64, len as i64)
2267}
2268
2269#[inline]
2270unsafe fn sys_connect(fd: c_int, addr: *const sockaddr, len: c_uint) -> i64 {
2271    <Arch as Syscalls>::syscall3(SYS_CONNECT, fd as i64, addr as i64, len as i64)
2272}
2273
2274#[inline]
2275unsafe fn sys_sendto(fd: c_int,
2276    buf: *const c_void,
2277    len: usize,
2278    flags: c_int,
2279    addr: *const sockaddr,
2280    addrlen: c_uint,) -> i64 {
2281    <Arch as Syscalls>::syscall6(SYS_SENDTO, fd as i64, buf as i64, len as i64, flags as i64, addr as i64, addrlen as i64)
2282}
2283
2284#[inline]
2285unsafe fn sys_recvfrom(fd: c_int,
2286    buf: *mut c_void,
2287    len: usize,
2288    flags: c_int,
2289    addr: *mut sockaddr,
2290    addrlen: *mut c_uint,) -> i64 {
2291    <Arch as Syscalls>::syscall6(SYS_RECVFROM, fd as i64, buf as i64, len as i64, flags as i64, addr as i64, addrlen as i64)
2292}
2293
2294#[inline]
2295unsafe fn sys_shutdown(fd: c_int, how: c_int) -> i64 {
2296    <Arch as Syscalls>::syscall2(SYS_SHUTDOWN, fd as i64, how as i64)
2297}
2298
2299#[inline]
2300unsafe fn sys_setsockopt(fd: c_int,
2301    level: c_int,
2302    optname: c_int,
2303    optval: *const c_void,
2304    optlen: c_uint,) -> i64 {
2305    <Arch as Syscalls>::syscall5(SYS_SETSOCKOPT, fd as i64, level as i64, optname as i64, optval as i64, optlen as i64)
2306}
2307
2308#[inline]
2309unsafe fn sys_getsockname(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> i64 {
2310    <Arch as Syscalls>::syscall3(SYS_GETSOCKNAME, fd as i64, addr as i64, len as i64)
2311}
2312
2313#[no_mangle]
2314pub unsafe extern "C" fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int {
2315    let r = sys_socket(domain, ty, protocol);
2316    syscall_ret(r) as c_int
2317}
2318
2319#[no_mangle]
2320pub unsafe extern "C" fn socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_int) -> c_int {
2321    let r = sys_socketpair(domain, ty, protocol, sv);
2322    syscall_ret(r) as c_int
2323}
2324
2325#[no_mangle]
2326pub unsafe extern "C" fn bind(fd: c_int, addr: *const sockaddr, len: c_uint) -> c_int {
2327    let r = sys_bind(fd, addr, len);
2328    syscall_ret(r) as c_int
2329}
2330
2331#[no_mangle]
2332pub unsafe extern "C" fn listen(fd: c_int, backlog: c_int) -> c_int {
2333    let r = sys_listen(fd, backlog);
2334    syscall_ret(r) as c_int
2335}
2336
2337#[no_mangle]
2338pub unsafe extern "C" fn accept(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> c_int {
2339    let r = sys_accept(fd, addr, len);
2340    syscall_ret(r) as c_int
2341}
2342
2343#[no_mangle]
2344pub unsafe extern "C" fn connect(fd: c_int, addr: *const sockaddr, len: c_uint) -> c_int {
2345    let r = sys_connect(fd, addr, len);
2346    syscall_ret(r) as c_int
2347}
2348
2349#[no_mangle]
2350pub unsafe extern "C" fn send(fd: c_int, buf: *const c_void, len: usize, flags: c_int) -> isize {
2351    let r = sys_sendto(fd, buf, len, flags, core::ptr::null(), 0);
2352    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2353    r as isize
2354}
2355
2356#[no_mangle]
2357pub unsafe extern "C" fn recv(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize {
2358    let r = sys_recvfrom(fd, buf, len, flags, core::ptr::null_mut(), core::ptr::null_mut());
2359    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2360    r as isize
2361}
2362
2363#[no_mangle]
2364pub unsafe extern "C" fn sendto(
2365    fd: c_int,
2366    buf: *const c_void,
2367    len: usize,
2368    flags: c_int,
2369    addr: *const sockaddr,
2370    addrlen: c_uint,
2371) -> isize {
2372    let r = sys_sendto(fd, buf, len, flags, addr, addrlen);
2373    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2374    r as isize
2375}
2376
2377#[no_mangle]
2378pub unsafe extern "C" fn recvfrom(
2379    fd: c_int,
2380    buf: *mut c_void,
2381    len: usize,
2382    flags: c_int,
2383    addr: *mut sockaddr,
2384    addrlen: *mut c_uint,
2385) -> isize {
2386    let r = sys_recvfrom(fd, buf, len, flags, addr, addrlen);
2387    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2388    r as isize
2389}
2390
2391#[no_mangle]
2392pub unsafe extern "C" fn shutdown(fd: c_int, how: c_int) -> c_int {
2393    let r = sys_shutdown(fd, how);
2394    syscall_ret(r) as c_int
2395}
2396
2397#[no_mangle]
2398pub unsafe extern "C" fn setsockopt(
2399    fd: c_int,
2400    level: c_int,
2401    optname: c_int,
2402    optval: *const c_void,
2403    optlen: c_uint,
2404) -> c_int {
2405    let r = sys_setsockopt(fd, level, optname, optval, optlen);
2406    syscall_ret(r) as c_int
2407}
2408
2409#[no_mangle]
2410pub unsafe extern "C" fn getsockname(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> c_int {
2411    let r = sys_getsockname(fd, addr, len);
2412    syscall_ret(r) as c_int
2413}
2414
2415#[no_mangle]
2416pub extern "C" fn htonl(hostlong: c_uint) -> c_uint {
2417    hostlong.to_be()
2418}
2419
2420#[no_mangle]
2421pub extern "C" fn ntohl(netlong: c_uint) -> c_uint {
2422    c_uint::from_be(netlong)
2423}
2424
2425#[no_mangle]
2426pub extern "C" fn htons(hostshort: u16) -> u16 {
2427    hostshort.to_be()
2428}
2429
2430#[no_mangle]
2431pub extern "C" fn ntohs(netshort: u16) -> u16 {
2432    u16::from_be(netshort)
2433}
2434
2435pub type PthreadT = c_ulong;
2436
2437// pthread_attr_t: musl 64-bit layout (56 bytes = int[14])
2438#[repr(C)]
2439pub struct pthread_attr_t {
2440    __i: [c_int; 14],
2441}
2442
2443// pthread_mutex_t: musl 64-bit layout (40 bytes = int[10])
2444// _m_type=__i[0], _m_lock=__i[1], _m_waiters=__i[2], _m_count=__i[5]
2445#[repr(C)]
2446pub struct pthread_mutex_t {
2447    __i: [c_int; 10],
2448}
2449
2450#[repr(C)]
2451pub struct pthread_mutexattr_t {
2452    __attr: c_uint,
2453}
2454
2455// pthread_cond_t: musl 64-bit layout (48 bytes = int[12])
2456// _c_seq=__i[2], _c_waiters=__i[3], _c_clock=__i[4]
2457#[repr(C)]
2458pub struct pthread_cond_t {
2459    __i: [c_int; 12],
2460}
2461
2462#[repr(C)]
2463pub struct pthread_condattr_t {
2464    __attr: c_uint,
2465}
2466
2467// pthread_rwlock_t: musl 64-bit layout (56 bytes = int[14])
2468// _rw_lock=__i[0], _rw_waiters=__i[1], _rw_shared=__i[2]
2469#[repr(C)]
2470pub struct pthread_rwlock_t {
2471    __i: [c_int; 14],
2472}
2473
2474#[repr(C)]
2475pub struct pthread_rwlockattr_t {
2476    __attr: [c_uint; 2],
2477}
2478
2479// pthread_barrier_t: musl 64-bit layout (32 bytes = int[8])
2480#[repr(C)]
2481pub struct pthread_barrier_t {
2482    __i: [c_int; 8],
2483}
2484
2485#[repr(C)]
2486pub struct pthread_barrierattr_t {
2487    __attr: c_uint,
2488}
2489
2490pub type pthread_spinlock_t = c_int;
2491pub type pthread_once_t = c_int;
2492pub type pthread_key_t = c_uint;
2493
2494// sem_t: musl 64-bit layout (32 bytes = int[8])
2495#[repr(C)]
2496pub struct sem_t {
2497    __val: [c_int; 8],
2498}
2499
2500#[repr(C)]
2501pub struct sched_param {
2502    pub sched_priority: c_int,
2503}
2504
2505const CLONE_VM: c_ulong = 0x00000100;
2506const CLONE_FS: c_ulong = 0x00000200;
2507const CLONE_FILES: c_ulong = 0x00000400;
2508const CLONE_SIGHAND: c_ulong = 0x00000800;
2509const CLONE_THREAD: c_ulong = 0x00010000;
2510const CLONE_SYSVSEM: c_ulong = 0x00040000;
2511const CLONE_SETTLS: c_ulong = 0x00080000;
2512const CLONE_PARENT_SETTID: c_ulong = 0x00100000;
2513const CLONE_CHILD_CLEARTID: c_ulong = 0x00200000;
2514
2515const FUTEX_WAIT: c_int = 0;
2516const FUTEX_WAKE: c_int = 1;
2517const FUTEX_LOCK_PI: c_int = 6;
2518const FUTEX_UNLOCK_PI: c_int = 7;
2519const FUTEX_TRYLOCK_PI: c_int = 8;
2520
2521// SIGCANCEL (32) is musl's internal cancel signal
2522const SIGCANCEL: c_int = 32;
2523
2524const PTHREAD_MUTEX_NORMAL: c_int = 0;
2525const PTHREAD_MUTEX_DEFAULT: c_int = 0;
2526const PTHREAD_MUTEX_RECURSIVE: c_int = 1;
2527const PTHREAD_MUTEX_ERRORCHECK: c_int = 2;
2528
2529const PTHREAD_CREATE_JOINABLE: c_int = 0;
2530const PTHREAD_CREATE_DETACHED: c_int = 1;
2531
2532const PTHREAD_CANCEL_ENABLE: c_int = 0;
2533const PTHREAD_CANCEL_DISABLE: c_int = 1;
2534const PTHREAD_CANCEL_DEFERRED: c_int = 0;
2535const PTHREAD_CANCEL_ASYNCHRONOUS: c_int = 1;
2536
2537const PTHREAD_SCOPE_SYSTEM: c_int = 0;
2538const PTHREAD_PROCESS_PRIVATE: c_int = 0;
2539const PTHREAD_PROCESS_SHARED: c_int = 1;
2540const PTHREAD_INHERIT_SCHED: c_int = 0;
2541const PTHREAD_EXPLICIT_SCHED: c_int = 1;
2542
2543const PTHREAD_BARRIER_SERIAL_THREAD: c_int = -1;
2544
2545const PTHREAD_KEYS_MAX: usize = 128;
2546const PTHREAD_DESTRUCTOR_ITERATIONS: usize = 4;
2547const SEM_VALUE_MAX: c_int = 0x7fffffff;
2548
2549const DT_EXITED: c_int = 0;
2550const DT_EXITING: c_int = 1;
2551const DT_JOINABLE: c_int = 2;
2552const DT_DETACHED: c_int = 3;
2553
2554// musl __ptcb cleanup handler node
2555#[repr(C)]
2556#[derive(Copy, Clone)]
2557pub struct __ptcb {
2558    __f: Option<unsafe extern "C" fn(*mut c_void)>,
2559    __x: *mut c_void,
2560    __next: *mut __ptcb,
2561}
2562
2563// robust_list_head for kernel robust mutex support
2564#[repr(C)]
2565#[derive(Copy, Clone)]
2566struct robust_list {
2567    next: *mut robust_list,
2568}
2569
2570#[repr(C)]
2571#[derive(Copy, Clone)]
2572struct robust_list_head {
2573    list: robust_list,
2574    futex_offset: c_long,
2575    pending: *mut robust_list,
2576}
2577
2578// Adapted from musl's x86_64 clone.s.
2579#[cfg(all(target_arch = "x86_64", not(test)))]
2580core::arch::global_asm!(
2581    ".global __keel_clone",
2582    ".type __keel_clone, @function",
2583    "__keel_clone:",
2584    "mov rax, rdi",
2585    "mov rdi, rdx",
2586    "mov rdx, r8",
2587    "mov r10, [rsp + 8]",
2588    "mov r8, r9",
2589    "mov r9, rax",
2590    "and rsi, -16",
2591    "sub rsi, 8",
2592    "mov [rsi], rcx",
2593    "mov eax, 56",
2594    "syscall",
2595    "test rax, rax",
2596    "jnz 1f",
2597    "pop rdi",
2598    "call r9",
2599    // A clone() child that returns from its function must exit with that
2600    // value (musl does the same); falling through to hlt raises SIGSEGV.
2601    "mov edi, eax",
2602    "mov eax, 60",
2603    "syscall",
2604    "hlt",
2605    "1:",
2606    "ret",
2607);
2608
2609// Adapted from musl's aarch64 clone.s.
2610#[no_mangle]
2611#[unsafe(naked)]
2612#[cfg(target_arch = "aarch64")]
2613pub unsafe extern "C" fn __keel_clone(
2614    fn_: usize,
2615    stack: *mut u8,
2616    flags: c_ulong,
2617    arg: *mut c_void,
2618    ptid: *mut c_int,
2619    tls: c_ulong,
2620    ctid: *mut c_int,
2621) -> i64 {
2622    core::arch::naked_asm!(
2623        "and x1, x1, #-16",
2624        "stp x0, x3, [x1, #-16]!",
2625        "uxtw x0, w2",
2626        "mov x2, x4",
2627        "mov x3, x5",
2628        "mov x4, x6",
2629        "mov x8, #220",
2630        "svc #0",
2631        "cbz x0, 1f",
2632        "ret",
2633        "1:",
2634        "mov x29, #0",
2635        "ldp x1, x0, [sp], #16",
2636        "blr x1",
2637        "mov x8, #93",
2638        "svc #0",
2639    );
2640}
2641
2642#[no_mangle]
2643#[unsafe(naked)]
2644#[cfg(target_arch = "riscv64")]
2645pub unsafe extern "C" fn __keel_clone(
2646    fn_: usize,
2647    stack: *mut u8,
2648    flags: c_ulong,
2649    arg: *mut c_void,
2650    ptid: *mut c_int,
2651    tls: c_ulong,
2652    ctid: *mut c_int,
2653) -> i64 {
2654    core::arch::naked_asm!(
2655        "andi a1, a1, -16",
2656        "addi a1, a1, -16",
2657        "sd a0, 0(a1)",
2658        "sd a3, 8(a1)",
2659        "mv a0, a2",
2660        "mv a2, a4",
2661        "mv a3, a5",
2662        "mv a4, a6",
2663        "li a7, 220",
2664        "ecall",
2665        "beqz a0, 1f",
2666        "ret",
2667        "1:",
2668        "ld a1, 0(sp)",
2669        "ld a0, 8(sp)",
2670        "jalr a1",
2671        "li a7, 93",
2672        "ecall",
2673    );
2674}
2675
2676#[cfg(all(target_arch = "x86_64", test))]
2677#[inline(never)]
2678unsafe fn __keel_clone(
2679    _fn_: usize,
2680    _stack: *mut u8,
2681    _flags: c_ulong,
2682    _arg: *mut c_void,
2683    _ptid: *mut c_int,
2684    _tls: c_ulong,
2685    _ctid: *mut c_int,
2686) -> i64 {
2687    -1
2688}
2689
2690#[cfg(all(target_arch = "x86_64", not(test)))]
2691extern "C" {
2692    fn __keel_clone(
2693        fn_: usize,
2694        stack: *mut u8,
2695        flags: c_ulong,
2696        arg: *mut c_void,
2697        ptid: *mut c_int,
2698        tls: c_ulong,
2699        ctid: *mut c_int,
2700    ) -> i64;
2701}
2702
2703#[derive(Copy, Clone)]
2704struct TlsHooks {
2705    create: unsafe extern "C" fn() -> *mut u8,
2706    init: unsafe extern "C" fn(*mut u8) -> *mut u8,
2707    block_size: extern "C" fn() -> usize,
2708    base_offset: extern "C" fn() -> usize,
2709}
2710
2711// Installed by the dynamic loader before any thread is created. A static
2712// executable leaves this as None and uses the weak fallbacks.
2713static mut TLS_HOOKS: Option<TlsHooks> = None;
2714
2715/// Called by the dynamic loader once it is self-relocated.  A static
2716/// executable does not call this and keeps the fallback behaviour.
2717#[no_mangle]
2718pub unsafe extern "C" fn __keel_set_thread_tls_hooks(
2719    create: usize,
2720    init: usize,
2721    block_size: usize,
2722    base_offset: usize,
2723) {
2724    TLS_HOOKS = Some(TlsHooks {
2725        create: core::mem::transmute(create),
2726        init: core::mem::transmute(init),
2727        block_size: core::mem::transmute(block_size),
2728        base_offset: core::mem::transmute(base_offset),
2729    });
2730}
2731
2732#[inline(never)]
2733#[linkage = "weak"]
2734#[no_mangle]
2735pub extern "C" fn __keel_create_thread_tls() -> *mut u8 {
2736    match unsafe { TLS_HOOKS } {
2737        Some(hooks) => unsafe { (hooks.create)() },
2738        None => core::ptr::null_mut(),
2739    }
2740}
2741
2742#[inline(never)]
2743#[linkage = "weak"]
2744#[no_mangle]
2745pub unsafe extern "C" fn __keel_init_thread_tls_at(block: *mut u8) -> *mut u8 {
2746    match TLS_HOOKS {
2747        Some(hooks) => (hooks.init)(block),
2748        None => core::ptr::null_mut(),
2749    }
2750}
2751
2752#[inline(never)]
2753#[linkage = "weak"]
2754#[no_mangle]
2755pub extern "C" fn __keel_tls_block_size() -> usize {
2756    match unsafe { TLS_HOOKS } {
2757        Some(hooks) => (hooks.block_size)(),
2758        None => 0,
2759    }
2760}
2761
2762#[inline(never)]
2763#[linkage = "weak"]
2764#[no_mangle]
2765pub extern "C" fn __keel_tls_base_offset() -> usize {
2766    match unsafe { TLS_HOOKS } {
2767        Some(hooks) => (hooks.base_offset)(),
2768        None => 0,
2769    }
2770}
2771
2772#[inline]
2773unsafe fn sys_gettid() -> i64 {
2774    <Arch as Syscalls>::syscall0(SYS_GETTID)
2775}
2776
2777#[inline]
2778unsafe fn sys_futex(uaddr: *mut c_int,
2779    futex_op: c_int,
2780    val: c_int,
2781    timeout: *mut c_void,
2782    uaddr2: *mut c_int,
2783    val3: c_int,) -> i64 {
2784    <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)
2785}
2786
2787const THREAD_CHUNK: usize = 1024;
2788const STACK_SIZE: usize = 1024 * 1024;
2789// Per-thread pointer to its Thread record.  The TCB has room after errno
2790// (0x30), the vDSO getrandom state (0x38), and this pointer (0x40).
2791const THREAD_TCB_OFFSET: usize = 0x40;
2792
2793#[repr(C)]
2794#[derive(Copy, Clone)]
2795struct Thread {
2796    tid: c_int,
2797    detach_state: c_int,
2798    result: *mut c_void,
2799    cancel: c_int,
2800    cancel_state: c_int,
2801    cancel_type: c_int,
2802    user_fn: usize,
2803    user_arg: *mut c_void,
2804    stack: *mut u8,
2805    stack_size: usize,
2806    stack_owned: bool,
2807    fs_base: *mut u8,
2808    // TLS block as allocated at creation. The global TLS size can grow when
2809    // a DSO is dlopen'ed, so it must not be used to free an older thread's
2810    // block: the address and length would be wrong and could unmap a
2811    // neighbouring thread stack.
2812    tls_base: *mut u8,
2813    tls_size: usize,
2814    tsd: [*mut c_void; PTHREAD_KEYS_MAX],
2815    cancelbuf: *mut __ptcb,
2816    robust_list: robust_list_head,
2817    free_next: *mut Thread,
2818}
2819
2820static mut THREADS: [Thread; THREAD_CHUNK] = [Thread {
2821    tid: -1,
2822    detach_state: DT_JOINABLE,
2823    result: core::ptr::null_mut(),
2824    cancel: 0,
2825    cancel_state: PTHREAD_CANCEL_ENABLE,
2826    cancel_type: PTHREAD_CANCEL_DEFERRED,
2827    user_fn: 0,
2828    user_arg: core::ptr::null_mut(),
2829    stack: core::ptr::null_mut(),
2830    stack_size: 0,
2831    stack_owned: false,
2832    fs_base: core::ptr::null_mut(),
2833    tls_base: core::ptr::null_mut(),
2834    tls_size: 0,
2835    tsd: [core::ptr::null_mut(); PTHREAD_KEYS_MAX],
2836    cancelbuf: core::ptr::null_mut(),
2837    robust_list: robust_list_head {
2838        list: robust_list { next: core::ptr::null_mut() },
2839        futex_offset: 0,
2840        pending: core::ptr::null_mut(),
2841    },
2842    free_next: core::ptr::null_mut(),
2843}; THREAD_CHUNK];
2844#[repr(C)]
2845struct ThreadChunk {
2846    next: *mut ThreadChunk,
2847    base: *mut Thread,
2848}
2849static THREAD_CHUNK_LIST: AtomicPtr<ThreadChunk> =
2850    AtomicPtr::new(core::ptr::null_mut());
2851static EXTRA_CHUNK_COUNT: AtomicUsize = AtomicUsize::new(0);
2852// Free list of thread slots, protected by THREAD_LOCK.  Slots are never
2853// moved, so pthread_t values stay valid for the life of a thread.
2854static mut FREE_THREADS: *mut Thread = core::ptr::null_mut();
2855static mut THREAD_TABLE_READY: bool = false;
2856static mut THREAD_LOCK: c_int = 0;
2857static mut THREAD_WAITERS: c_int = 0;
2858static ACTIVE_THREADS: AtomicUsize = AtomicUsize::new(0);
2859static mut KEY_DTORS: [Option<unsafe extern "C" fn(*mut c_void)>; PTHREAD_KEYS_MAX] = [None; PTHREAD_KEYS_MAX];
2860static NEXT_KEY: AtomicUsize = AtomicUsize::new(0);
2861
2862// futex helpers
2863unsafe fn futex_wait(addr: *mut c_int, expected: c_int) -> c_int {
2864    let r = sys_futex(addr, FUTEX_WAIT, expected, null_mut(), null_mut(), 0);
2865    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
2866}
2867
2868unsafe fn futex_wake(addr: *mut c_int, count: c_int) {
2869    let c = if count < 0 { c_int::MAX } else { count };
2870    sys_futex(addr, FUTEX_WAKE, c, null_mut(), null_mut(), 0);
2871}
2872
2873unsafe fn futex_lock_pi(addr: *mut c_int, abs_timeout: *const timespec) -> c_int {
2874    let timeout_ptr = if abs_timeout.is_null() { null_mut() } else { abs_timeout as *mut c_void };
2875    let r = sys_futex(addr, FUTEX_LOCK_PI, 0, timeout_ptr, null_mut(), 0);
2876    if r < 0 { (-r) as c_int } else { 0 }
2877}
2878
2879unsafe fn futex_unlock_pi(addr: *mut c_int) -> c_int {
2880    let r = sys_futex(addr, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
2881    if r < 0 { (-r) as c_int } else { 0 }
2882}
2883
2884#[inline]
2885unsafe fn sys_set_robust_list(head: *mut robust_list_head, len: usize) -> i64 {
2886    <Arch as Syscalls>::syscall2(SYS_SET_ROBUST_LIST, head as i64, len as i64)
2887}
2888
2889unsafe fn futex_timedwait(addr: *mut c_int, expected: c_int, abs_timeout: *const timespec) -> c_int {
2890    if abs_timeout.is_null() { return futex_wait(addr, expected); }
2891    let mut now: timespec = core::mem::zeroed();
2892    if sys_clock_gettime(CLOCK_REALTIME, &mut now) < 0 { return EINVAL; }
2893    let mut rel: timespec = core::mem::zeroed();
2894    rel.tv_sec = (*abs_timeout).tv_sec - now.tv_sec;
2895    rel.tv_nsec = (*abs_timeout).tv_nsec - now.tv_nsec;
2896    if rel.tv_nsec < 0 { rel.tv_sec -= 1; rel.tv_nsec += 1_000_000_000; }
2897    if rel.tv_sec < 0 { return ETIMEDOUT; }
2898    let r = sys_futex(addr, FUTEX_WAIT, expected, &mut rel as *mut timespec as *mut c_void, null_mut(), 0);
2899    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
2900}
2901
2902// atomic helpers wrapping AtomicI32
2903unsafe fn a_cas(addr: *mut c_int, expected: c_int, desired: c_int) -> c_int {
2904    let a = &*(addr as *const AtomicI32);
2905    match a.compare_exchange(expected, desired, Ordering::AcqRel, Ordering::Acquire) {
2906        Ok(v) | Err(v) => v,
2907    }
2908}
2909
2910unsafe fn a_store(addr: *mut c_int, val: c_int) {
2911    (*(addr as *const AtomicI32)).store(val, Ordering::Release);
2912}
2913
2914unsafe fn a_load(addr: *const c_int) -> c_int {
2915    (*(addr as *const AtomicI32)).load(Ordering::Acquire)
2916}
2917
2918unsafe fn a_swap(addr: *mut c_int, val: c_int) -> c_int {
2919    (*(addr as *const AtomicI32)).swap(val, Ordering::AcqRel)
2920}
2921
2922unsafe fn a_fetch_add(addr: *mut c_int, val: c_int) -> c_int {
2923    (*(addr as *const AtomicI32)).fetch_add(val, Ordering::AcqRel)
2924}
2925
2926unsafe fn a_fetch_sub(addr: *mut c_int, val: c_int) -> c_int {
2927    (*(addr as *const AtomicI32)).fetch_sub(val, Ordering::AcqRel)
2928}
2929
2930unsafe fn spinlock_lock(lock: *mut c_int, waiters: *mut c_int) {
2931    while a_swap(lock, 1) != 0 {
2932        let mut spins = 100;
2933        while spins > 0 && a_load(lock) != 0 { core::hint::spin_loop(); spins -= 1; }
2934        if a_load(lock) == 0 { continue; }
2935        a_fetch_add(waiters, 1);
2936        futex_wait(lock, 1);
2937        a_fetch_sub(waiters, 1);
2938    }
2939}
2940
2941unsafe fn spinlock_unlock(lock: *mut c_int, waiters: *mut c_int) {
2942    a_store(lock, 0);
2943    if a_load(waiters) > 0 { futex_wake(lock, 1); }
2944}
2945
2946unsafe fn thread_slot_count() -> usize {
2947    THREAD_CHUNK + EXTRA_CHUNK_COUNT.load(Ordering::Acquire) * THREAD_CHUNK
2948}
2949
2950unsafe fn thread_slot_at(index: usize) -> *mut Thread {
2951    if index < THREAD_CHUNK {
2952        core::ptr::addr_of_mut!(THREADS[index])
2953    } else {
2954        let extra = index - THREAD_CHUNK;
2955        let chunk_index = extra / THREAD_CHUNK;
2956        let offset = extra % THREAD_CHUNK;
2957        let mut chunk = THREAD_CHUNK_LIST.load(Ordering::Acquire);
2958        let mut i = 0usize;
2959        while i < chunk_index && !chunk.is_null() {
2960            chunk = (*chunk).next;
2961            i += 1;
2962        }
2963        if chunk.is_null() {
2964            return core::ptr::null_mut();
2965        }
2966        (*chunk).base.add(offset)
2967    }
2968}
2969
2970unsafe fn release_thread_slot(slot: *const Thread) {
2971    let slot = slot as *mut Thread;
2972    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
2973    (*slot).tid = -1;
2974    (*slot).free_next = FREE_THREADS;
2975    FREE_THREADS = slot;
2976    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
2977}
2978
2979unsafe fn alloc_thread_slot() -> Option<&'static mut Thread> {
2980    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
2981    if !THREAD_TABLE_READY {
2982        // Slot 0 is reserved for the process's initial thread.  Registering
2983        // it must not require touching the rest of the table.
2984        let mut i = THREAD_CHUNK;
2985        while i > 1 {
2986            i -= 1;
2987            let slot = &mut THREADS[i];
2988            slot.free_next = FREE_THREADS;
2989            FREE_THREADS = slot;
2990        }
2991        THREAD_TABLE_READY = true;
2992    }
2993    let mut slot = FREE_THREADS;
2994    if slot.is_null() {
2995        let bytes = core::mem::size_of::<ThreadChunk>()
2996            + THREAD_CHUNK * core::mem::size_of::<Thread>();
2997        let raw = sys_mmap(
2998            core::ptr::null_mut(),
2999            bytes,
3000            PROT_READ | PROT_WRITE,
3001            MAP_PRIVATE | MAP_ANONYMOUS,
3002            -1,
3003            0,
3004        ) as *mut u8;
3005        if raw.is_null() || raw == MMAP_FAILED {
3006            spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3007            return None;
3008        }
3009        let header = raw as *mut ThreadChunk;
3010        let base = raw.add(core::mem::size_of::<ThreadChunk>()) as *mut Thread;
3011        (*header).base = base;
3012        let mut i = THREAD_CHUNK;
3013        while i > 1 {
3014            i -= 1;
3015            let s = base.add(i);
3016            (*s).free_next = FREE_THREADS;
3017            FREE_THREADS = s;
3018        }
3019        (*header).next = THREAD_CHUNK_LIST.load(Ordering::Relaxed);
3020        THREAD_CHUNK_LIST.store(header, Ordering::Release);
3021        EXTRA_CHUNK_COUNT.fetch_add(1, Ordering::AcqRel);
3022        slot = base;
3023    } else {
3024        FREE_THREADS = (*slot).free_next;
3025        (*slot).free_next = core::ptr::null_mut();
3026    }
3027    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3028    Some(&mut *slot)
3029}
3030
3031/// The child of fork() keeps only the calling thread.  Rebuild the free list
3032/// so slots belonging to vanished threads are reusable, and update the
3033/// current thread's tid to the child's.
3034unsafe fn thread_allocator_after_fork() {
3035    a_store(&raw mut THREAD_LOCK, 0);
3036    a_store(&raw mut THREAD_WAITERS, 0);
3037    let tp = tcb_slot(THREAD_TCB_OFFSET);
3038    let current = if tp.is_null() {
3039        core::ptr::null_mut()
3040    } else {
3041        core::ptr::read_unaligned(tp) as *mut Thread
3042    };
3043    let child_tid = sys_gettid() as c_int;
3044    if !THREAD_TABLE_READY {
3045        // The initial thread is registered directly in slot 0, so the free
3046        // list may never have been built.  Only update that one slot; the
3047        // first pthread_create() will build the free list.
3048        if !current.is_null() {
3049            (*current).tid = child_tid;
3050            ACTIVE_THREADS.store(1, Ordering::Release);
3051        }
3052        return;
3053    }
3054    let count = thread_slot_count();
3055    let mut free = core::ptr::null_mut();
3056    let mut active = 0usize;
3057    let mut i = 0usize;
3058    while i < count {
3059        let slot = thread_slot_at(i);
3060        if slot == current {
3061            (*slot).tid = child_tid;
3062            (*slot).free_next = core::ptr::null_mut();
3063            active += 1;
3064        } else {
3065            (*slot).tid = -1;
3066            (*slot).free_next = free;
3067            free = slot;
3068        }
3069        i += 1;
3070    }
3071    FREE_THREADS = free;
3072    ACTIVE_THREADS.store(active, Ordering::Release);
3073}
3074
3075unsafe fn run_key_dtors(slot: &mut Thread) {
3076    for _ in 0..PTHREAD_DESTRUCTOR_ITERATIONS {
3077        let mut any = false;
3078        for i in 0..PTHREAD_KEYS_MAX {
3079            let val = slot.tsd[i];
3080            if !val.is_null() {
3081                if let Some(dtor) = KEY_DTORS[i] {
3082                    slot.tsd[i] = core::ptr::null_mut();
3083                    any = true;
3084                    dtor(val);
3085                }
3086            }
3087        }
3088        if !any { break; }
3089    }
3090}
3091
3092unsafe extern "C" fn thread_entry(slot: *mut c_void) -> *mut c_void {
3093    let slot = &mut *(slot as *mut Thread);
3094    let tp = tcb_slot(THREAD_TCB_OFFSET);
3095    if !tp.is_null() {
3096        core::ptr::write_unaligned(tp, slot as *mut Thread as usize);
3097    }
3098    // A reused slot may still carry the previous thread's robust-list state;
3099    // register a fresh list for this thread.
3100    slot.robust_list.list.next = core::ptr::null_mut();
3101    slot.robust_list.futex_offset = 0;
3102    slot.robust_list.pending = core::ptr::null_mut();
3103    ensure_robust_list(slot);
3104    let mut set: SigSetT = 0;
3105    sigemptyset(&mut set);
3106    sigaddset(&mut set, SIGCANCEL);
3107    pthread_sigmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
3108    let user_fn: unsafe extern "C" fn(*mut c_void) -> *mut c_void =
3109        core::mem::transmute::<usize, _>(slot.user_fn);
3110    let ret = user_fn(slot.user_arg);
3111    thread_finish(slot, ret)
3112}
3113
3114/// Common exit path for a thread that returned from its start routine and
3115/// for pthread_exit(): run cleanup handlers and TSD destructors, publish the
3116/// result, and give up the CPU.
3117unsafe fn thread_finish(slot: &mut Thread, retval: *mut c_void) -> ! {
3118    run_cleanup_handlers(slot);
3119    run_key_dtors(slot);
3120    vdso_getrandom_thread_exit();
3121    slot.result = retval;
3122    a_store(&raw mut slot.detach_state, DT_EXITED);
3123    futex_wake(&raw mut slot.detach_state, 1);
3124    if ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel) <= 1 {
3125        exit(0);
3126    }
3127    sys_exit_thread(0)
3128}
3129
3130unsafe fn init_thread_slot(slot: *mut Thread, me: c_int) {
3131    (*slot).tid = me;
3132    (*slot).detach_state = DT_JOINABLE;
3133    (*slot).result = core::ptr::null_mut();
3134    (*slot).cancel = 0;
3135    (*slot).cancel_state = PTHREAD_CANCEL_ENABLE;
3136    (*slot).cancel_type = PTHREAD_CANCEL_DEFERRED;
3137    (*slot).cancelbuf = core::ptr::null_mut();
3138    core::ptr::write_bytes((*slot).tsd.as_mut_ptr(), 0, PTHREAD_KEYS_MAX);
3139    (*slot).robust_list.list.next = core::ptr::null_mut();
3140    (*slot).robust_list.futex_offset = 0;
3141    (*slot).robust_list.pending = core::ptr::null_mut();
3142    (*slot).free_next = core::ptr::null_mut();
3143}
3144
3145unsafe fn register_main_thread() -> Option<&'static mut Thread> {
3146    let me = sys_gettid() as c_int;
3147    let tp = tcb_slot(THREAD_TCB_OFFSET);
3148    if !tp.is_null() {
3149        let p = core::ptr::read_unaligned(tp) as *mut Thread;
3150        if !p.is_null() && (*p).tid == me {
3151            return Some(&mut *p);
3152        }
3153    }
3154    let slot = core::ptr::addr_of_mut!(THREADS[0]);
3155    init_thread_slot(slot, me);
3156    if !tp.is_null() {
3157        core::ptr::write_unaligned(tp, slot as usize);
3158    }
3159    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3160    Some(&mut *slot)
3161}
3162
3163unsafe fn register_current_thread() -> Option<&'static mut Thread> {
3164    let me = sys_gettid() as c_int;
3165    let slot_ref = alloc_thread_slot()?;
3166    let slot = slot_ref as *mut Thread;
3167    init_thread_slot(slot, me);
3168    let tp = tcb_slot(THREAD_TCB_OFFSET);
3169    if !tp.is_null() {
3170        core::ptr::write_unaligned(tp, slot as usize);
3171    }
3172    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3173    Some(&mut *slot)
3174}
3175
3176unsafe fn find_thread() -> Option<&'static mut Thread> {
3177    let me = sys_gettid() as c_int;
3178    let tp = tcb_slot(THREAD_TCB_OFFSET);
3179    if !tp.is_null() {
3180        let p = core::ptr::read_unaligned(tp) as *mut Thread;
3181        if !p.is_null() && (*p).tid == me {
3182            return Some(&mut *p);
3183        }
3184    }
3185    let main = core::ptr::addr_of_mut!(THREADS[0]);
3186    if (*main).tid == me {
3187        if !tp.is_null() {
3188            core::ptr::write_unaligned(tp, main as usize);
3189        }
3190        return Some(&mut *main);
3191    }
3192    let count = thread_slot_count();
3193    let mut i = 0usize;
3194    while i < count {
3195        let slot = thread_slot_at(i);
3196        if core::ptr::read_volatile(&raw const (*slot).tid) == me {
3197            if !tp.is_null() {
3198                core::ptr::write_unaligned(tp, slot as usize);
3199            }
3200            return Some(&mut *slot);
3201        }
3202        i += 1;
3203    }
3204    register_current_thread()
3205}
3206
3207#[no_mangle]
3208pub unsafe extern "C" fn pthread_self() -> PthreadT {
3209    match find_thread() {
3210        Some(slot) => slot as *mut Thread as PthreadT,
3211        None => 0,
3212    }
3213}
3214
3215#[no_mangle]
3216pub unsafe extern "C" fn pthread_equal(t1: PthreadT, t2: PthreadT) -> c_int {
3217    (t1 == t2) as c_int
3218}
3219
3220unsafe fn dynamic_tls_init(block: *mut u8) -> *mut u8 {
3221    __keel_init_thread_tls_at(block)
3222}
3223
3224unsafe fn dynamic_tls_create() -> *mut u8 {
3225    __keel_create_thread_tls()
3226}
3227
3228/// Prefer carving TLS out of the top of an application-provided stack; a
3229/// separate mapping can land below a MAP_GROWSDOWN stack and block growth.
3230unsafe fn carve_thread_tls(
3231    init_at: unsafe fn(*mut u8) -> *mut u8,
3232    create: unsafe fn() -> *mut u8,
3233    user_top: *mut c_void,
3234    stack_size: usize,
3235    tls_total: usize,
3236    stack_owned: bool,
3237    stack_top: &mut *mut u8,
3238    tls_owned: &mut bool,
3239) -> *mut u8 {
3240    if !stack_owned && tls_total > 0 && stack_size > tls_total + 4096 {
3241        let block = ((user_top as usize - tls_total) & !63usize) as *mut u8;
3242        let fs = init_at(block);
3243        if !fs.is_null() {
3244            *stack_top = block;
3245            *tls_owned = false;
3246            return fs;
3247        }
3248    }
3249    create()
3250}
3251
3252#[no_mangle]
3253pub unsafe extern "C" fn pthread_create(
3254    thread: *mut PthreadT,
3255    attr: *const pthread_attr_t,
3256    start_routine: usize,
3257    arg: *mut c_void,
3258) -> c_int {
3259    if start_routine == 0 || thread.is_null() { return EINVAL; }
3260    let Some(slot_ref) = alloc_thread_slot() else { return EAGAIN; };
3261    let slot = slot_ref as *mut Thread;
3262    let stack_size = if !attr.is_null() {
3263        let s = attr_stack_size(attr);
3264        if s > 0 { s } else { STACK_SIZE }
3265    } else { STACK_SIZE };
3266    // musl stores the stack *top* in pthread_attr_t; zero means "allocate".
3267    let user_top = if !attr.is_null() {
3268        attr_stack_top(attr)
3269    } else {
3270        core::ptr::null_mut()
3271    };
3272    let stack_owned = user_top.is_null();
3273    let stack = if stack_owned {
3274        sys_mmap(null_mut(), stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
3275    } else {
3276        (user_top as *mut u8).sub(stack_size)
3277    };
3278    if stack == MMAP_FAILED { release_thread_slot(slot); return EAGAIN; }
3279    let static_mode = RC_STATIC_EXEC;
3280    let tls_total = if static_mode {
3281        STATIC_TLS_BLOCK_SIZE
3282    } else {
3283        __keel_tls_block_size()
3284    };
3285    let mut stack_top = stack.add(stack_size);
3286    let mut tls_owned = true;
3287    let fs_base = if static_mode {
3288        carve_thread_tls(
3289            static_tls_init_block,
3290            static_tls_create_block,
3291            user_top,
3292            stack_size,
3293            tls_total,
3294            stack_owned,
3295            &mut stack_top,
3296            &mut tls_owned,
3297        )
3298    } else {
3299        carve_thread_tls(
3300            dynamic_tls_init,
3301            dynamic_tls_create,
3302            user_top,
3303            stack_size,
3304            tls_total,
3305            stack_owned,
3306            &mut stack_top,
3307            &mut tls_owned,
3308        )
3309    };
3310    if fs_base.is_null() {
3311        if stack_owned { sys_munmap(stack, stack_size); }
3312        release_thread_slot(slot);
3313        return EAGAIN;
3314    }
3315    let tls_base = if static_mode {
3316        fs_base.sub(STATIC_TLS_TP_OFFSET)
3317    } else {
3318        fs_base.sub(__keel_tls_base_offset())
3319    };
3320    let tls_size = if tls_owned { tls_total } else { 0 };
3321    init_thread_slot(slot, 1);
3322    (*slot).user_fn = start_routine;
3323    (*slot).user_arg = arg;
3324    (*slot).stack = stack;
3325    (*slot).stack_size = stack_size;
3326    (*slot).stack_owned = stack_owned;
3327    (*slot).fs_base = fs_base;
3328    (*slot).tls_base = tls_base;
3329    (*slot).tls_size = tls_size;
3330    let tid_ptr = &raw mut (*slot).tid;
3331    let flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD
3332        | CLONE_SYSVSEM | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SETTLS;
3333    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3334    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);
3335    if tid < 0 {
3336        ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel);
3337        (*slot).tid = -1;
3338        if stack_owned { sys_munmap(stack, stack_size); }
3339        if tls_size > 0 { sys_munmap(tls_base, tls_size); }
3340        release_thread_slot(slot);
3341        return EAGAIN;
3342    }
3343    if !attr.is_null() && (*attr).__i[6] == PTHREAD_CREATE_DETACHED {
3344        (*slot).detach_state = DT_DETACHED;
3345    }
3346    *thread = slot as PthreadT;
3347    0
3348}
3349
3350/// Tear down a joined or detached thread slot. The TLS block is kept mapped:
3351/// some runtimes (notably V8) retain pointers into an exited thread's TLS
3352/// and dereference them during process teardown.
3353unsafe fn release_finished_slot(slot: *mut Thread) {
3354    let stack = (*slot).stack;
3355    let stack_size = (*slot).stack_size;
3356    let stack_owned = (*slot).stack_owned;
3357    (*slot).tid = -1;
3358    (*slot).detach_state = DT_JOINABLE;
3359    (*slot).result = core::ptr::null_mut();
3360    (*slot).stack = core::ptr::null_mut();
3361    (*slot).stack_size = 0;
3362    (*slot).stack_owned = false;
3363    (*slot).fs_base = core::ptr::null_mut();
3364    (*slot).tls_base = core::ptr::null_mut();
3365    (*slot).tls_size = 0;
3366    if stack_owned && !stack.is_null() && stack_size > 0 {
3367        sys_munmap(stack, stack_size);
3368    }
3369    release_thread_slot(slot);
3370}
3371
3372#[no_mangle]
3373pub unsafe extern "C" fn pthread_join(thread: PthreadT, retval: *mut *mut c_void) -> c_int {
3374    let slot = thread as *mut Thread;
3375    if slot.is_null() { return EINVAL; }
3376    if thread == pthread_self() { return EDEADLK; }
3377    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
3378    let tid_ptr = &raw mut (*slot).tid;
3379    loop {
3380        pthread_testcancel();
3381        let tid = core::ptr::read_volatile(tid_ptr);
3382        if tid == 0 { break; }
3383        if tid < 0 { return EINVAL; }
3384        sys_futex(tid_ptr, FUTEX_WAIT, tid, null_mut(), null_mut(), 0);
3385        pthread_testcancel();
3386    }
3387    if !retval.is_null() { *retval = (*slot).result; }
3388    release_finished_slot(slot);
3389    0
3390}
3391
3392#[no_mangle]
3393pub unsafe extern "C" fn pthread_detach(thread: PthreadT) -> c_int {
3394    let slot = thread as *mut Thread;
3395    if slot.is_null() { return EINVAL; }
3396    let old = a_cas(&raw mut (*slot).detach_state, DT_JOINABLE, DT_DETACHED);
3397    if old == DT_EXITED {
3398        release_finished_slot(slot);
3399    }
3400    0
3401}
3402
3403#[no_mangle]
3404pub unsafe extern "C" fn pthread_exit(retval: *mut c_void) -> ! {
3405    if let Some(slot) = find_thread() {
3406        thread_finish(slot, retval)
3407    }
3408    sys_exit_thread(0)
3409}
3410
3411// pthread_attr_t stores a usize stack size at __i[0..2], a usize guard at
3412// __i[2..4], the stack top pointer at __i[4..6], and scalar flags after it.
3413unsafe fn attr_stack_size(attr: *const pthread_attr_t) -> usize {
3414    *((*attr).__i.as_ptr() as *const usize)
3415}
3416unsafe fn attr_set_stack_size(attr: *mut pthread_attr_t, sz: usize) {
3417    *((*attr).__i.as_mut_ptr() as *mut usize) = sz;
3418}
3419unsafe fn attr_stack_top(attr: *const pthread_attr_t) -> *mut c_void {
3420    *((*attr).__i.as_ptr().add(4) as *const *mut c_void)
3421}
3422unsafe fn attr_set_stack_top(attr: *mut pthread_attr_t, top: *mut c_void) {
3423    *((*attr).__i.as_mut_ptr().add(4) as *mut *mut c_void) = top;
3424}
3425unsafe fn attr_guard_size(attr: *const pthread_attr_t) -> usize {
3426    *((*attr).__i.as_ptr().add(2) as *const usize)
3427}
3428unsafe fn attr_set_guard_size(attr: *mut pthread_attr_t, sz: usize) {
3429    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = sz;
3430}
3431
3432// --- pthread_attr_* ---
3433#[no_mangle]
3434pub unsafe extern "C" fn pthread_attr_init(attr: *mut pthread_attr_t) -> c_int {
3435    core::ptr::write_bytes(attr, 0, 1);
3436    attr_set_stack_size(attr, STACK_SIZE);
3437    attr_set_guard_size(attr, 4096);
3438    (*attr).__i[6] = PTHREAD_CREATE_JOINABLE;
3439    (*attr).__i[7] = PTHREAD_INHERIT_SCHED;
3440    0
3441}
3442#[no_mangle]
3443pub unsafe extern "C" fn pthread_attr_destroy(_attr: *mut pthread_attr_t) -> c_int { 0 }
3444#[no_mangle]
3445pub unsafe extern "C" fn pthread_attr_setdetachstate(attr: *mut pthread_attr_t, s: c_int) -> c_int {
3446    if s != PTHREAD_CREATE_JOINABLE && s != PTHREAD_CREATE_DETACHED { return EINVAL; }
3447    (*attr).__i[6] = s; 0
3448}
3449#[no_mangle]
3450pub unsafe extern "C" fn pthread_attr_getdetachstate(attr: *const pthread_attr_t, s: *mut c_int) -> c_int {
3451    *s = (*attr).__i[6]; 0
3452}
3453#[no_mangle]
3454pub unsafe extern "C" fn pthread_attr_setstacksize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
3455    if sz < 2048 { return EINVAL; }
3456    attr_set_stack_size(attr, sz);
3457    attr_set_stack_top(attr, core::ptr::null_mut());
3458    0
3459}
3460#[no_mangle]
3461pub unsafe extern "C" fn pthread_attr_getstacksize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
3462    *sz = attr_stack_size(attr); 0
3463}
3464#[no_mangle]
3465pub unsafe extern "C" fn pthread_attr_setstack(attr: *mut pthread_attr_t, addr: *mut c_void, sz: usize) -> c_int {
3466    if sz < 2048 { return EINVAL; }
3467    attr_set_stack_size(attr, sz);
3468    // musl stores the top of the stack, not its base.
3469    attr_set_stack_top(attr, (addr as *mut u8).add(sz) as *mut c_void);
3470    0
3471}
3472#[no_mangle]
3473pub unsafe extern "C" fn pthread_attr_getstack(attr: *const pthread_attr_t, addr: *mut *mut c_void, sz: *mut usize) -> c_int {
3474    let size = attr_stack_size(attr);
3475    *sz = size;
3476    let top = attr_stack_top(attr);
3477    *addr = if top.is_null() {
3478        core::ptr::null_mut()
3479    } else {
3480        (top as *mut u8).sub(size) as *mut c_void
3481    };
3482    0
3483}
3484#[no_mangle]
3485pub unsafe extern "C" fn pthread_attr_setguardsize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
3486    attr_set_guard_size(attr, sz); 0
3487}
3488#[no_mangle]
3489pub unsafe extern "C" fn pthread_attr_getguardsize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
3490    *sz = attr_guard_size(attr); 0
3491}
3492#[no_mangle]
3493pub unsafe extern "C" fn pthread_attr_setscope(_attr: *mut pthread_attr_t, scope: c_int) -> c_int {
3494    if scope != PTHREAD_SCOPE_SYSTEM { return EINVAL; }
3495    0
3496}
3497#[no_mangle]
3498pub unsafe extern "C" fn pthread_attr_getscope(_attr: *const pthread_attr_t, scope: *mut c_int) -> c_int {
3499    *scope = PTHREAD_SCOPE_SYSTEM; 0
3500}
3501#[no_mangle]
3502pub unsafe extern "C" fn pthread_attr_setinheritsched(attr: *mut pthread_attr_t, inh: c_int) -> c_int {
3503    if inh != PTHREAD_INHERIT_SCHED && inh != PTHREAD_EXPLICIT_SCHED { return EINVAL; }
3504    (*attr).__i[7] = inh; 0
3505}
3506#[no_mangle]
3507pub unsafe extern "C" fn pthread_attr_getinheritsched(attr: *const pthread_attr_t, inh: *mut c_int) -> c_int {
3508    *inh = (*attr).__i[7]; 0
3509}
3510#[no_mangle]
3511pub unsafe extern "C" fn pthread_attr_setschedpolicy(attr: *mut pthread_attr_t, p: c_int) -> c_int {
3512    (*attr).__i[8] = p; 0
3513}
3514#[no_mangle]
3515pub unsafe extern "C" fn pthread_attr_getschedpolicy(attr: *const pthread_attr_t, p: *mut c_int) -> c_int {
3516    *p = (*attr).__i[8]; 0
3517}
3518#[no_mangle]
3519pub unsafe extern "C" fn pthread_attr_setschedparam(attr: *mut pthread_attr_t, param: *const sched_param) -> c_int {
3520    (*attr).__i[9] = (*param).sched_priority; 0
3521}
3522#[no_mangle]
3523pub unsafe extern "C" fn pthread_attr_getschedparam(attr: *const pthread_attr_t, param: *mut sched_param) -> c_int {
3524    (*param).sched_priority = (*attr).__i[9]; 0
3525}
3526
3527// --- pthread_mutexattr_* ---
3528#[no_mangle]
3529pub unsafe extern "C" fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> c_int {
3530    (*attr).__attr = 0; 0
3531}
3532#[no_mangle]
3533pub unsafe extern "C" fn pthread_mutexattr_destroy(_attr: *mut pthread_mutexattr_t) -> c_int { 0 }
3534#[no_mangle]
3535pub unsafe extern "C" fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, t: c_int) -> c_int {
3536    if (t as c_uint) > 2 { return EINVAL; }
3537    (*attr).__attr = ((*attr).__attr & !3) | t as c_uint; 0
3538}
3539#[no_mangle]
3540pub unsafe extern "C" fn pthread_mutexattr_gettype(attr: *const pthread_mutexattr_t, t: *mut c_int) -> c_int {
3541    *t = ((*attr).__attr & 3) as c_int; 0
3542}
3543#[no_mangle]
3544pub unsafe extern "C" fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, p: c_int) -> c_int {
3545    if (p as c_uint) > 1 { return EINVAL; }
3546    (*attr).__attr = ((*attr).__attr & !(MUTEX_PSHARED as c_uint)) | ((p as c_uint) << 7); 0
3547}
3548#[no_mangle]
3549pub unsafe extern "C" fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, p: *mut c_int) -> c_int {
3550    *p = (((*attr).__attr >> 7) & 1) as c_int; 0
3551}
3552
3553#[no_mangle]
3554pub unsafe extern "C" fn pthread_mutexattr_setprotocol(attr: *mut pthread_mutexattr_t, protocol: c_int) -> c_int {
3555    match protocol {
3556        0 => { (*attr).__attr &= !(MUTEX_PI as c_uint); 0 }
3557        1 => {
3558            let mut lk: c_int = 0;
3559            let r = sys_futex(&raw mut lk, FUTEX_LOCK_PI, 0, null_mut(), null_mut(), 0);
3560            if r < 0 { return (-r) as c_int; }
3561            sys_futex(&raw mut lk, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
3562            (*attr).__attr |= MUTEX_PI as c_uint;
3563            0
3564        }
3565        2 => ENOTSUP,
3566        _ => EINVAL,
3567    }
3568}
3569#[no_mangle]
3570pub unsafe extern "C" fn pthread_mutexattr_getprotocol(attr: *const pthread_mutexattr_t, protocol: *mut c_int) -> c_int {
3571    *protocol = (((*attr).__attr >> 3) & 3) as c_int; 0
3572}
3573
3574
3575#[no_mangle]
3576pub unsafe extern "C" fn pthread_mutexattr_setrobust(attr: *mut pthread_mutexattr_t, robust: c_int) -> c_int {
3577    if (robust as c_uint) > 1 { return EINVAL; }
3578    if robust != 0 {
3579        (*attr).__attr |= MUTEX_ROBUST as c_uint;
3580    } else {
3581        (*attr).__attr &= !(MUTEX_ROBUST as c_uint);
3582    }
3583    0
3584}
3585#[no_mangle]
3586pub unsafe extern "C" fn pthread_mutexattr_getrobust(attr: *const pthread_mutexattr_t, robust: *mut c_int) -> c_int {
3587    *robust = (((*attr).__attr >> 2) & 1) as c_int; 0
3588}
3589
3590#[no_mangle]
3591pub unsafe extern "C" fn pthread_mutex_consistent(m: *mut pthread_mutex_t) -> c_int {
3592    let old = a_load(&raw const (*m).__i[1]);
3593    let own = old & MUTEX_OWNER_MASK;
3594    if ((*m).__i[0] & MUTEX_ROBUST) == 0 || own == 0 || (old & MUTEX_ROBUST_PENDING) == 0 {
3595        return EINVAL;
3596    }
3597    let self_tid = sys_gettid() as c_int;
3598    if own != self_tid { return EPERM; }
3599    a_and(&raw mut (*m).__i[1], !(MUTEX_ROBUST_PENDING));
3600    0
3601}
3602
3603unsafe fn a_and(addr: *mut c_int, val: c_int) {
3604    let a = &*(addr as *const AtomicI32);
3605    a.fetch_and(val, Ordering::AcqRel);
3606}
3607
3608// --- pthread_mutex_* ---
3609const MUTEX_TYPE_MASK: c_int = 3;
3610const MUTEX_ROBUST: c_int = 4;
3611const MUTEX_PI: c_int = 8;
3612const MUTEX_PSHARED: c_int = 128;
3613const MUTEX_OWNER_MASK: c_int = 0x3fff_ffff;
3614const MUTEX_ROBUST_PENDING: c_int = 0x4000_0000;
3615const FUTEX_WAITER_BIT: c_int = 1i32 << 31;
3616
3617unsafe fn ensure_robust_list(slot: &mut Thread) {
3618    if slot.robust_list.futex_offset == 0 {
3619        slot.robust_list.futex_offset = -28;
3620        slot.robust_list.pending = core::ptr::null_mut();
3621        sys_set_robust_list(&mut slot.robust_list, 24);
3622    }
3623}
3624
3625unsafe fn mutex_trylock(m: *mut pthread_mutex_t) -> c_int {
3626    let type_ = (*m).__i[0];
3627    // Fast path: plain NORMAL only (no PI, no robust, no pshared).
3628    // A failed CAS must report EBUSY unconditionally: the old value may be
3629    // the waiter bit (0x80000000), whose low bits are zero, and masking it
3630    // with EBUSY would falsely report that the lock was acquired.
3631    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL {
3632        let old = a_cas(&raw mut (*m).__i[1], 0, EBUSY);
3633        return if old == 0 { 0 } else { EBUSY };
3634    }
3635    let base_type = type_ & MUTEX_TYPE_MASK;
3636    let self_tid = sys_gettid() as c_int;
3637    let old = a_load(&raw const (*m).__i[1]);
3638    let own = old & MUTEX_OWNER_MASK;
3639    if own == self_tid {
3640        if (type_ & MUTEX_PI) != 0 && (*m).__i[5] < 0 {
3641            (*m).__i[5] = 0;
3642            return 0;
3643        }
3644        if base_type == PTHREAD_MUTEX_RECURSIVE {
3645            if (*m).__i[5] >= c_int::MAX { return EAGAIN; }
3646            (*m).__i[5] += 1;
3647            return 0;
3648        }
3649        if base_type == PTHREAD_MUTEX_ERRORCHECK { return EDEADLK; }
3650        return EBUSY;
3651    }
3652    if own == MUTEX_OWNER_MASK { return ENOTRECOVERABLE; }
3653    if own != 0 || (old != 0 && (type_ & MUTEX_ROBUST) == 0) { return EBUSY; }
3654    let mut newtid = self_tid;
3655    if (type_ & MUTEX_ROBUST) != 0 {
3656        if (*m).__i[2] != 0 { newtid |= FUTEX_WAITER_BIT; }
3657        newtid |= old & MUTEX_ROBUST_PENDING;
3658    }
3659    if a_cas(&raw mut (*m).__i[1], old, newtid) == old {
3660        (*m).__i[5] = 0;
3661        if (type_ & MUTEX_ROBUST) != 0 {
3662            if let Some(slot) = find_thread() {
3663                ensure_robust_list(slot);
3664                let m_next = &raw mut (*m).__i[8] as *mut robust_list;
3665                let head = &mut slot.robust_list.list;
3666                (*m_next).next = head.next;
3667                head.next = m_next;
3668            }
3669        }
3670        if old != 0 { return EOWNERDEAD; }
3671        0
3672    } else { EBUSY }
3673}
3674
3675unsafe fn mutex_lock_internal(m: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3676    let type_ = (*m).__i[0];
3677    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL && a_cas(&raw mut (*m).__i[1], 0, EBUSY) == 0 {
3678        return 0;
3679    }
3680    let r = mutex_trylock(m);
3681    if r != EBUSY { return r; }
3682    if (type_ & MUTEX_PI) != 0 {
3683        let timeout_ptr = if abs_timeout.is_null() { core::ptr::null() } else { abs_timeout };
3684        loop {
3685            let e = futex_lock_pi(&raw mut (*m).__i[1], timeout_ptr);
3686            match e {
3687                0 => {
3688                    if (type_ & MUTEX_ROBUST) != 0 && (((*m).__i[1] & MUTEX_ROBUST_PENDING) != 0 || (*m).__i[2] != 0) {
3689                        (*m).__i[5] = -1;
3690                        let _ = mutex_trylock(m);
3691                        return EOWNERDEAD;
3692                    }
3693                    if (type_ & MUTEX_ROBUST) == 0 && (((*m).__i[1] & MUTEX_ROBUST_PENDING) != 0 || (*m).__i[2] != 0) {
3694                        (*m).__i[2] = -1;
3695                        futex_unlock_pi(&raw mut (*m).__i[1]);
3696                        return EBUSY;
3697                    }
3698                    (*m).__i[5] = -1;
3699                    let r2 = mutex_trylock(m);
3700                    if r2 == 0 { return 0; }
3701                    return r2;
3702                }
3703                EINTR => continue,
3704                EDEADLK => {
3705                    if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK { return e; }
3706                    loop { pause(); }
3707                }
3708                EOWNERDEAD => {
3709                    (*m).__i[5] = -1;
3710                    let _ = mutex_trylock(m);
3711                    return EOWNERDEAD;
3712                }
3713                _ => return e,
3714            }
3715        }
3716    }
3717    let mut spins = 100;
3718    while spins > 0 {
3719        let r = mutex_trylock(m);
3720        if r != EBUSY { return r; }
3721        core::hint::spin_loop();
3722        spins -= 1;
3723    }
3724    loop {
3725        let r = mutex_trylock(m);
3726        if r != EBUSY { return r; }
3727        if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK {
3728            let self_tid = sys_gettid() as c_int;
3729            if (a_load(&raw const (*m).__i[1]) & MUTEX_OWNER_MASK) == self_tid { return EDEADLK; }
3730        }
3731        a_fetch_add(&raw mut (*m).__i[2], 1);
3732        let val = a_load(&raw const (*m).__i[1]);
3733        // If the previous owner released the lock between trylock() and the
3734        // load above, retry instead of publishing a waiter-only lock word
3735        // (0x80000000) that no thread owns.
3736        if val == 0 {
3737            a_fetch_sub(&raw mut (*m).__i[2], 1);
3738            continue;
3739        }
3740        a_cas(&raw mut (*m).__i[1], val, val | FUTEX_WAITER_BIT);
3741        let e = futex_timedwait(&raw mut (*m).__i[1], val | FUTEX_WAITER_BIT, abs_timeout);
3742        a_fetch_sub(&raw mut (*m).__i[2], 1);
3743        if e != 0 && e != EINTR { return e; }
3744    }
3745}
3746
3747#[no_mangle]
3748pub unsafe extern "C" fn pthread_mutex_init(mutex: *mut pthread_mutex_t, attr: *const pthread_mutexattr_t) -> c_int {
3749    core::ptr::write_bytes(mutex, 0, 1);
3750    if !attr.is_null() { (*mutex).__i[0] = (*attr).__attr as c_int; }
3751    0
3752}
3753#[no_mangle]
3754pub unsafe extern "C" fn pthread_mutex_destroy(_mutex: *mut pthread_mutex_t) -> c_int { 0 }
3755#[no_mangle]
3756pub unsafe extern "C" fn pthread_mutex_lock(mutex: *mut pthread_mutex_t) -> c_int {
3757    mutex_lock_internal(mutex, core::ptr::null())
3758}
3759#[no_mangle]
3760pub unsafe extern "C" fn pthread_mutex_trylock(mutex: *mut pthread_mutex_t) -> c_int {
3761    mutex_trylock(mutex)
3762}
3763#[no_mangle]
3764pub unsafe extern "C" fn pthread_mutex_timedlock(mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3765    mutex_lock_internal(mutex, abs_timeout)
3766}
3767#[no_mangle]
3768pub unsafe extern "C" fn pthread_mutex_unlock(mutex: *mut pthread_mutex_t) -> c_int {
3769    let type_ = (*mutex).__i[0];
3770    let base_type = type_ & MUTEX_TYPE_MASK;
3771    let old = a_load(&raw const (*mutex).__i[1]);
3772    if base_type != PTHREAD_MUTEX_NORMAL {
3773        let self_tid = sys_gettid() as c_int;
3774        if (old & MUTEX_OWNER_MASK) != self_tid { return EPERM; }
3775        if base_type == PTHREAD_MUTEX_RECURSIVE && (*mutex).__i[5] > 0 {
3776            (*mutex).__i[5] -= 1;
3777            return 0;
3778        }
3779    }
3780    let mut new = 0;
3781    if (type_ & MUTEX_ROBUST) != 0 && (old & MUTEX_ROBUST_PENDING) != 0 {
3782        new = 0x7fffffff;
3783    }
3784    if (type_ & MUTEX_PI) != 0 {
3785        if old < 0 || a_cas(&raw mut (*mutex).__i[1], old, new) != old {
3786            if new != 0 { a_store(&raw mut (*mutex).__i[2], -1); }
3787            return futex_unlock_pi(&raw mut (*mutex).__i[1]);
3788        }
3789        return 0;
3790    }
3791    a_store(&raw mut (*mutex).__i[1], new);
3792    if new == 0 && (a_load(&raw const (*mutex).__i[2]) > 0 || old < 0) {
3793        futex_wake(&raw mut (*mutex).__i[1], 1);
3794    }
3795    0
3796}
3797
3798// --- pthread_condattr_* ---
3799#[no_mangle]
3800pub unsafe extern "C" fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> c_int {
3801    (*attr).__attr = 0; 0
3802}
3803#[no_mangle]
3804pub unsafe extern "C" fn pthread_condattr_destroy(_attr: *mut pthread_condattr_t) -> c_int { 0 }
3805#[no_mangle]
3806pub unsafe extern "C" fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, clk: c_int) -> c_int {
3807    if clk != CLOCK_REALTIME && clk != CLOCK_MONOTONIC { return EINVAL; }
3808    (*attr).__attr = ((*attr).__attr & 0x80000000) | clk as c_uint; 0
3809}
3810#[no_mangle]
3811pub unsafe extern "C" fn pthread_condattr_getclock(attr: *const pthread_condattr_t, clk: *mut c_int) -> c_int {
3812    *clk = ((*attr).__attr & 0x7fffffff) as c_int; 0
3813}
3814#[no_mangle]
3815pub unsafe extern "C" fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, p: c_int) -> c_int {
3816    if (p as c_uint) > 1 { return EINVAL; }
3817    (*attr).__attr = ((*attr).__attr & 0x7fffffff) | ((p as c_uint) << 31); 0
3818}
3819#[no_mangle]
3820pub unsafe extern "C" fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, p: *mut c_int) -> c_int {
3821    *p = ((*attr).__attr >> 31) as c_int; 0
3822}
3823
3824// --- pthread_cond_* ---
3825#[no_mangle]
3826pub unsafe extern "C" fn pthread_cond_init(cond: *mut pthread_cond_t, attr: *const pthread_condattr_t) -> c_int {
3827    core::ptr::write_bytes(cond, 0, 1);
3828    if !attr.is_null() {
3829        (*cond).__i[4] = ((*attr).__attr & 0x7fffffff) as c_int;
3830    }
3831    0
3832}
3833#[no_mangle]
3834pub unsafe extern "C" fn pthread_cond_destroy(_cond: *mut pthread_cond_t) -> c_int { 0 }
3835#[no_mangle]
3836pub unsafe extern "C" fn pthread_cond_wait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t) -> c_int {
3837    pthread_cond_timedwait(cond, mutex, core::ptr::null())
3838}
3839
3840
3841#[no_mangle]
3842pub unsafe extern "C" fn pthread_cond_timedwait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3843    pthread_testcancel();
3844    let seq_ptr = &raw mut (*cond).__i[2];
3845    let waiters_ptr = &raw mut (*cond).__i[3];
3846    let seq = a_load(seq_ptr);
3847    a_fetch_add(waiters_ptr, 1);
3848    pthread_mutex_unlock(mutex);
3849    let e = futex_timedwait(seq_ptr, seq, abs_timeout);
3850    a_fetch_sub(waiters_ptr, 1);
3851    let r = pthread_mutex_lock(mutex);
3852    if r != 0 { return r; }
3853    if e == EINTR {
3854        pthread_testcancel();
3855    }
3856    if e != 0 && e != EINTR { return e; }
3857    0
3858}
3859#[no_mangle]
3860pub unsafe extern "C" fn pthread_cond_signal(cond: *mut pthread_cond_t) -> c_int {
3861    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
3862    a_fetch_add(&raw mut (*cond).__i[2], 1);
3863    futex_wake(&raw mut (*cond).__i[2], 1);
3864    0
3865}
3866#[no_mangle]
3867pub unsafe extern "C" fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> c_int {
3868    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
3869    a_fetch_add(&raw mut (*cond).__i[2], 1);
3870    futex_wake(&raw mut (*cond).__i[2], -1);
3871    0
3872}
3873
3874// --- pthread_rwlockattr_* ---
3875#[no_mangle]
3876pub unsafe extern "C" fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> c_int {
3877    (*attr).__attr = [0; 2]; 0
3878}
3879#[no_mangle]
3880pub unsafe extern "C" fn pthread_rwlockattr_destroy(_attr: *mut pthread_rwlockattr_t) -> c_int { 0 }
3881#[no_mangle]
3882pub unsafe extern "C" fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, p: c_int) -> c_int {
3883    if (p as c_uint) > 1 { return EINVAL; }
3884    (*attr).__attr[0] = ((*attr).__attr[0] & !128) | ((p as c_uint) << 7); 0
3885}
3886#[no_mangle]
3887pub unsafe extern "C" fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, p: *mut c_int) -> c_int {
3888    *p = (((*attr).__attr[0] >> 7) & 1) as c_int; 0
3889}
3890
3891// --- pthread_rwlock_* ---
3892unsafe fn rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int {
3893    loop {
3894        let val = a_load(&raw const (*rw).__i[0]);
3895        let cnt = val & 0x7fffffff;
3896        if cnt == 0x7fffffff { return EBUSY; }
3897        if cnt == 0x7ffffffe { return EAGAIN; }
3898        if a_cas(&raw mut (*rw).__i[0], val, val + 1) == val { return 0; }
3899    }
3900}
3901unsafe fn rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int {
3902    if a_cas(&raw mut (*rw).__i[0], 0, 0x7fffffff) == 0 { 0 } else { EBUSY }
3903}
3904unsafe fn rwlock_timedrdlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
3905    let r = rwlock_tryrdlock(rw);
3906    if r != EBUSY { return r; }
3907    let mut spins = 100;
3908    while spins > 0 { let r = rwlock_tryrdlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
3909    loop {
3910        let r = rwlock_tryrdlock(rw);
3911        if r != EBUSY { return r; }
3912        let val = a_load(&raw const (*rw).__i[0]);
3913        if val & 0x7fffffff != 0x7fffffff { continue; }
3914        a_fetch_add(&raw mut (*rw).__i[1], 1);
3915        a_cas(&raw mut (*rw).__i[0], val, val | FUTEX_WAITER_BIT);
3916        let e = futex_timedwait(&raw mut (*rw).__i[0], val | FUTEX_WAITER_BIT, abs_timeout);
3917        a_fetch_sub(&raw mut (*rw).__i[1], 1);
3918        if e != 0 && e != EINTR { return e; }
3919    }
3920}
3921unsafe fn rwlock_timedwrlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
3922    let r = rwlock_trywrlock(rw);
3923    if r != EBUSY { return r; }
3924    let mut spins = 100;
3925    while spins > 0 { let r = rwlock_trywrlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
3926    loop {
3927        let r = rwlock_trywrlock(rw);
3928        if r != EBUSY { return r; }
3929        let val = a_load(&raw const (*rw).__i[0]);
3930        if val == 0 { continue; }
3931        a_fetch_add(&raw mut (*rw).__i[1], 1);
3932        a_cas(&raw mut (*rw).__i[0], val, val | FUTEX_WAITER_BIT);
3933        let e = futex_timedwait(&raw mut (*rw).__i[0], val | FUTEX_WAITER_BIT, abs_timeout);
3934        a_fetch_sub(&raw mut (*rw).__i[1], 1);
3935        if e != 0 && e != EINTR { return e; }
3936    }
3937}
3938
3939#[no_mangle]
3940pub unsafe extern "C" fn pthread_rwlock_init(rw: *mut pthread_rwlock_t, attr: *const pthread_rwlockattr_t) -> c_int {
3941    core::ptr::write_bytes(rw, 0, 1);
3942    if !attr.is_null() { (*rw).__i[2] = (*attr).__attr[0] as c_int & 128; }
3943    0
3944}
3945#[no_mangle]
3946pub unsafe extern "C" fn pthread_rwlock_destroy(_rw: *mut pthread_rwlock_t) -> c_int { 0 }
3947#[no_mangle]
3948pub unsafe extern "C" fn pthread_rwlock_rdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedrdlock(rw, core::ptr::null()) }
3949#[no_mangle]
3950pub unsafe extern "C" fn pthread_rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_tryrdlock(rw) }
3951#[no_mangle]
3952pub unsafe extern "C" fn pthread_rwlock_timedrdlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedrdlock(rw, t) }
3953#[no_mangle]
3954pub unsafe extern "C" fn pthread_rwlock_wrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedwrlock(rw, core::ptr::null()) }
3955#[no_mangle]
3956pub unsafe extern "C" fn pthread_rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_trywrlock(rw) }
3957#[no_mangle]
3958pub unsafe extern "C" fn pthread_rwlock_timedwrlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedwrlock(rw, t) }
3959#[no_mangle]
3960pub unsafe extern "C" fn pthread_rwlock_unlock(rw: *mut pthread_rwlock_t) -> c_int {
3961    loop {
3962        let val = a_load(&raw const (*rw).__i[0]);
3963        let cnt = val & 0x7fffffff;
3964        let new_val = if cnt == 0x7fffffff || cnt == 1 { 0 } else { val - 1 };
3965        if a_cas(&raw mut (*rw).__i[0], val, new_val) == val {
3966            if new_val == 0 && (a_load(&raw const (*rw).__i[1]) > 0 || val < 0) {
3967                futex_wake(&raw mut (*rw).__i[0], cnt);
3968            }
3969            return 0;
3970        }
3971    }
3972}
3973
3974// --- pthread_barrierattr_* ---
3975#[no_mangle]
3976pub unsafe extern "C" fn pthread_barrierattr_init(attr: *mut pthread_barrierattr_t) -> c_int { (*attr).__attr = 0; 0 }
3977#[no_mangle]
3978pub unsafe extern "C" fn pthread_barrierattr_destroy(_attr: *mut pthread_barrierattr_t) -> c_int { 0 }
3979#[no_mangle]
3980pub unsafe extern "C" fn pthread_barrierattr_setpshared(attr: *mut pthread_barrierattr_t, p: c_int) -> c_int {
3981    if (p as c_uint) > 1 { return EINVAL; }
3982    (*attr).__attr = p as c_uint; 0
3983}
3984#[no_mangle]
3985pub unsafe extern "C" fn pthread_barrierattr_getpshared(attr: *const pthread_barrierattr_t, p: *mut c_int) -> c_int {
3986    *p = (*attr).__attr as c_int; 0
3987}
3988
3989// --- pthread_barrier_* ---
3990#[no_mangle]
3991pub unsafe extern "C" fn pthread_barrier_init(b: *mut pthread_barrier_t, _attr: *const pthread_barrierattr_t, count: c_uint) -> c_int {
3992    if count == 0 { return EINVAL; }
3993    core::ptr::write_bytes(b, 0, 1);
3994    (*b).__i[2] = count as c_int - 1;
3995    0
3996}
3997#[no_mangle]
3998pub unsafe extern "C" fn pthread_barrier_destroy(_b: *mut pthread_barrier_t) -> c_int { 0 }
3999#[no_mangle]
4000pub unsafe extern "C" fn pthread_barrier_wait(b: *mut pthread_barrier_t) -> c_int {
4001    let limit = (*b).__i[2];
4002    if limit == 0 { return PTHREAD_BARRIER_SERIAL_THREAD; }
4003    spinlock_lock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4004    let arrived = a_load(&raw const (*b).__i[3]) + 1;
4005    a_store(&raw mut (*b).__i[3], arrived);
4006    if arrived > limit {
4007        a_store(&raw mut (*b).__i[3], 0);
4008        let gen = a_load(&raw const (*b).__i[4]);
4009        a_store(&raw mut (*b).__i[4], gen + 1);
4010        spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4011        futex_wake(&raw mut (*b).__i[4], -1);
4012        return PTHREAD_BARRIER_SERIAL_THREAD;
4013    }
4014    let gen = a_load(&raw const (*b).__i[4]);
4015    spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4016    while a_load(&raw const (*b).__i[4]) == gen {
4017        futex_wait(&raw mut (*b).__i[4], gen);
4018    }
4019    0
4020}
4021
4022// --- pthread_spin_* ---
4023#[no_mangle]
4024pub unsafe extern "C" fn pthread_spin_init(s: *mut pthread_spinlock_t, _pshared: c_int) -> c_int { a_store(s, 0); 0 }
4025#[no_mangle]
4026pub unsafe extern "C" fn pthread_spin_destroy(_s: *mut pthread_spinlock_t) -> c_int { 0 }
4027#[no_mangle]
4028pub unsafe extern "C" fn pthread_spin_lock(s: *mut pthread_spinlock_t) -> c_int {
4029    while a_load(s) != 0 || a_cas(s, 0, EBUSY) != 0 { core::hint::spin_loop(); }
4030    0
4031}
4032#[no_mangle]
4033pub unsafe extern "C" fn pthread_spin_trylock(s: *mut pthread_spinlock_t) -> c_int { a_cas(s, 0, EBUSY) }
4034#[no_mangle]
4035pub unsafe extern "C" fn pthread_spin_unlock(s: *mut pthread_spinlock_t) -> c_int { a_store(s, 0); 0 }
4036
4037// --- sem_* ---
4038#[no_mangle]
4039pub unsafe extern "C" fn sem_init(sem: *mut sem_t, pshared: c_int, value: c_uint) -> c_int {
4040    if value > SEM_VALUE_MAX as c_uint { return EINVAL; }
4041    (*sem).__val[0] = value as c_int;
4042    (*sem).__val[1] = 0;
4043    (*sem).__val[2] = if pshared != 0 { 0 } else { 128 };
4044    0
4045}
4046#[no_mangle]
4047pub unsafe extern "C" fn sem_destroy(_sem: *mut sem_t) -> c_int { 0 }
4048
4049unsafe fn sem_trywait_internal(sem: *mut sem_t) -> c_int {
4050    loop {
4051        let val = a_load(&raw const (*sem).__val[0]);
4052        if val & SEM_VALUE_MAX == 0 { return EAGAIN; }
4053        if a_cas(&raw mut (*sem).__val[0], val, val - 1) == val { return 0; }
4054    }
4055}
4056
4057#[no_mangle]
4058pub unsafe extern "C" fn sem_trywait(sem: *mut sem_t) -> c_int {
4059    if sem_trywait_internal(sem) == 0 { 0 } else { ERRNO!() = EAGAIN; -1 }
4060}
4061#[no_mangle]
4062pub unsafe extern "C" fn sem_wait(sem: *mut sem_t) -> c_int {
4063    pthread_testcancel();
4064    if sem_trywait_internal(sem) == 0 { return 0; }
4065    let mut spins = 100;
4066    while spins > 0 { if sem_trywait_internal(sem) == 0 { return 0; } core::hint::spin_loop(); spins -= 1; }
4067    loop {
4068        pthread_testcancel();
4069        if sem_trywait_internal(sem) == 0 { return 0; }
4070        let val = a_load(&raw const (*sem).__val[0]);
4071        if val & SEM_VALUE_MAX != 0 { continue; }
4072        a_cas(&raw mut (*sem).__val[0], val, val | FUTEX_WAITER_BIT);
4073        a_fetch_add(&raw mut (*sem).__val[1], 1);
4074        futex_wait(&raw mut (*sem).__val[0], FUTEX_WAITER_BIT);
4075        a_fetch_sub(&raw mut (*sem).__val[1], 1);
4076    }
4077}
4078#[no_mangle]
4079pub unsafe extern "C" fn sem_timedwait(sem: *mut sem_t, abs_timeout: *const timespec) -> c_int {
4080    pthread_testcancel();
4081    if sem_trywait_internal(sem) == 0 { return 0; }
4082    let mut spins = 100;
4083    while spins > 0 { if sem_trywait_internal(sem) == 0 { return 0; } core::hint::spin_loop(); spins -= 1; }
4084    loop {
4085        pthread_testcancel();
4086        if sem_trywait_internal(sem) == 0 { return 0; }
4087        let val = a_load(&raw const (*sem).__val[0]);
4088        if val & SEM_VALUE_MAX != 0 { continue; }
4089        a_cas(&raw mut (*sem).__val[0], val, val | FUTEX_WAITER_BIT);
4090        a_fetch_add(&raw mut (*sem).__val[1], 1);
4091        let e = futex_timedwait(&raw mut (*sem).__val[0], FUTEX_WAITER_BIT, abs_timeout);
4092        a_fetch_sub(&raw mut (*sem).__val[1], 1);
4093        if e != 0 && e != EINTR { ERRNO!() = e; return -1; }
4094    }
4095}
4096#[no_mangle]
4097pub unsafe extern "C" fn sem_post(sem: *mut sem_t) -> c_int {
4098    loop {
4099        let val = a_load(&raw const (*sem).__val[0]);
4100        if (val & SEM_VALUE_MAX) == SEM_VALUE_MAX { ERRNO!() = EOVERFLOW; return -1; }
4101        let mut new = val + 1;
4102        let waiters = a_load(&raw const (*sem).__val[1]);
4103        if waiters <= 1 { new &= !FUTEX_WAITER_BIT; }
4104        if a_cas(&raw mut (*sem).__val[0], val, new) == val {
4105            if val < 0 || waiters > 0 {
4106                futex_wake(&raw mut (*sem).__val[0], if waiters > 1 { 1 } else { -1 });
4107            }
4108            return 0;
4109        }
4110    }
4111}
4112#[no_mangle]
4113pub unsafe extern "C" fn sem_getvalue(sem: *mut sem_t, sval: *mut c_int) -> c_int {
4114    *sval = a_load(&raw const (*sem).__val[0]) & SEM_VALUE_MAX;
4115    0
4116}
4117
4118// ============================================================
4119// POSIX shared memory + named semaphores
4120// ============================================================
4121
4122const NAME_MAX: usize = 255;
4123const SEM_NSEMS_MAX: usize = 256;
4124
4125// global spinlock for semtab, upgrade to per-entry if contention matters
4126static SEMTAB_LOCK: AtomicI32 = AtomicI32::new(0);
4127
4128struct SemEntry {
4129    ino: u64,
4130    sem: *mut sem_t,
4131    refcnt: u32,
4132}
4133
4134// zero-init is fine for static mut (all-zero = free slots)
4135static mut SEMTAB: [SemEntry; SEM_NSEMS_MAX] = {
4136    const ZERO: SemEntry = SemEntry { ino: 0, sem: core::ptr::null_mut(), refcnt: 0 };
4137    [ZERO; SEM_NSEMS_MAX]
4138};
4139
4140unsafe fn semtab_lock() {
4141    while SEMTAB_LOCK.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed).is_err() {
4142        core::hint::spin_loop();
4143    }
4144}
4145
4146unsafe fn semtab_unlock() {
4147    SEMTAB_LOCK.store(0, Ordering::Release);
4148}
4149
4150// Validate shm/sem name and construct /dev/shm/<name> path.
4151// Returns path length or -1 with ERRNO set.
4152unsafe fn shm_mapname(name: *const c_char, buf: *mut u8) -> c_int {
4153    let mut p = name;
4154    // strip leading /
4155    while *p == b'/' as c_char { p = p.add(1); }
4156    let start = p;
4157    // find end of first component
4158    while *p != 0 && *p != b'/' as c_char { p = p.add(1); }
4159    let len = p.offset_from(start) as usize;
4160    // no trailing /, not empty, not "." or ".."
4161    if len == 0 || *p != 0 {
4162        ERRNO!() = EINVAL;
4163        return -1;
4164    }
4165    if len == 1 && *start == b'.' as c_char {
4166        ERRNO!() = EINVAL;
4167        return -1;
4168    }
4169    if len == 2 && *start == b'.' as c_char && *start.add(1) == b'.' as c_char {
4170        ERRNO!() = EINVAL;
4171        return -1;
4172    }
4173    if len > NAME_MAX {
4174        ERRNO!() = ENAMETOOLONG;
4175        return -1;
4176    }
4177    // build /dev/shm/<name>
4178    let prefix = b"/dev/shm/\0";
4179    let mut i = 0;
4180    while prefix[i] != 0 {
4181        *buf.add(i) = prefix[i];
4182        i += 1;
4183    }
4184    let mut j = 0;
4185    while j < len {
4186        *buf.add(i + j) = *start.add(j) as u8;
4187        j += 1;
4188    }
4189    *buf.add(i + j) = 0;
4190    (i + j) as c_int
4191}
4192
4193#[no_mangle]
4194pub unsafe extern "C" fn shm_open(name: *const c_char, flags: c_int, mode: mode_t) -> c_int {
4195    let mut buf = [0u8; 16 + NAME_MAX + 1];
4196    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
4197    let fd = sys_open(buf.as_ptr(), (flags | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
4198    if fd < 0 { ERRNO!() = (-fd) as c_int; return -1; }
4199    fd as c_int
4200}
4201
4202#[no_mangle]
4203pub unsafe extern "C" fn shm_unlink(name: *const c_char) -> c_int {
4204    let mut buf = [0u8; 16 + NAME_MAX + 1];
4205    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
4206    let r = sys_unlink(buf.as_ptr());
4207    syscall_ret(r) as c_int
4208}
4209
4210#[no_mangle]
4211pub unsafe extern "C" fn sem_open(name: *const c_char, flags: c_int, mut args: ...) -> *mut sem_t {
4212    let mut buf = [0u8; 16 + NAME_MAX + 1];
4213    if shm_mapname(name, buf.as_mut_ptr()).is_negative() {
4214        return core::ptr::null_mut(); // SEM_FAILED
4215    }
4216
4217    let oflags = flags & (O_CREAT | O_EXCL);
4218
4219    semtab_lock();
4220
4221    // find a free slot
4222    let mut slot: c_int = -1;
4223    for i in 0..SEMTAB_LEN {
4224        if SEMTAB[i].sem.is_null() && slot < 0 { slot = i as c_int; }
4225    }
4226    if slot < 0 {
4227        ERRNO!() = EMFILE;
4228        semtab_unlock();
4229        return core::ptr::null_mut();
4230    }
4231    // reserve slot
4232    SEMTAB[slot as usize].sem = !0usize as *mut sem_t; // sentinel
4233    semtab_unlock();
4234
4235    // extract va_args for O_CREAT
4236    let mut mode: mode_t = 0;
4237    let mut value: c_uint = 0;
4238    if oflags & O_CREAT != 0 {
4239        mode = args.next_arg::<mode_t>() & 0o666;
4240        value = args.next_arg::<c_uint>();
4241        if value > SEM_VALUE_MAX as c_uint {
4242            ERRNO!() = EINVAL;
4243            semtab_lock();
4244            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4245            semtab_unlock();
4246            return core::ptr::null_mut();
4247        }
4248    }
4249
4250    // try opening existing first (unless O_CREAT|O_EXCL)
4251    if oflags != O_CREAT | O_EXCL {
4252        let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
4253        if fd >= 0 {
4254            let map = sys_mmap(
4255                core::ptr::null_mut(),
4256                core::mem::size_of::<sem_t>(),
4257                PROT_READ | PROT_WRITE,
4258                MAP_SHARED,
4259                fd as i32,
4260                0,
4261            );
4262            sys_close(fd);
4263            if map != MMAP_FAILED {
4264                let st_ino = get_ino(fd as c_int, buf.as_ptr());
4265                return sem_register(map as *mut sem_t, st_ino, slot);
4266            }
4267        }
4268        if oflags == 0 {
4269            // no O_CREAT and file doesn't exist
4270            semtab_lock();
4271            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4272            semtab_unlock();
4273            return core::ptr::null_mut();
4274        }
4275    }
4276
4277    // create: write sem_t to temp file, mmap, link
4278    let mut tmp = [0u8; 32];
4279    let tmpname = b"/dev/shm/tmp-XXXXXX\0";
4280    tmp[..tmpname.len()].copy_from_slice(tmpname);
4281    // use clock for unique name
4282    let mut ts: timespec = core::mem::zeroed();
4283    sys_clock_gettime(0, &mut ts);
4284    // append ns to tmp name
4285    let mut n = ts.tv_nsec;
4286    let mut pos = tmpname.len() - 1;
4287    tmp[pos] = 0;
4288    pos -= 1;
4289    loop {
4290        tmp[pos] = b'0' + (n % 10) as u8;
4291        n /= 10;
4292        if n == 0 || pos == 0 { break; }
4293        pos -= 1;
4294    }
4295        // shift to start of number part
4296        let tmp_path = tmp.as_ptr();
4297
4298    let mut newsem: sem_t = core::mem::zeroed();
4299    newsem.__val[0] = value as c_int;
4300    newsem.__val[1] = 0;
4301    newsem.__val[2] = 128; // pshared=0 flag
4302
4303    let mut attempts = 0usize;
4304    loop {
4305        let fd = sys_open(tmp_path as *const u8, (O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
4306        if fd < 0 {
4307            if (-fd) as c_int == EEXIST {
4308                attempts += 1;
4309                if attempts >= 16 {
4310                    ERRNO!() = EEXIST;
4311                    semtab_lock();
4312                    SEMTAB[slot as usize].sem = core::ptr::null_mut();
4313                    semtab_unlock();
4314                    return core::ptr::null_mut();
4315                }
4316                continue;
4317            }
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 written = sys_write(fd, &newsem as *const sem_t as *const u8, core::mem::size_of::<sem_t>());
4324        if written != core::mem::size_of::<sem_t>() as i64 {
4325            sys_close(fd);
4326            sys_unlink(tmp_path);
4327            semtab_lock();
4328            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4329            semtab_unlock();
4330            return core::ptr::null_mut();
4331        }
4332        let map = sys_mmap(
4333            core::ptr::null_mut(),
4334            core::mem::size_of::<sem_t>(),
4335            PROT_READ | PROT_WRITE,
4336            MAP_SHARED,
4337            fd as i32,
4338            0,
4339        );
4340        sys_close(fd);
4341        if map == MMAP_FAILED {
4342            sys_unlink(tmp_path);
4343            semtab_lock();
4344            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4345            semtab_unlock();
4346            return core::ptr::null_mut();
4347        }
4348        // link to final name
4349        let r = sys_linkat(AT_FDCWD, tmp_path, AT_FDCWD, buf.as_ptr(), 0);
4350        let e = if r < 0 { (-r) as c_int } else { 0 };
4351        sys_unlink(tmp_path);
4352        if e == 0 {
4353            let st_ino = get_ino(-1, buf.as_ptr());
4354            return sem_register(map as *mut sem_t, st_ino, slot);
4355        }
4356        sys_munmap(map, core::mem::size_of::<sem_t>());
4357        if e != EEXIST || oflags == O_CREAT | O_EXCL {
4358            ERRNO!() = e;
4359            semtab_lock();
4360            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4361            semtab_unlock();
4362            return core::ptr::null_mut();
4363        }
4364        // EEXIST without O_EXCL: retry open existing
4365        break;
4366    }
4367
4368    // fallthrough: try opening the existing file that won the race
4369    let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
4370    if fd < 0 {
4371        semtab_lock();
4372        SEMTAB[slot as usize].sem = core::ptr::null_mut();
4373        semtab_unlock();
4374        return core::ptr::null_mut();
4375    }
4376    let map = sys_mmap(
4377        core::ptr::null_mut(),
4378        core::mem::size_of::<sem_t>(),
4379        PROT_READ | PROT_WRITE,
4380        MAP_SHARED,
4381        fd as i32,
4382        0,
4383    );
4384    sys_close(fd);
4385    if map == MMAP_FAILED {
4386        semtab_lock();
4387        SEMTAB[slot as usize].sem = core::ptr::null_mut();
4388        semtab_unlock();
4389        return core::ptr::null_mut();
4390    }
4391    let st_ino = get_ino(-1, buf.as_ptr());
4392    sem_register(map as *mut sem_t, st_ino, slot)
4393}
4394
4395unsafe fn get_ino(_fd_hint: c_int, path: *const u8) -> u64 {
4396    let mut st: Stat = core::mem::zeroed();
4397    if sys_newfstatat(AT_FDCWD, path as *const c_char, &mut st as *mut Stat as *mut u8, 0) == 0 {
4398        st.st_ino
4399    } else {
4400        0
4401    }
4402}
4403
4404unsafe fn sem_register(map: *mut sem_t, ino: u64, slot_hint: c_int) -> *mut sem_t {
4405    semtab_lock();
4406    // check if already mapped (by inode)
4407    for i in 0..SEMTAB_LEN {
4408        if SEMTAB[i].ino == ino && !SEMTAB[i].sem.is_null() && SEMTAB[i].sem != !0usize as *mut sem_t {
4409            // already mapped: unmap new, use existing, release hint slot
4410            sys_munmap(map as *mut u8, core::mem::size_of::<sem_t>());
4411            SEMTAB[slot_hint as usize].sem = core::ptr::null_mut();
4412            SEMTAB[i].refcnt += 1;
4413            let ret = SEMTAB[i].sem;
4414            semtab_unlock();
4415            return ret;
4416        }
4417    }
4418    // new entry
4419    SEMTAB[slot_hint as usize].sem = map;
4420    SEMTAB[slot_hint as usize].ino = ino;
4421    SEMTAB[slot_hint as usize].refcnt = 1;
4422    semtab_unlock();
4423    map
4424}
4425
4426const SEMTAB_LEN: usize = SEM_NSEMS_MAX;
4427
4428#[no_mangle]
4429pub unsafe extern "C" fn sem_close(sem: *mut sem_t) -> c_int {
4430    if sem.is_null() {
4431        ERRNO!() = EINVAL;
4432        return -1;
4433    }
4434    semtab_lock();
4435    for i in 0..SEMTAB_LEN {
4436        if SEMTAB[i].sem == sem {
4437            if SEMTAB[i].refcnt == 0 {
4438                semtab_unlock();
4439                ERRNO!() = EINVAL;
4440                return -1;
4441            }
4442            SEMTAB[i].refcnt -= 1;
4443            if SEMTAB[i].refcnt == 0 {
4444                SEMTAB[i].sem = core::ptr::null_mut();
4445                SEMTAB[i].ino = 0;
4446                semtab_unlock();
4447                sys_munmap(sem as *mut u8, core::mem::size_of::<sem_t>());
4448                return 0;
4449            }
4450            semtab_unlock();
4451            return 0;
4452        }
4453    }
4454    semtab_unlock();
4455    ERRNO!() = EINVAL;
4456    -1
4457}
4458
4459#[no_mangle]
4460pub unsafe extern "C" fn sem_unlink(name: *const c_char) -> c_int {
4461    shm_unlink(name)
4462}
4463
4464// --- pthread_once ---
4465#[no_mangle]
4466pub unsafe extern "C" fn pthread_once(control: *mut pthread_once_t, init_routine: Option<unsafe extern "C" fn()>) -> c_int {
4467    if a_load(control) == 2 { return 0; }
4468    loop {
4469        match a_cas(control, 0, 1) {
4470            0 => {
4471                if let Some(f) = init_routine { f(); }
4472                if a_swap(control, 2) == 3 { futex_wake(control, -1); }
4473                return 0;
4474            }
4475            1 => { a_cas(control, 1, 3); }
4476            3 => { futex_wait(control, 3); }
4477            _ => { return 0; }
4478        }
4479    }
4480}
4481
4482// --- pthread_key_* ---
4483#[no_mangle]
4484pub unsafe extern "C" fn pthread_key_create(key: *mut pthread_key_t, dtor: Option<unsafe extern "C" fn(*mut c_void)>) -> c_int {
4485    let start = NEXT_KEY.load(Ordering::Relaxed);
4486    let mut j = start;
4487    loop {
4488        if KEY_DTORS[j].is_none() {
4489            KEY_DTORS[j] = dtor;
4490            NEXT_KEY.store((j + 1) % PTHREAD_KEYS_MAX, Ordering::Relaxed);
4491            *key = j as pthread_key_t;
4492            return 0;
4493        }
4494        j = (j + 1) % PTHREAD_KEYS_MAX;
4495        if j == start { return EAGAIN; }
4496    }
4497}
4498#[no_mangle]
4499pub unsafe extern "C" fn pthread_key_delete(key: pthread_key_t) -> c_int {
4500    if key as usize >= PTHREAD_KEYS_MAX {
4501        return EINVAL;
4502    }
4503    KEY_DTORS[key as usize] = None;
4504    let count = thread_slot_count();
4505    let mut i = 0usize;
4506    while i < count {
4507        let slot = thread_slot_at(i);
4508        if !slot.is_null() && core::ptr::read_volatile(&raw const (*slot).tid) > 0 {
4509            (*slot).tsd[key as usize] = core::ptr::null_mut();
4510        }
4511        i += 1;
4512    }
4513    0
4514}
4515#[no_mangle]
4516pub unsafe extern "C" fn pthread_getspecific(key: pthread_key_t) -> *mut c_void {
4517    if key as usize >= PTHREAD_KEYS_MAX {
4518        return core::ptr::null_mut();
4519    }
4520    if let Some(slot) = find_thread() { slot.tsd[key as usize] } else { core::ptr::null_mut() }
4521}
4522#[no_mangle]
4523pub unsafe extern "C" fn pthread_setspecific(key: pthread_key_t, value: *const c_void) -> c_int {
4524    if key as usize >= PTHREAD_KEYS_MAX {
4525        ERRNO!() = EINVAL;
4526        return EINVAL;
4527    }
4528    if let Some(slot) = find_thread() {
4529        slot.tsd[key as usize] = value as *mut c_void;
4530        0
4531    } else { EINVAL }
4532}
4533
4534// --- pthread_cancel/state ---
4535unsafe fn run_cleanup_handlers(slot: &mut Thread) {
4536    let mut cb = slot.cancelbuf;
4537    while !cb.is_null() {
4538        let cur = &*cb;
4539        let f = cur.__f;
4540        let x = cur.__x;
4541        cb = cur.__next;
4542        if let Some(func) = f {
4543            func(x);
4544        }
4545    }
4546    slot.cancelbuf = core::ptr::null_mut();
4547}
4548
4549unsafe fn do_cancel() -> ! {
4550    if let Some(slot) = find_thread() {
4551        run_cleanup_handlers(slot);
4552        slot.result = !0usize as *mut c_void; // PTHREAD_CANCELED
4553        slot.detach_state = DT_EXITED;
4554        futex_wake(&raw mut slot.detach_state, 1);
4555    }
4556    sys_exit_thread(0);
4557}
4558
4559extern "C" fn cancel_handler(_sig: c_int) {
4560    unsafe {
4561        if let Some(slot) = find_thread() {
4562            // In asynchronous mode, cancel immediately from the signal handler.
4563            // In deferred mode, the signal just interrupts blocking syscalls so
4564            // the next cancellation point can act on the pending request.
4565            if slot.cancel != 0
4566                && slot.cancel_state == PTHREAD_CANCEL_ENABLE
4567                && slot.cancel_type == PTHREAD_CANCEL_ASYNCHRONOUS
4568            {
4569                do_cancel();
4570            }
4571        }
4572    }
4573}
4574
4575static CANCEL_INIT: AtomicI32 = AtomicI32::new(0);
4576
4577unsafe fn ensure_cancel_handler() {
4578    if CANCEL_INIT.swap(1, Ordering::AcqRel) == 0 {
4579        let act = KSigAction {
4580            sa_handler: cancel_handler as *const () as usize,
4581            sa_flags: SA_RESTORER,
4582            sa_restorer: sig_restorer as *const () as usize,
4583            sa_mask: [!0u64],
4584        };
4585        sys_rt_sigaction(SIGCANCEL, &act as *const KSigAction, core::ptr::null_mut(), 8);
4586    }
4587}
4588
4589#[no_mangle]
4590pub unsafe extern "C" fn pthread_cancel(thread: PthreadT) -> c_int {
4591    let slot = thread as *mut Thread;
4592    if slot.is_null() { return EINVAL; }
4593    ensure_cancel_handler();
4594    a_store(&raw mut (*slot).cancel, 1);
4595    let tid = (*slot).tid;
4596    if tid > 0 {
4597        sys_tgkill(sys_getpid() as c_int, tid, SIGCANCEL);
4598    }
4599    0
4600}
4601#[no_mangle]
4602pub unsafe extern "C" fn pthread_setcancelstate(state: c_int, oldstate: *mut c_int) -> c_int {
4603    if state != PTHREAD_CANCEL_ENABLE && state != PTHREAD_CANCEL_DISABLE { return EINVAL; }
4604    if let Some(slot) = find_thread() {
4605        if !oldstate.is_null() { *oldstate = slot.cancel_state; }
4606        slot.cancel_state = state;
4607        0
4608    } else { EINVAL }
4609}
4610#[no_mangle]
4611pub unsafe extern "C" fn pthread_setcanceltype(type_: c_int, oldtype: *mut c_int) -> c_int {
4612    if type_ != PTHREAD_CANCEL_DEFERRED && type_ != PTHREAD_CANCEL_ASYNCHRONOUS { return EINVAL; }
4613    if let Some(slot) = find_thread() {
4614        if !oldtype.is_null() { *oldtype = slot.cancel_type; }
4615        slot.cancel_type = type_;
4616        0
4617    } else { EINVAL }
4618}
4619#[no_mangle]
4620pub unsafe extern "C" fn pthread_testcancel() {
4621    if let Some(slot) = find_thread() {
4622        if slot.cancel != 0 && slot.cancel_state == PTHREAD_CANCEL_ENABLE {
4623            do_cancel();
4624        }
4625    }
4626}
4627
4628#[no_mangle]
4629pub unsafe extern "C" fn _pthread_cleanup_push(cb: *mut __ptcb, f: Option<unsafe extern "C" fn(*mut c_void)>, x: *mut c_void) {
4630    (*cb).__f = f;
4631    (*cb).__x = x;
4632    if let Some(slot) = find_thread() {
4633        (*cb).__next = slot.cancelbuf;
4634        slot.cancelbuf = cb;
4635    } else {
4636        (*cb).__next = core::ptr::null_mut();
4637    }
4638}
4639
4640#[no_mangle]
4641pub unsafe extern "C" fn _pthread_cleanup_pop(cb: *mut __ptcb, run: c_int) {
4642    if let Some(slot) = find_thread() {
4643        slot.cancelbuf = (*cb).__next;
4644    }
4645    if run != 0 {
4646        if let Some(f) = (*cb).__f {
4647            f((*cb).__x);
4648        }
4649    }
4650}
4651
4652#[no_mangle]
4653pub unsafe extern "C" fn pthread_kill(thread: PthreadT, sig: c_int) -> c_int {
4654    let slot = thread as *mut Thread;
4655    if slot.is_null() { return EINVAL; }
4656    let tid = (*slot).tid;
4657    if tid <= 0 { return EINVAL; }
4658    if sys_tgkill(sys_getpid() as c_int, tid, sig) < 0 { -1 } else { 0 }
4659}
4660
4661#[no_mangle]
4662pub unsafe extern "C" fn pthread_sigmask(how: c_int, set: *const SigSetT, oldset: *mut SigSetT) -> c_int {
4663    // POSIX pthread functions return the error number itself, not -1/errno.
4664    if sigprocmask(how, set, oldset) < 0 { ERRNO!() } else { 0 }
4665}
4666
4667
4668#[repr(C)]
4669pub struct lconv {
4670    pub decimal_point: *mut c_char,
4671    pub thousands_sep: *mut c_char,
4672    pub grouping: *mut c_char,
4673    pub int_curr_symbol: *mut c_char,
4674    pub currency_symbol: *mut c_char,
4675    pub mon_decimal_point: *mut c_char,
4676    pub mon_thousands_sep: *mut c_char,
4677    pub mon_grouping: *mut c_char,
4678    pub positive_sign: *mut c_char,
4679    pub negative_sign: *mut c_char,
4680    pub int_frac_digits: c_char,
4681    pub frac_digits: c_char,
4682    pub p_cs_precedes: c_char,
4683    pub p_sep_by_space: c_char,
4684    pub n_cs_precedes: c_char,
4685    pub n_sep_by_space: c_char,
4686    pub p_sign_posn: c_char,
4687    pub n_sign_posn: c_char,
4688    pub int_p_cs_precedes: c_char,
4689    pub int_p_sep_by_space: c_char,
4690    pub int_n_cs_precedes: c_char,
4691    pub int_n_sep_by_space: c_char,
4692    pub int_p_sign_posn: c_char,
4693    pub int_n_sign_posn: c_char,
4694}
4695
4696static UTF8_NAME: [u8; 6] = [b'U', b'T', b'F', b'-', b'8', 0];
4697static C_NAME: [u8; 2] = [b'C', 0];
4698static mut LOCALE_NAME: *const c_char = C_NAME.as_ptr() as *const c_char;
4699static mut LOCALE_CTYPE_UTF8: bool = true;
4700static mut EMPTY_STR: [c_char; 1] = [0];
4701static mut DECIMAL_POINT: [c_char; 2] = [b'.' as c_char, 0];
4702static mut LCONV: lconv = lconv {
4703    decimal_point: core::ptr::null_mut(),
4704    thousands_sep: core::ptr::null_mut(),
4705    grouping: core::ptr::null_mut(),
4706    int_curr_symbol: core::ptr::null_mut(),
4707    currency_symbol: core::ptr::null_mut(),
4708    mon_decimal_point: core::ptr::null_mut(),
4709    mon_thousands_sep: core::ptr::null_mut(),
4710    mon_grouping: core::ptr::null_mut(),
4711    positive_sign: core::ptr::null_mut(),
4712    negative_sign: core::ptr::null_mut(),
4713    int_frac_digits: (-1i32) as c_char,
4714    frac_digits: (-1i32) as c_char,
4715    p_cs_precedes: (-1i32) as c_char,
4716    p_sep_by_space: (-1i32) as c_char,
4717    n_cs_precedes: (-1i32) as c_char,
4718    n_sep_by_space: (-1i32) as c_char,
4719    p_sign_posn: (-1i32) as c_char,
4720    n_sign_posn: (-1i32) as c_char,
4721    int_p_cs_precedes: (-1i32) as c_char,
4722    int_p_sep_by_space: (-1i32) as c_char,
4723    int_n_cs_precedes: (-1i32) as c_char,
4724    int_n_sep_by_space: (-1i32) as c_char,
4725    int_p_sign_posn: (-1i32) as c_char,
4726    int_n_sign_posn: (-1i32) as c_char,
4727};
4728
4729unsafe fn cstr_contains_ci(s: *const u8, needle: &[u8]) -> bool {
4730    let len = strlen(s as *const c_char) as usize;
4731    let s_slice = core::slice::from_raw_parts(s, len);
4732    if needle.len() > len { return false; }
4733    for i in 0..=len - needle.len() {
4734        if s_slice[i..i + needle.len()].eq_ignore_ascii_case(needle) {
4735            return true;
4736        }
4737    }
4738    false
4739}
4740
4741#[no_mangle]
4742pub unsafe extern "C" fn setlocale(_category: c_int, locale: *const c_char) -> *mut c_char {
4743    if locale.is_null() || *locale == 0 {
4744        return LOCALE_NAME as *mut c_char;
4745    }
4746    let name = locale as *const u8;
4747    if strcmp(name, b"C\0".as_ptr()) == 0 || strcmp(name, b"POSIX\0".as_ptr()) == 0 {
4748        LOCALE_CTYPE_UTF8 = false;
4749        return LOCALE_NAME as *mut c_char;
4750    }
4751    if cstr_contains_ci(name, b"UTF-8") || cstr_contains_ci(name, b"UTF8") {
4752        LOCALE_CTYPE_UTF8 = true;
4753        return LOCALE_NAME as *mut c_char;
4754    }
4755    core::ptr::null_mut()
4756}
4757
4758#[no_mangle]
4759pub unsafe extern "C" fn localeconv() -> *mut lconv {
4760    let empty = core::ptr::addr_of_mut!(EMPTY_STR) as *mut c_char;
4761    let lconv = core::ptr::addr_of_mut!(LCONV);
4762    (*lconv).decimal_point = core::ptr::addr_of_mut!(DECIMAL_POINT) as *mut c_char;
4763    (*lconv).thousands_sep = empty;
4764    (*lconv).grouping = empty;
4765    (*lconv).int_curr_symbol = empty;
4766    (*lconv).currency_symbol = empty;
4767    (*lconv).mon_decimal_point = empty;
4768    (*lconv).mon_thousands_sep = empty;
4769    (*lconv).mon_grouping = empty;
4770    (*lconv).positive_sign = empty;
4771    (*lconv).negative_sign = empty;
4772    lconv
4773}
4774
4775pub type locale_t = *mut c_void;
4776static mut CURRENT_LOCALE: locale_t = LC_GLOBAL_LOCALE;
4777
4778static mut C_LOCALE_STORAGE: c_int = 0;
4779const C_LOCALE: locale_t = core::ptr::addr_of_mut!(C_LOCALE_STORAGE) as locale_t;
4780const LC_GLOBAL_LOCALE: locale_t = usize::MAX as locale_t;
4781
4782#[no_mangle]
4783pub unsafe extern "C" fn newlocale(_mask: c_int, name: *const c_char, base: locale_t) -> locale_t {
4784    if !name.is_null() && *name != 0 {
4785        let n = name as *const u8;
4786        if strcmp(n, b"C\0".as_ptr()) != 0
4787            && strcmp(n, b"POSIX\0".as_ptr()) != 0
4788        {
4789            return core::ptr::null_mut();
4790        }
4791    }
4792    if base.is_null() || base == C_LOCALE || base == LC_GLOBAL_LOCALE {
4793        C_LOCALE
4794    } else {
4795        core::ptr::null_mut()
4796    }
4797}
4798
4799#[no_mangle]
4800pub unsafe extern "C" fn freelocale(_loc: locale_t) {}
4801
4802#[no_mangle]
4803pub unsafe extern "C" fn uselocale(loc: locale_t) -> locale_t {
4804    let old = CURRENT_LOCALE;
4805    if !loc.is_null() {
4806        CURRENT_LOCALE = loc;
4807    }
4808    old
4809}
4810
4811#[no_mangle]
4812pub unsafe extern "C" fn duplocale(loc: locale_t) -> locale_t {
4813    if loc.is_null() {
4814        return core::ptr::null_mut();
4815    }
4816    C_LOCALE
4817}
4818
4819const NL_ITEM_CODESET: c_int = 14;
4820const NL_ITEM_RADIXCHAR: c_int = 0x10000;
4821const NL_ITEM_THOUSEP: c_int = 0x10001;
4822const NL_ITEM_YESEXPR: c_int = 0x50000;
4823const NL_ITEM_NOEXPR: c_int = 0x50001;
4824
4825const C_TIME_STRINGS: &[u8] = b"Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat\0\
4826Sunday\0Monday\0Tuesday\0Wednesday\0Thursday\0Friday\0Saturday\0\
4827Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec\0\
4828January\0February\0March\0April\0May\0June\0July\0August\0\
4829September\0October\0November\0December\0\
4830AM\0PM\0\
4831%a %b %e %T %Y\0%m/%d/%y\0%H:%M:%S\0%I:%M:%S %p\0\
4832\0\0%m/%d/%y\00123456789\0%a %b %e %T %Y\0%H:%M:%S\0";
4833
4834const C_NUMERIC_STRINGS: &[u8] = b".\0\0";
4835const C_MESSAGES_STRINGS: &[u8] = b"^[yY]\0^[nN]\0";
4836
4837unsafe fn langinfo_str(table: *const u8, mut idx: c_int) -> *mut c_char {
4838    let mut p = table;
4839    while idx > 0 {
4840        while *p != 0 { p = p.add(1); }
4841        p = p.add(1);
4842        idx -= 1;
4843    }
4844    p as *mut c_char
4845}
4846
4847#[no_mangle]
4848pub unsafe extern "C" fn nl_langinfo(item: c_int) -> *mut c_char {
4849    if item == NL_ITEM_CODESET {
4850        return if LOCALE_CTYPE_UTF8 {
4851            b"UTF-8\0".as_ptr() as *mut c_char
4852        } else {
4853            b"US-ASCII\0".as_ptr() as *mut c_char
4854        };
4855    }
4856    let cat = item >> 16;
4857    let idx = item & 0xFFFF;
4858    match cat {
4859        1 => {
4860            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
4861            langinfo_str(C_NUMERIC_STRINGS.as_ptr(), idx)
4862        }
4863        2 => {
4864            if idx > 49 { return b"\0".as_ptr() as *mut c_char; }
4865            langinfo_str(C_TIME_STRINGS.as_ptr(), idx)
4866        }
4867        5 => {
4868            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
4869            langinfo_str(C_MESSAGES_STRINGS.as_ptr(), idx)
4870        }
4871        _ => b"\0".as_ptr() as *mut c_char,
4872    }
4873}
4874
4875pub type nl_catd = *mut c_void;
4876
4877#[no_mangle]
4878pub unsafe extern "C" fn catopen(_name: *const c_char, _oflag: c_int) -> nl_catd {
4879    !0usize as nl_catd
4880}
4881
4882#[no_mangle]
4883pub unsafe extern "C" fn catclose(_catd: nl_catd) -> c_int { 0 }
4884
4885#[no_mangle]
4886pub unsafe extern "C" fn catgets(catd: nl_catd, _set_id: c_int, _msg_id: c_int, s: *const c_char) -> *mut c_char {
4887    if catd == !0usize as nl_catd {
4888        ERRNO!() = EBADF;
4889        return s as *mut c_char;
4890    }
4891    s as *mut c_char
4892}
4893
4894pub type IconvT = *mut c_void;
4895
4896const ENC_UTF8: i32 = 1;
4897const ENC_UTF16LE: i32 = 2;
4898const ENC_UTF16BE: i32 = 3;
4899const ENC_UTF32LE: i32 = 4;
4900const ENC_UTF32BE: i32 = 5;
4901const ENC_WCHAR_T: i32 = 6;
4902const ENC_ASCII: i32 = 7;
4903const ENC_LATIN1: i32 = 8;
4904const ENC_WIN1252: i32 = 9;
4905const ENC_WIN1251: i32 = 10;
4906const ENC_KOI8R: i32 = 11;
4907const ENC_GBK: i32 = 12;
4908const ENC_GB2312: i32 = 13;
4909const ENC_BIG5: i32 = 14;
4910const ENC_EUCJP: i32 = 15;
4911const ENC_SHIFTJIS: i32 = 16;
4912const ENC_ISO8859_2: i32 = 17;
4913const ENC_ISO8859_3: i32 = 18;
4914const ENC_ISO8859_4: i32 = 19;
4915const ENC_ISO8859_5: i32 = 20;
4916const ENC_ISO8859_6: i32 = 21;
4917const ENC_ISO8859_7: i32 = 22;
4918const ENC_ISO8859_8: i32 = 23;
4919const ENC_ISO8859_9: i32 = 24;
4920const ENC_ISO8859_10: i32 = 25;
4921const ENC_ISO8859_11: i32 = 26;
4922const ENC_ISO8859_13: i32 = 27;
4923const ENC_ISO8859_14: i32 = 28;
4924const ENC_ISO8859_15: i32 = 29;
4925const ENC_ISO8859_16: i32 = 30;
4926
4927include!("iconv_iso8859.rs");
4928
4929fn make_cd(from: i32, to: i32) -> IconvT {
4930    ((from as usize) << 16 | (to as usize) << 1 | 1) as IconvT
4931}
4932fn extract_from(cd: IconvT) -> i32 {
4933    ((cd as usize) >> 16) as i32
4934}
4935fn extract_to(cd: IconvT) -> i32 {
4936    (((cd as usize) >> 1) & 0x7fff) as i32
4937}
4938
4939unsafe fn match_name(input: *const u8, target: &[u8]) -> bool {
4940    let mut i = input;
4941    let mut j = 0;
4942    while *i != 0 && j < target.len() {
4943        let mut c = *i;
4944        if !c.is_ascii_alphanumeric() { i = i.add(1); continue; }
4945        c = c.to_ascii_lowercase();
4946        if c != target[j] { return false; }
4947        i = i.add(1);
4948        j += 1;
4949    }
4950    while *i != 0 && !(*i).is_ascii_alphanumeric() { i = i.add(1); }
4951    *i == 0 && j == target.len()
4952}
4953
4954unsafe fn find_encoding(name: *const u8) -> i32 {
4955    if name.is_null() { return -1; }
4956    if match_name(name, b"utf8") || match_name(name, b"utf-8") || match_name(name, b"char") { return ENC_UTF8; }
4957    if match_name(name, b"utf16le") || match_name(name, b"utf-16le") { return ENC_UTF16LE; }
4958    if match_name(name, b"utf16be") || match_name(name, b"utf-16be") { return ENC_UTF16BE; }
4959    if match_name(name, b"utf32le") || match_name(name, b"utf-32le") || match_name(name, b"ucs4le") { return ENC_UTF32LE; }
4960    if match_name(name, b"utf32be") || match_name(name, b"utf-32be") || match_name(name, b"ucs4be") { return ENC_UTF32BE; }
4961    if match_name(name, b"wchart") || match_name(name, b"wchar-t") { return ENC_WCHAR_T; }
4962    if match_name(name, b"ascii") || match_name(name, b"usascii") || match_name(name, b"iso646") { return ENC_ASCII; }
4963    if match_name(name, b"iso88591") || match_name(name, b"iso-8859-1") || match_name(name, b"latin1") { return ENC_LATIN1; }
4964    if match_name(name, b"iso88592") || match_name(name, b"iso-8859-2") { return ENC_ISO8859_2; }
4965    if match_name(name, b"iso88593") || match_name(name, b"iso-8859-3") { return ENC_ISO8859_3; }
4966    if match_name(name, b"iso88594") || match_name(name, b"iso-8859-4") { return ENC_ISO8859_4; }
4967    if match_name(name, b"iso88595") || match_name(name, b"iso-8859-5") { return ENC_ISO8859_5; }
4968    if match_name(name, b"iso88596") || match_name(name, b"iso-8859-6") { return ENC_ISO8859_6; }
4969    if match_name(name, b"iso88597") || match_name(name, b"iso-8859-7") { return ENC_ISO8859_7; }
4970    if match_name(name, b"iso88598") || match_name(name, b"iso-8859-8") { return ENC_ISO8859_8; }
4971    if match_name(name, b"iso88599") || match_name(name, b"iso-8859-9") { return ENC_ISO8859_9; }
4972    if match_name(name, b"iso885910") || match_name(name, b"iso-8859-10") { return ENC_ISO8859_10; }
4973    if match_name(name, b"iso885911") || match_name(name, b"iso-8859-11") || match_name(name, b"tis620") { return ENC_ISO8859_11; }
4974    if match_name(name, b"iso885913") || match_name(name, b"iso-8859-13") { return ENC_ISO8859_13; }
4975    if match_name(name, b"iso885914") || match_name(name, b"iso-8859-14") { return ENC_ISO8859_14; }
4976    if match_name(name, b"iso885915") || match_name(name, b"iso-8859-15") { return ENC_ISO8859_15; }
4977    if match_name(name, b"iso885916") || match_name(name, b"iso-8859-16") { return ENC_ISO8859_16; }
4978    if match_name(name, b"cp1252") || match_name(name, b"windows1252") || match_name(name, b"windows-1252") { return ENC_WIN1252; }
4979    if match_name(name, b"cp1251") || match_name(name, b"windows1251") || match_name(name, b"windows-1251") { return ENC_WIN1251; }
4980    if match_name(name, b"koi8r") || match_name(name, b"koi8-r") { return ENC_KOI8R; }
4981    if match_name(name, b"gbk") || match_name(name, b"cp936") { return ENC_GBK; }
4982    if match_name(name, b"gb2312") { return ENC_GB2312; }
4983    if match_name(name, b"big5") || match_name(name, b"bigfive") || match_name(name, b"cp950") { return ENC_BIG5; }
4984    if match_name(name, b"eucjp") || match_name(name, b"euc-jp") { return ENC_EUCJP; }
4985    if match_name(name, b"shiftjis") || match_name(name, b"sjis") || match_name(name, b"cp932") { return ENC_SHIFTJIS; }
4986    -1
4987}
4988
4989fn uni_to_jis(c: u32) -> u16 {
4990    let mut b = 0usize;
4991    let mut nel = REV_JIS.len();
4992    loop {
4993        let i = nel / 2;
4994        let j = REV_JIS[b + i] as usize;
4995        let row = j / 256;
4996        let col = j % 256;
4997        let d = JIS0208[row * 94 + col] as u32;
4998        if d == c { return (j as u16) + 0x2121; }
4999        if nel == 1 { return 0; }
5000        if c < d { nel /= 2; }
5001        else { b += i; nel -= nel / 2; }
5002    }
5003}
5004
5005unsafe fn iconv_decode(enc: i32, src: *const u8, src_left: usize) -> (u32, usize, c_int) {
5006    if src_left == 0 { return (0, 0, EINVAL); }
5007    match enc {
5008        ENC_UTF8 => {
5009            let c = *src;
5010            if c < 128 { return (c as u32, 1, 0); }
5011            if c < 0xC2 { return (0, 0, EILSEQ); }
5012            if c < 0xE0 {
5013                if src_left < 2 || (*src.add(1) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
5014                return (((c as u32 & 0x1F) << 6) | (*src.add(1) as u32 & 0x3F), 2, 0);
5015            }
5016            if c < 0xF0 {
5017                if src_left < 3 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
5018                let cp = ((c as u32 & 0x0F) << 12) | ((*src.add(1) as u32 & 0x3F) << 6) | (*src.add(2) as u32 & 0x3F);
5019                if cp < 0x800 { return (0, 0, EILSEQ); }
5020                return (cp, 3, 0);
5021            }
5022            if c < 0xF8 {
5023                if src_left < 4 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 || (*src.add(3) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
5024                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);
5025                if cp < 0x10000 || cp >= 0x110000 { return (0, 0, EILSEQ); }
5026                return (cp, 4, 0);
5027            }
5028            (0, 0, EILSEQ)
5029        }
5030        ENC_UTF16LE => {
5031            if src_left < 2 { return (0, 0, EINVAL); }
5032            let c = (*src as u32) | ((*src.add(1) as u32) << 8);
5033            if c >= 0xD800 && c <= 0xDBFF {
5034                if src_left < 4 { return (0, 0, EINVAL); }
5035                let d = (*src.add(2) as u32) | ((*src.add(3) as u32) << 8);
5036                if d < 0xDC00 || d > 0xDFFF { return (0, 0, EILSEQ); }
5037                return (((c - 0xD800) << 10) + (d - 0xDC00) + 0x10000, 4, 0);
5038            }
5039            if c >= 0xDC00 && c <= 0xDFFF { return (0, 0, EILSEQ); }
5040            (c, 2, 0)
5041        }
5042        ENC_UTF16BE => {
5043            if src_left < 2 { return (0, 0, EINVAL); }
5044            let c = ((*src as u32) << 8) | (*src.add(1) as u32);
5045            if c >= 0xD800 && c <= 0xDBFF {
5046                if src_left < 4 { return (0, 0, EINVAL); }
5047                let d = ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
5048                if d < 0xDC00 || d > 0xDFFF { return (0, 0, EILSEQ); }
5049                return (((c - 0xD800) << 10) + (d - 0xDC00) + 0x10000, 4, 0);
5050            }
5051            if c >= 0xDC00 && c <= 0xDFFF { return (0, 0, EILSEQ); }
5052            (c, 2, 0)
5053        }
5054        ENC_UTF32LE => {
5055            if src_left < 4 { return (0, 0, EINVAL); }
5056            let c = (*src as u32) | ((*src.add(1) as u32) << 8) | ((*src.add(2) as u32) << 16) | ((*src.add(3) as u32) << 24);
5057            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
5058            if c >= 0x110000 { return (0, 0, EILSEQ); }
5059            (c, 4, 0)
5060        }
5061        ENC_UTF32BE => {
5062            if src_left < 4 { return (0, 0, EINVAL); }
5063            let c = ((*src as u32) << 24) | ((*src.add(1) as u32) << 16) | ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
5064            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
5065            if c >= 0x110000 { return (0, 0, EILSEQ); }
5066            (c, 4, 0)
5067        }
5068        ENC_WCHAR_T => {
5069            if src_left < 4 { return (0, 0, EINVAL); }
5070            let c = core::ptr::read_unaligned(src as *const u32);
5071            if c >= 0xD800 && c < 0xE000 { return (0, 0, EILSEQ); }
5072            if c >= 0x110000 { return (0, 0, EILSEQ); }
5073            (c, 4, 0)
5074        }
5075        ENC_ASCII => {
5076            let c = *src as u32;
5077            if c >= 128 { return (0, 0, EILSEQ); }
5078            (c, 1, 0)
5079        }
5080        ENC_LATIN1 => (*src as u32, 1, 0),
5081        ENC_ISO8859_2 => (iso8859_to_u(&ISO8859_2_TO_U, *src), 1, 0),
5082        ENC_ISO8859_3 => (iso8859_to_u(&ISO8859_3_TO_U, *src), 1, 0),
5083        ENC_ISO8859_4 => (iso8859_to_u(&ISO8859_4_TO_U, *src), 1, 0),
5084        ENC_ISO8859_5 => (iso8859_to_u(&ISO8859_5_TO_U, *src), 1, 0),
5085        ENC_ISO8859_6 => (iso8859_to_u(&ISO8859_6_TO_U, *src), 1, 0),
5086        ENC_ISO8859_7 => (iso8859_to_u(&ISO8859_7_TO_U, *src), 1, 0),
5087        ENC_ISO8859_8 => (iso8859_to_u(&ISO8859_8_TO_U, *src), 1, 0),
5088        ENC_ISO8859_9 => (iso8859_to_u(&ISO8859_9_TO_U, *src), 1, 0),
5089        ENC_ISO8859_10 => (iso8859_to_u(&ISO8859_10_TO_U, *src), 1, 0),
5090        ENC_ISO8859_11 => (iso8859_to_u(&ISO8859_11_TO_U, *src), 1, 0),
5091        ENC_ISO8859_13 => (iso8859_to_u(&ISO8859_13_TO_U, *src), 1, 0),
5092        ENC_ISO8859_14 => (iso8859_to_u(&ISO8859_14_TO_U, *src), 1, 0),
5093        ENC_ISO8859_15 => (iso8859_to_u(&ISO8859_15_TO_U, *src), 1, 0),
5094        ENC_ISO8859_16 => (iso8859_to_u(&ISO8859_16_TO_U, *src), 1, 0),
5095        ENC_WIN1252 => {
5096            let b = *src;
5097            if b < 128 { return (b as u32, 1, 0); }
5098            (WIN1252_TO_U[b as usize - 128], 1, 0)
5099        }
5100        ENC_GBK | ENC_GB2312 => {
5101            let c = *src;
5102            if c < 128 { return (c as u32, 1, 0); }
5103            if c == 128 { return (0x20AC, 1, 0); }
5104            if src_left < 2 { return (0, 0, EINVAL); }
5105            let d = *src.add(1);
5106            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
5107            let row = (c as usize).wrapping_sub(0x81);
5108            if row >= 126 { return (0, 0, EILSEQ); }
5109            let mut col = (d as usize) - 0x40;
5110            if col > 63 { col -= 1; }
5111            let cp = GB18030_TABLE[row * 190 + col] as u32;
5112            if cp == 0 { return (0, 0, EILSEQ); }
5113            (cp, 2, 0)
5114        }
5115        ENC_BIG5 => {
5116            let c = *src;
5117            if c < 128 { return (c as u32, 1, 0); }
5118            if src_left < 2 { return (0, 0, EINVAL); }
5119            let d = *src.add(1);
5120            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
5121            let mut col = (d as usize) - 0x40;
5122            if col > 0x3E { col -= 0x22; }
5123            if c >= 0xA1 && c < 0xFA {
5124                let row = (c as usize) - 0xA1;
5125                if row >= 89 { return (0, 0, EILSEQ); }
5126                let cp = BIG5_TABLE[row * 157 + col] as u32;
5127                if cp == 0 { return (0, 0, EILSEQ); }
5128                return (cp, 2, 0);
5129            }
5130            (0, 0, EILSEQ)
5131        }
5132        ENC_EUCJP => {
5133            let c = *src;
5134            if c < 128 { return (c as u32, 1, 0); }
5135            if c == 0x8E {
5136                if src_left < 2 { return (0, 0, EINVAL); }
5137                let d = *src.add(1);
5138                if d < 0xA1 || d > 0xDF { return (0, 0, EILSEQ); }
5139                return ((d as u32) + 0xFF61 - 0xA1, 2, 0);
5140            }
5141            if c < 0xA1 { return (0, 0, EILSEQ); }
5142            if src_left < 2 { return (0, 0, EINVAL); }
5143            let d = *src.add(1);
5144            if d < 0xA1 || d > 0xFE { return (0, 0, EILSEQ); }
5145            let row = (c as usize) - 0xA1;
5146            let col = (d as usize) - 0xA1;
5147            if row >= 84 || col >= 94 { return (0, 0, EILSEQ); }
5148            let cp = JIS0208[row * 94 + col] as u32;
5149            if cp == 0 { return (0, 0, EILSEQ); }
5150            (cp, 2, 0)
5151        }
5152        ENC_SHIFTJIS => {
5153            let c = *src;
5154            if c < 128 { return (c as u32, 1, 0); }
5155            if c >= 0xA1 && c <= 0xDF { return ((c as u32) + 0xFF61 - 0xA1, 1, 0); }
5156            if src_left < 2 { return (0, 0, EINVAL); }
5157            let d = *src.add(1);
5158            if d < 0x40 || d == 0x7F || d > 0xFC { return (0, 0, EILSEQ); }
5159            let row = if c >= 129 && c <= 159 { (c as usize) - 129 }
5160                      else if c >= 224 && c <= 239 { (c as usize) - 193 }
5161                      else { return (0, 0, EILSEQ); };
5162            let (col, row_adj) = if d >= 64 && d <= 158 && d != 127 {
5163                let mut dd = d as usize;
5164                if dd > 127 { dd -= 1; }
5165                (dd - 64, row * 2)
5166            } else if d >= 159 && d <= 252 {
5167                ((d as usize) - 159, row * 2 + 1)
5168            } else {
5169                return (0, 0, EILSEQ);
5170            };
5171            if row_adj >= 84 { return (0, 0, EILSEQ); }
5172            let cp = JIS0208[row_adj * 94 + col] as u32;
5173            if cp == 0 { return (0, 0, EILSEQ); }
5174            (cp, 2, 0)
5175        }
5176        _ => (0, 0, EILSEQ),
5177    }
5178}
5179
5180unsafe fn encode_single_byte(
5181    table: &[u32; 128],
5182    c: u32,
5183    dst: *mut u8,
5184    dst_left: usize,
5185) -> (usize, c_int) {
5186    if let Some(b) = u_to_iso8859(table, c) {
5187        if dst_left < 1 { return (0, E2BIG); }
5188        *dst = b;
5189        (1, 0)
5190    } else {
5191        (0, EILSEQ)
5192    }
5193}
5194
5195unsafe fn iconv_encode(enc: i32, c: u32, dst: *mut u8, dst_left: usize) -> (usize, c_int) {
5196    // All ISO-8859 tables, Windows-1251 and KOI8-R share the same
5197    // ASCII-passthrough + reverse-table encoding.
5198    let single_byte_table = match enc {
5199        ENC_ISO8859_2 => Some(&ISO8859_2_TO_U),
5200        ENC_ISO8859_3 => Some(&ISO8859_3_TO_U),
5201        ENC_ISO8859_4 => Some(&ISO8859_4_TO_U),
5202        ENC_ISO8859_5 => Some(&ISO8859_5_TO_U),
5203        ENC_ISO8859_6 => Some(&ISO8859_6_TO_U),
5204        ENC_ISO8859_7 => Some(&ISO8859_7_TO_U),
5205        ENC_ISO8859_8 => Some(&ISO8859_8_TO_U),
5206        ENC_ISO8859_9 => Some(&ISO8859_9_TO_U),
5207        ENC_ISO8859_10 => Some(&ISO8859_10_TO_U),
5208        ENC_ISO8859_11 => Some(&ISO8859_11_TO_U),
5209        ENC_ISO8859_13 => Some(&ISO8859_13_TO_U),
5210        ENC_ISO8859_14 => Some(&ISO8859_14_TO_U),
5211        ENC_ISO8859_15 => Some(&ISO8859_15_TO_U),
5212        ENC_ISO8859_16 => Some(&ISO8859_16_TO_U),
5213        ENC_WIN1251 => Some(&WIN1251_TO_U),
5214        ENC_KOI8R => Some(&KOI8R_TO_U),
5215        _ => None,
5216    };
5217    if let Some(table) = single_byte_table {
5218        return encode_single_byte(table, c, dst, dst_left);
5219    }
5220
5221    match enc {
5222        ENC_UTF8 => {
5223            if c < 0x80 {
5224                if dst_left < 1 { return (0, E2BIG); }
5225                *dst = c as u8; return (1, 0);
5226            }
5227            if c < 0x800 {
5228                if dst_left < 2 { return (0, E2BIG); }
5229                *dst = (0xC0 | (c >> 6)) as u8;
5230                *dst.add(1) = (0x80 | (c & 0x3F)) as u8;
5231                return (2, 0);
5232            }
5233            if c < 0x10000 {
5234                if dst_left < 3 { return (0, E2BIG); }
5235                *dst = (0xE0 | (c >> 12)) as u8;
5236                *dst.add(1) = (0x80 | ((c >> 6) & 0x3F)) as u8;
5237                *dst.add(2) = (0x80 | (c & 0x3F)) as u8;
5238                return (3, 0);
5239            }
5240            if dst_left < 4 { return (0, E2BIG); }
5241            *dst = (0xF0 | (c >> 18)) as u8;
5242            *dst.add(1) = (0x80 | ((c >> 12) & 0x3F)) as u8;
5243            *dst.add(2) = (0x80 | ((c >> 6) & 0x3F)) as u8;
5244            *dst.add(3) = (0x80 | (c & 0x3F)) as u8;
5245            (4, 0)
5246        }
5247        ENC_UTF16LE => {
5248            if c < 0x10000 {
5249                if dst_left < 2 { return (0, E2BIG); }
5250                *dst = (c & 0xFF) as u8;
5251                *dst.add(1) = (c >> 8) as u8;
5252                return (2, 0);
5253            }
5254            if dst_left < 4 { return (0, E2BIG); }
5255            let c = c - 0x10000;
5256            let hi = ((c >> 10) + 0xD800) as u16;
5257            let lo = ((c & 0x3FF) + 0xDC00) as u16;
5258            *dst = (hi & 0xFF) as u8; *dst.add(1) = (hi >> 8) as u8;
5259            *dst.add(2) = (lo & 0xFF) as u8; *dst.add(3) = (lo >> 8) as u8;
5260            (4, 0)
5261        }
5262        ENC_UTF16BE => {
5263            if c < 0x10000 {
5264                if dst_left < 2 { return (0, E2BIG); }
5265                *dst = (c >> 8) as u8;
5266                *dst.add(1) = (c & 0xFF) as u8;
5267                return (2, 0);
5268            }
5269            if dst_left < 4 { return (0, E2BIG); }
5270            let c = c - 0x10000;
5271            let hi = ((c >> 10) + 0xD800) as u16;
5272            let lo = ((c & 0x3FF) + 0xDC00) as u16;
5273            *dst = (hi >> 8) as u8; *dst.add(1) = (hi & 0xFF) as u8;
5274            *dst.add(2) = (lo >> 8) as u8; *dst.add(3) = (lo & 0xFF) as u8;
5275            (4, 0)
5276        }
5277        ENC_UTF32LE => {
5278            if dst_left < 4 { return (0, E2BIG); }
5279            *dst = (c & 0xFF) as u8; *dst.add(1) = ((c >> 8) & 0xFF) as u8;
5280            *dst.add(2) = ((c >> 16) & 0xFF) as u8; *dst.add(3) = (c >> 24) as u8;
5281            (4, 0)
5282        }
5283        ENC_UTF32BE => {
5284            if dst_left < 4 { return (0, E2BIG); }
5285            *dst = (c >> 24) as u8; *dst.add(1) = ((c >> 16) & 0xFF) as u8;
5286            *dst.add(2) = ((c >> 8) & 0xFF) as u8; *dst.add(3) = (c & 0xFF) as u8;
5287            (4, 0)
5288        }
5289        ENC_WCHAR_T => {
5290            if dst_left < 4 { return (0, E2BIG); }
5291            core::ptr::write_unaligned(dst as *mut u32, c);
5292            (4, 0)
5293        }
5294        ENC_ASCII => {
5295            if c < 128 {
5296                if dst_left < 1 { return (0, E2BIG); }
5297                *dst = c as u8; return (1, 0);
5298            }
5299            (0, EILSEQ)
5300        }
5301        ENC_LATIN1 => {
5302            if c < 256 {
5303                if dst_left < 1 { return (0, E2BIG); }
5304                *dst = c as u8; return (1, 0);
5305            }
5306            (0, EILSEQ)
5307        }
5308        ENC_WIN1252 => {
5309            if c < 128 {
5310                if dst_left < 1 { return (0, E2BIG); }
5311                *dst = c as u8; return (1, 0);
5312            }
5313            if c >= 0xA0 && c <= 0xFF && WIN1252_TO_U[c as usize - 128] == c {
5314                if dst_left < 1 { return (0, E2BIG); }
5315                *dst = c as u8; return (1, 0);
5316            }
5317            for i in 0..128usize {
5318                if WIN1252_TO_U[i] == c {
5319                    if dst_left < 1 { return (0, E2BIG); }
5320                    *dst = (i + 128) as u8; return (1, 0);
5321                }
5322            }
5323            (0, EILSEQ)
5324        }
5325        ENC_WIN1251 => {
5326            if c < 128 {
5327                if dst_left < 1 { return (0, E2BIG); }
5328                *dst = c as u8; return (1, 0);
5329            }
5330            for i in 0..128usize {
5331                if WIN1251_TO_U[i] == c {
5332                    if dst_left < 1 { return (0, E2BIG); }
5333                    *dst = (i + 128) as u8; return (1, 0);
5334                }
5335            }
5336            (0, EILSEQ)
5337        }
5338        ENC_KOI8R => {
5339            if c < 128 {
5340                if dst_left < 1 { return (0, E2BIG); }
5341                *dst = c as u8; return (1, 0);
5342            }
5343            for i in 0..128usize {
5344                if KOI8R_TO_U[i] == c {
5345                    if dst_left < 1 { return (0, E2BIG); }
5346                    *dst = (i + 128) as u8; return (1, 0);
5347                }
5348            }
5349            (0, EILSEQ)
5350        }
5351        ENC_GBK | ENC_GB2312 => {
5352            if c < 128 {
5353                if dst_left < 1 { return (0, E2BIG); }
5354                *dst = c as u8; return (1, 0);
5355            }
5356            if c == 0x20AC {
5357                if dst_left < 1 { return (0, E2BIG); }
5358                *dst = 128; return (1, 0);
5359            }
5360            for row in 0..126usize {
5361                for col in 0..190usize {
5362                    if GB18030_TABLE[row * 190 + col] as u32 == c {
5363                        if dst_left < 2 { return (0, E2BIG); }
5364                        *dst = (row + 0x81) as u8;
5365                        *dst.add(1) = if col <= 62 { (col + 0x40) as u8 } else { (col + 0x41) as u8 };
5366                        return (2, 0);
5367                    }
5368                }
5369            }
5370            (0, EILSEQ)
5371        }
5372        ENC_BIG5 => {
5373            if c < 128 {
5374                if dst_left < 1 { return (0, E2BIG); }
5375                *dst = c as u8; return (1, 0);
5376            }
5377            for row in 0..89usize {
5378                for col in 0..157usize {
5379                    if BIG5_TABLE[row * 157 + col] as u32 == c {
5380                        if dst_left < 2 { return (0, E2BIG); }
5381                        *dst = (row + 0xA1) as u8;
5382                        *dst.add(1) = if col <= 0x3E { (col + 0x40) as u8 } else { (col + 0x62) as u8 };
5383                        return (2, 0);
5384                    }
5385                }
5386            }
5387            (0, EILSEQ)
5388        }
5389        ENC_EUCJP => {
5390            if c < 128 {
5391                if dst_left < 1 { return (0, E2BIG); }
5392                *dst = c as u8; return (1, 0);
5393            }
5394            if c >= 0xFF61 && c <= 0xFF9F {
5395                if dst_left < 2 { return (0, E2BIG); }
5396                *dst = 0x8E;
5397                *dst.add(1) = (c - 0xFF61 + 0xA1) as u8;
5398                return (2, 0);
5399            }
5400            let jis = uni_to_jis(c);
5401            if jis == 0 { return (0, EILSEQ); }
5402            if dst_left < 2 { return (0, E2BIG); }
5403            *dst = ((jis >> 8) as u8).wrapping_add(0x80);
5404            *dst.add(1) = ((jis & 0xFF) as u8).wrapping_add(0x80);
5405            (2, 0)
5406        }
5407        ENC_SHIFTJIS => {
5408            if c < 128 {
5409                if dst_left < 1 { return (0, E2BIG); }
5410                *dst = c as u8; return (1, 0);
5411            }
5412            if c >= 0xFF61 && c <= 0xFF9F {
5413                if dst_left < 1 { return (0, E2BIG); }
5414                *dst = (c - 0xFF61 + 0xA1) as u8;
5415                return (1, 0);
5416            }
5417            let jis = uni_to_jis(c);
5418            if jis == 0 { return (0, EILSEQ); }
5419            if dst_left < 2 { return (0, E2BIG); }
5420            let r = (jis >> 8) as usize;
5421            let d = (jis & 0xFF) as usize;
5422            *dst = ((r + 1) / 2 + if r < 95 { 112 } else { 176 }) as u8;
5423            *dst.add(1) = if r % 2 == 1 { (d + 31 + d / 96) as u8 } else { (d + 126) as u8 };
5424            (2, 0)
5425        }
5426        _ => (0, EILSEQ),
5427    }
5428}
5429
5430#[no_mangle]
5431pub unsafe extern "C" fn iconv_open(tocode: *const c_char, fromcode: *const c_char) -> IconvT {
5432    let to = find_encoding(tocode as *const u8);
5433    let from = find_encoding(fromcode as *const u8);
5434    if to < 0 || from < 0 {
5435        ERRNO!() = EINVAL;
5436        return !0usize as IconvT;
5437    }
5438    make_cd(from, to)
5439}
5440
5441#[no_mangle]
5442pub unsafe extern "C" fn iconv(
5443    cd: IconvT,
5444    inbuf: *mut *mut c_char,
5445    inbytesleft: *mut SizeT,
5446    outbuf: *mut *mut c_char,
5447    outbytesleft: *mut SizeT,
5448) -> SizeT {
5449    if cd == !0usize as IconvT {
5450        ERRNO!() = EINVAL;
5451        return !0usize;
5452    }
5453    // A null inbuf is the state-reset call; all converters are stateless.
5454    if inbuf.is_null() { return 0; }
5455    if inbytesleft.is_null() || outbuf.is_null() || outbytesleft.is_null() {
5456        ERRNO!() = EINVAL;
5457        return !0usize;
5458    }
5459    let from = extract_from(cd);
5460    let to = extract_to(cd);
5461    let mut src = *inbuf as *const u8;
5462    let mut dst = *outbuf as *mut u8;
5463    let mut src_left = *inbytesleft;
5464    let mut dst_left = *outbytesleft;
5465    let mut subst = 0usize;
5466    while src_left > 0 {
5467        let (cp, consumed, err) = iconv_decode(from, src, src_left);
5468        if err != 0 {
5469            if err == EINVAL { break; }
5470            ERRNO!() = err;
5471            return !0usize;
5472        }
5473        let (written, err) = iconv_encode(to, cp, dst, dst_left);
5474        if err != 0 {
5475            if err == E2BIG {
5476                ERRNO!() = E2BIG;
5477                return !0usize;
5478            }
5479            if dst_left < 1 {
5480                ERRNO!() = E2BIG;
5481                return !0usize;
5482            }
5483            *dst = b'*';
5484            dst = dst.add(1);
5485            dst_left -= 1;
5486            subst += 1;
5487        } else {
5488            dst = dst.add(written);
5489            dst_left -= written;
5490        }
5491        src = src.add(consumed);
5492        src_left -= consumed;
5493    }
5494    *inbuf = src as *mut c_char;
5495    *outbuf = dst as *mut c_char;
5496    *inbytesleft = src_left;
5497    *outbytesleft = dst_left;
5498    subst
5499}
5500
5501#[no_mangle]
5502pub unsafe extern "C" fn iconv_close(_cd: IconvT) -> c_int { 0 }
5503
5504// ============================================================
5505// Syscall wrappers as public C ABI
5506// ============================================================
5507
5508#[no_mangle]
5509pub unsafe extern "C" fn write(fd: c_int, buf: *const c_void, count: SizeT) -> SSizeT {
5510    syscall_ret(sys_write(fd as i64, buf as *const u8, count)) as SSizeT
5511}
5512
5513#[no_mangle]
5514pub unsafe extern "C" fn read(fd: c_int, buf: *mut c_void, count: SizeT) -> SSizeT {
5515    syscall_ret(sys_read(fd as i64, buf as *mut u8, count)) as SSizeT
5516}
5517
5518#[no_mangle]
5519pub unsafe extern "C" fn open(path: *const c_char, flags: c_int, mode: c_int) -> c_int {
5520    syscall_ret(sys_open(path as *const u8, flags as i64, mode as i64)) as c_int
5521}
5522
5523#[no_mangle]
5524pub unsafe extern "C" fn close(fd: c_int) -> c_int {
5525    syscall_ret(sys_close(fd as i64)) as c_int
5526}
5527
5528#[no_mangle]
5529pub unsafe extern "C" fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64 {
5530    syscall_ret(sys_lseek(fd as i64, offset, whence as i64))
5531}
5532
5533// ============================================================
5534// Additional syscall wrappers for stdio
5535// ============================================================
5536
5537const O_RDONLY: i32 = 0;
5538const O_WRONLY: i32 = 1;
5539const O_RDWR: i32 = 2;
5540const O_CREAT: i32 = 64;
5541const O_TRUNC: i32 = 512;
5542const O_APPEND: i32 = 1024;
5543const O_EXCL: i32 = 128;
5544const O_NONBLOCK: i32 = 2048;
5545const O_NOFOLLOW: i32 = if cfg!(target_arch = "aarch64") { 0o100000 } else { 0o400000 };
5546const O_DIRECTORY: i32 = if cfg!(target_arch = "aarch64") { 0o40000 } else { 0o200000 };
5547const O_CLOEXEC: i32 = 0x80000;
5548
5549const F_GETFD: i32 = 1;
5550const F_SETFD: i32 = 2;
5551const F_GETFL: i32 = 3;
5552const F_SETFL: i32 = 4;
5553const F_GETLK: i32 = 5;
5554const F_SETLK: i32 = 6;
5555const F_SETLKW: i32 = 7;
5556const F_DUPFD: i32 = 0;
5557const F_DUPFD_CLOEXEC: i32 = 1030;
5558const FD_CLOEXEC: i32 = 1;
5559
5560const TIOCGWINSZ: u32 = 0x5413;
5561
5562#[repr(C)]
5563struct winsize {
5564    ws_row: u16,
5565    ws_col: u16,
5566    ws_xpixel: u16,
5567    ws_ypixel: u16,
5568}
5569
5570#[inline]
5571unsafe fn sys_pipe2(fds: *mut c_int, flags: i32) -> i64 {
5572    <Arch as Syscalls>::syscall2(SYS_PIPE2, fds as i64, flags as i64)
5573}
5574
5575#[inline]
5576unsafe fn sys_dup3(oldfd: i32, newfd: i32, flags: i32) -> i64 {
5577    <Arch as Syscalls>::syscall3(SYS_DUP3, oldfd as i64, newfd as i64, flags as i64)
5578}
5579
5580#[inline]
5581unsafe fn sys_fcntl(fd: i32, cmd: i32, arg: i64) -> i64 {
5582    <Arch as Syscalls>::syscall3(SYS_FCNTL, fd as i64, cmd as i64, arg as i64)
5583}
5584
5585#[inline]
5586unsafe fn sys_ioctl(fd: c_int, request: u32, arg: *mut u8) -> i64 {
5587    <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg as i64)
5588}
5589
5590#[inline]
5591unsafe fn sys_unlinkat(dirfd: i32, path: *const u8, flags: i32) -> i64 {
5592    <Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, path as i64, flags as i64)
5593}
5594
5595#[inline]
5596unsafe fn sys_renameat2(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: u32) -> i64 {
5597    <Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
5598}
5599
5600// ============================================================
5601// FILE / stdio (buffered, musl-compatible layout)
5602// ============================================================
5603
5604const UNGET: usize = 8;
5605const F_PERM: u32 = 1;
5606const F_NORD: u32 = 4;
5607const F_NOWR: u32 = 8;
5608const F_EOF: u32 = 16;
5609const F_ERR: u32 = 32;
5610const F_SVB: u32 = 64;
5611const F_APP: u32 = 128;
5612
5613const BUFSIZ: usize = 1024;
5614
5615const _IOFBF: c_int = 0;
5616const _IOLBF: c_int = 1;
5617const _IONBF: c_int = 2;
5618
5619const SEEK_SET: c_int = 0;
5620const SEEK_CUR: c_int = 1;
5621const SEEK_END: c_int = 2;
5622
5623// Buffered FILE using musl's 64-bit layout.
5624#[repr(C)]
5625pub struct FILE {
5626    flags: c_uint,
5627    rpos: *mut u8,
5628    rend: *mut u8,
5629    close: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
5630    wend: *mut u8,
5631    wpos: *mut u8,
5632    mustbezero_1: *mut u8,
5633    wbase: *mut u8,
5634    read_fn: Option<unsafe extern "C" fn(*mut FILE, *mut u8, usize) -> usize>,
5635    write_fn: Option<unsafe extern "C" fn(*mut FILE, *const u8, usize) -> usize>,
5636    seek_fn: Option<unsafe extern "C" fn(*mut FILE, i64, c_int) -> i64>,
5637    buf: *mut u8,
5638    buf_size: usize,
5639    prev: *mut FILE,
5640    next: *mut FILE,
5641    fd: c_int,
5642    pipe_pid: c_int,
5643    lockcount: c_long,
5644    mode: c_int,
5645    lock: c_int,
5646    lbf: c_int,
5647    cookie: *mut c_void,
5648    off: i64,
5649    getln_buf: *mut c_char,
5650    mustbezero_2: *mut c_void,
5651    shend: *mut u8,
5652    shlim: i64,
5653    shcnt: i64,
5654    ungotten: [c_int; UNGET],
5655    ungotten_count: c_int,
5656    _eof: c_int,
5657    _err: c_int,
5658}
5659
5660static mut STDIN_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5661static mut STDOUT_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5662static mut STDERR_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5663
5664static mut STDIN_FILE: FILE = FILE {
5665    flags: 0, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5666    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5667    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5668    read_fn: None, write_fn: None, seek_fn: None,
5669    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5670    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5671    fd: 0, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5672    cookie: core::ptr::null_mut(), off: 0,
5673    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5674    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5675    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5676};
5677static mut STDOUT_FILE: FILE = FILE {
5678    flags: F_NOWR as u32 + F_SVB as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5679    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5680    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5681    read_fn: None, write_fn: None, seek_fn: None,
5682    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5683    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5684    fd: 1, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5685    cookie: core::ptr::null_mut(), off: 0,
5686    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5687    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5688    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5689};
5690static mut STDERR_FILE: FILE = FILE {
5691    flags: F_NOWR as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5692    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5693    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5694    read_fn: None, write_fn: None, seek_fn: None,
5695    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5696    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5697    fd: 2, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5698    cookie: core::ptr::null_mut(), off: 0,
5699    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5700    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5701    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5702};
5703
5704#[no_mangle]
5705pub static mut stdin: *mut FILE = &raw mut STDIN_FILE as *mut FILE;
5706#[no_mangle]
5707pub static mut stdout: *mut FILE = &raw mut STDOUT_FILE as *mut FILE;
5708#[no_mangle]
5709pub static mut stderr: *mut FILE = &raw mut STDERR_FILE as *mut FILE;
5710
5711// All open streams, so fflush(NULL) can flush everything and fclose can
5712// unlink/free dynamically allocated FILEs.
5713static mut OFL_HEAD: *mut FILE = core::ptr::null_mut();
5714
5715unsafe fn ofl_add(f: *mut FILE) {
5716    (*f).prev = core::ptr::null_mut();
5717    (*f).next = OFL_HEAD;
5718    if !OFL_HEAD.is_null() {
5719        (*OFL_HEAD).prev = f;
5720    }
5721    OFL_HEAD = f;
5722}
5723
5724unsafe fn ofl_remove(f: *mut FILE) {
5725    let prev = (*f).prev;
5726    let next = (*f).next;
5727    if prev.is_null() {
5728        OFL_HEAD = next;
5729    } else {
5730        (*prev).next = next;
5731    }
5732    if !next.is_null() {
5733        (*next).prev = prev;
5734    }
5735    (*f).prev = core::ptr::null_mut();
5736    (*f).next = core::ptr::null_mut();
5737}
5738
5739// ============================================================
5740// FILE helpers
5741// ============================================================
5742
5743unsafe fn __stdio_init() {
5744    STDIN_FILE.buf = core::ptr::addr_of_mut!(STDIN_BUF) as *mut u8;
5745    STDIN_FILE.buf_size = BUFSIZ;
5746    STDIN_FILE.read_fn = Some(__stdio_read);
5747    STDIN_FILE.write_fn = Some(__stdio_write);
5748    STDIN_FILE.seek_fn = Some(__stdio_seek);
5749    STDOUT_FILE.buf = core::ptr::addr_of_mut!(STDOUT_BUF) as *mut u8;
5750    STDOUT_FILE.buf_size = BUFSIZ;
5751    STDOUT_FILE.lbf = b'\n' as c_int;
5752    STDOUT_FILE.read_fn = Some(__stdio_read);
5753    STDOUT_FILE.write_fn = Some(__stdio_write);
5754    STDOUT_FILE.seek_fn = Some(__stdio_seek);
5755    STDERR_FILE.buf = core::ptr::addr_of_mut!(STDERR_BUF) as *mut u8;
5756    STDERR_FILE.buf_size = BUFSIZ;
5757    STDERR_FILE.read_fn = Some(__stdio_read);
5758    STDERR_FILE.write_fn = Some(__stdio_write);
5759    STDERR_FILE.seek_fn = Some(__stdio_seek);
5760    STDIN_FILE.flags |= F_PERM;
5761    STDOUT_FILE.flags |= F_PERM;
5762    STDERR_FILE.flags |= F_PERM;
5763    STDIN_FILE.close = Some(__stdio_close);
5764    STDOUT_FILE.close = Some(__stdio_close);
5765    STDERR_FILE.close = Some(__stdio_close);
5766    ofl_add(&raw mut STDIN_FILE as *mut FILE);
5767    ofl_add(&raw mut STDOUT_FILE as *mut FILE);
5768    ofl_add(&raw mut STDERR_FILE as *mut FILE);
5769}
5770
5771unsafe fn buf_ptr(f: *mut FILE) -> *mut u8 {
5772    (f as *mut u8).add(core::mem::size_of::<FILE>())
5773}
5774
5775unsafe extern "C" fn __stdio_read(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
5776    let n = sys_read((*f).fd as i64, buf, len);
5777    if n <= 0 {
5778        if n == 0 { (*f).flags |= F_EOF; } else { (*f).flags |= F_ERR; (*f)._err = 1; }
5779        return 0;
5780    }
5781    n as usize
5782}
5783
5784unsafe extern "C" fn __stdio_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
5785    let l = (*f).wpos as usize - (*f).wbase as usize;
5786    let mut iov = [
5787        ((*f).wbase as *const u8, l),
5788        (buf, len),
5789    ];
5790    if iov[0].1 == 0 { iov = [iov[1], (core::ptr::null(), 0)]; }
5791    if (*f).flags & F_APP != 0 {
5792        let _ = sys_lseek((*f).fd as i64, 0, SEEK_END as i64);
5793    }
5794    let mut rem = iov[0].1 + iov[1].1;
5795    let mut idx = 0usize;
5796    while rem > 0 {
5797        let ptr = iov[idx].0;
5798        let cnt = iov[idx].1;
5799        if cnt == 0 { idx += 1; continue; }
5800        let n = sys_write((*f).fd as i64, ptr, cnt);
5801        if n <= 0 {
5802            (*f).wpos = core::ptr::null_mut();
5803            (*f).wbase = core::ptr::null_mut();
5804            (*f).wend = core::ptr::null_mut();
5805            (*f).flags |= F_ERR;
5806            return if iov[idx].0 == buf { 0 } else { len };
5807        }
5808        rem -= n as usize;
5809        iov[idx].0 = iov[idx].0.add(n as usize);
5810        iov[idx].1 -= n as usize;
5811        if iov[idx].1 == 0 { idx += 1; }
5812    }
5813    (*f).wend = (*f).buf.add((*f).buf_size);
5814    (*f).wbase = (*f).buf;
5815    (*f).wpos = (*f).buf;
5816    len
5817}
5818
5819unsafe extern "C" fn __stdio_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
5820    sys_lseek((*f).fd as i64, off, whence as i64)
5821}
5822
5823unsafe fn init_file(
5824    f: *mut FILE,
5825    fd: c_int,
5826    mode: *const c_char,
5827    close_fn: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
5828    buf_area: *mut u8,
5829    buf_sz: usize,
5830) {
5831    core::ptr::write_bytes(f as *mut u8, 0, core::mem::size_of::<FILE>());
5832    (*f).fd = fd;
5833    (*f).close = close_fn;
5834    (*f).lock = 0;
5835    (*f).lbf = -1;
5836    (*f).buf = buf_area;
5837    (*f).buf_size = buf_sz;
5838    (*f).read_fn = Some(__stdio_read);
5839    (*f).write_fn = Some(__stdio_write);
5840    (*f).seek_fn = Some(__stdio_seek);
5841    let m = *mode;
5842    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
5843    if m == b'r' as c_char && !has_plus {
5844        (*f).flags = F_NORD;
5845    } else if !has_plus {
5846        (*f).flags = F_NOWR;
5847    }
5848    ofl_add(f);
5849}
5850
5851unsafe extern "C" fn __stdio_close(f: *mut FILE) -> c_int {
5852    sys_close((*f).fd as i64);
5853    0
5854}
5855
5856unsafe fn fmodeflags(mode: *const c_char) -> c_int {
5857    let mut flags: c_int;
5858    let m = *mode;
5859    if !strchr(mode as *const u8, b'+' as c_int).is_null() {
5860        flags = O_RDWR;
5861    } else if m == b'r' as c_char {
5862        flags = O_RDONLY;
5863    } else {
5864        flags = O_WRONLY;
5865    }
5866    if !strchr(mode as *const u8, b'x' as c_int).is_null() { flags |= O_EXCL; }
5867    if !strchr(mode as *const u8, b'e' as c_int).is_null() { flags |= O_CLOEXEC; }
5868    if m != b'r' as c_char { flags |= O_CREAT; }
5869    if m == b'w' as c_char { flags |= O_TRUNC; }
5870    if m == b'a' as c_char { flags |= O_APPEND; }
5871    flags
5872}
5873
5874const O_ACCMODE: c_int = O_RDONLY | O_WRONLY | O_RDWR;
5875
5876unsafe fn flush_buf(f: *mut FILE) -> c_int {
5877    if (*f).wpos == (*f).wbase {
5878        if !(*f).wpos.is_null() {
5879            (*f).wend = (*f).buf.add((*f).buf_size);
5880            (*f).wpos = (*f).wbase;
5881        }
5882        return 0;
5883    }
5884    if let Some(wfunc) = (*f).write_fn {
5885        let ret = wfunc(f, core::ptr::null(), 0);
5886        if ret == 0 && (*f).wpos.is_null() { return -1; }
5887        return 0;
5888    }
5889    (*f).flags |= F_ERR;
5890    -1
5891}
5892
5893// ============================================================
5894// fopen / fdopen / freopen / fclose
5895// ============================================================
5896
5897#[no_mangle]
5898pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE {
5899    if filename.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
5900    let m = *mode;
5901    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
5902        ERRNO!() = EINVAL; return core::ptr::null_mut();
5903    }
5904    let flags = fmodeflags(mode);
5905    let fd = sys_open(filename as *const u8, flags as i64, 0o666);
5906    if fd < 0 { ERRNO!() = (-fd) as c_int; return core::ptr::null_mut(); }
5907    let f = fdopen(fd as c_int, mode);
5908    if f.is_null() {
5909        sys_close(fd);
5910    }
5911    f
5912}
5913
5914#[no_mangle]
5915pub unsafe extern "C" fn fdopen(fd: c_int, mode: *const c_char) -> *mut FILE {
5916    if fd < 0 || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
5917    let m = *mode;
5918    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
5919        ERRNO!() = EINVAL; return core::ptr::null_mut();
5920    }
5921    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
5922    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
5923    let buf = buf_ptr(f);
5924    init_file(f, fd, mode, Some(__stdio_close), buf, BUFSIZ);
5925    if !strchr(mode as *const u8, b'a' as c_int).is_null() { (*f).flags |= F_APP; }
5926    if !strchr(mode as *const u8, b'e' as c_int).is_null() { sys_fcntl(fd, F_SETFD, FD_CLOEXEC as i64); }
5927    if (*f).flags & F_NOWR == 0 {
5928        let mut ws: winsize = core::mem::zeroed();
5929        if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 {
5930            (*f).lbf = b'\n' as c_int;
5931        }
5932    }
5933    f
5934}
5935
5936#[no_mangle]
5937pub unsafe extern "C" fn freopen(
5938    filename: *const c_char, mode: *const c_char, f: *mut FILE,
5939) -> *mut FILE {
5940    fflush(f);
5941    if (*f).pipe_pid > 0 { let _ = __stdio_close(f); }
5942    if filename.is_null() {
5943        let m = *mode;
5944        if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
5945            ERRNO!() = EINVAL;
5946            return core::ptr::null_mut();
5947        }
5948        let flags = fmodeflags(mode);
5949        let mut fl = flags & !(O_CREAT | O_EXCL | O_CLOEXEC);
5950        if (*f).flags & F_APP != 0 { fl = (fl & !O_ACCMODE) | O_WRONLY | O_APPEND; }
5951        if sys_fcntl((*f).fd, F_SETFL, fl as i64) < 0 { return core::ptr::null_mut(); }
5952        let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
5953        if has_plus {
5954            (*f).flags &= !(F_NORD | F_NOWR);
5955        } else if *mode == b'r' as c_char {
5956            (*f).flags = ((*f).flags & !F_NOWR) | F_NORD;
5957        } else {
5958            (*f).flags = ((*f).flags & !F_NORD) | F_NOWR;
5959        }
5960        return f;
5961    }
5962    let new_f = fopen(filename, mode);
5963    if new_f.is_null() { let _ = __stdio_close(f); return core::ptr::null_mut(); }
5964    if (*new_f).fd == (*f).fd {
5965        (*new_f).fd = -1;
5966    } else {
5967        sys_dup3((*new_f).fd, (*f).fd, 0);
5968        let _ = __stdio_close(new_f);
5969    }
5970    (*f).flags = (*new_f).flags;
5971    (*f).rpos = core::ptr::null_mut();
5972    (*f).rend = core::ptr::null_mut();
5973    (*f).wpos = core::ptr::null_mut();
5974    (*f).wbase = core::ptr::null_mut();
5975    (*f).wend = core::ptr::null_mut();
5976    (*f).lbf = (*new_f).lbf;
5977    (*f).pipe_pid = 0;
5978    ofl_remove(new_f);
5979    free(new_f as *mut c_void);
5980    f
5981}
5982
5983#[no_mangle]
5984pub unsafe extern "C" fn fclose(f: *mut FILE) -> c_int {
5985    if f.is_null() {
5986        ERRNO!() = EINVAL;
5987        return -1;
5988    }
5989    let r = fflush(f);
5990    let close_r = if let Some(close_fn) = (*f).close { close_fn(f) } else { 0 };
5991    let permanent = (*f).flags & F_PERM != 0;
5992    let allocated_buf = if (*f).flags & F_SVB != 0 { (*f).buf } else { core::ptr::null_mut() };
5993    let getln = (*f).getln_buf;
5994    ofl_remove(f);
5995    if !permanent {
5996        if !allocated_buf.is_null() { free(allocated_buf as *mut c_void); }
5997        if !getln.is_null() { free(getln as *mut c_void); }
5998        free(f as *mut c_void);
5999    }
6000    if r != 0 || close_r != 0 { -1 } else { 0 }
6001}
6002
6003// ============================================================
6004// setvbuf / setbuf / setbuffer / fflush
6005// ============================================================
6006
6007#[no_mangle]
6008pub unsafe extern "C" fn setvbuf(f: *mut FILE, buf: *mut c_char, mode: c_int, size: usize) -> c_int {
6009    if f.is_null() || (mode != _IOFBF && mode != _IOLBF && mode != _IONBF) {
6010        ERRNO!() = EINVAL;
6011        return -1;
6012    }
6013    fflush(f);
6014    (*f).rpos = core::ptr::null_mut();
6015    (*f).rend = core::ptr::null_mut();
6016    (*f).wpos = core::ptr::null_mut();
6017    (*f).wbase = core::ptr::null_mut();
6018    (*f).wend = core::ptr::null_mut();
6019    if mode == _IONBF {
6020        (*f).buf = core::ptr::null_mut();
6021        (*f).buf_size = 0;
6022    } else {
6023        let wanted = if size == 0 { BUFSIZ } else { size };
6024        let actual = if buf.is_null() {
6025            let p = malloc(wanted) as *mut c_char;
6026            if p.is_null() {
6027                ERRNO!() = ENOMEM;
6028                return -1;
6029            }
6030            (*f).flags |= F_SVB;
6031            p
6032        } else {
6033            (*f).flags &= !F_SVB;
6034            buf
6035        };
6036        (*f).buf = actual as *mut u8;
6037        (*f).buf_size = wanted;
6038    }
6039    (*f).lbf = if mode == _IOLBF { b'\n' as c_int } else { -1 };
6040    0
6041}
6042
6043#[no_mangle]
6044pub unsafe extern "C" fn setbuf(f: *mut FILE, buf: *mut c_char) {
6045    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
6046    else { setvbuf(f, buf, _IOFBF, BUFSIZ); }
6047}
6048
6049#[no_mangle]
6050pub unsafe extern "C" fn setbuffer(f: *mut FILE, buf: *mut c_char, size: usize) {
6051    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
6052    else { setvbuf(f, buf, _IOFBF, size); }
6053}
6054
6055#[no_mangle]
6056pub unsafe extern "C" fn fflush(f: *mut FILE) -> c_int {
6057    if f.is_null() {
6058        let mut r = 0;
6059        let mut cur = OFL_HEAD;
6060        while !cur.is_null() {
6061            let next = (*cur).next;
6062            if !(*cur).wpos.is_null() && (*cur).wpos != (*cur).wbase {
6063                if flush_buf(cur) != 0 { r = -1; }
6064            }
6065            cur = next;
6066        }
6067        return r;
6068    }
6069    if !(*f).wpos.is_null() && (*f).wpos != (*f).wbase {
6070        return flush_buf(f);
6071    }
6072    0
6073}
6074
6075// ============================================================
6076// fwide / feof / ferror / clearerr / fileno
6077// ============================================================
6078
6079#[no_mangle]
6080pub unsafe extern "C" fn fwide(_f: *mut FILE, mode: c_int) -> c_int { mode }
6081
6082#[no_mangle]
6083pub unsafe extern "C" fn feof(f: *mut FILE) -> c_int { if (*f)._eof != 0 { 1 } else { 0 } }
6084
6085#[no_mangle]
6086pub unsafe extern "C" fn ferror(f: *mut FILE) -> c_int { if (*f)._err != 0 { 1 } else { 0 } }
6087
6088#[no_mangle]
6089pub unsafe extern "C" fn clearerr(f: *mut FILE) { (*f)._eof = 0; (*f)._err = 0; }
6090
6091#[no_mangle]
6092pub unsafe extern "C" fn fileno(f: *mut FILE) -> c_int { (*f).fd }
6093
6094// ============================================================
6095// fseek / ftell / rewind / fseeko / ftello / fgetpos / fsetpos
6096// ============================================================
6097
6098#[no_mangle]
6099pub unsafe extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int {
6100    fseeko(stream, offset as i64, whence)
6101}
6102
6103#[no_mangle]
6104pub unsafe extern "C" fn ftell(stream: *mut FILE) -> c_long {
6105    ftello(stream) as c_long
6106}
6107
6108#[no_mangle]
6109pub unsafe extern "C" fn rewind(stream: *mut FILE) {
6110    fseek(stream, 0, SEEK_SET);
6111    (*stream)._eof = 0;
6112    (*stream)._err = 0;
6113}
6114
6115#[no_mangle]
6116pub unsafe extern "C" fn fseeko(stream: *mut FILE, offset: i64, whence: c_int) -> c_int {
6117    if whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END {
6118        ERRNO!() = EINVAL;
6119        return -1;
6120    }
6121    let f = &mut *stream;
6122    let mut adj_offset = offset;
6123    if whence == SEEK_CUR {
6124        if !f.rpos.is_null() {
6125            let buffered = f.rend as i64 - f.rpos as i64;
6126            if adj_offset < i64::MIN + buffered {
6127                ERRNO!() = EOVERFLOW;
6128                return -1;
6129            }
6130            adj_offset -= buffered;
6131        }
6132        if adj_offset < i64::MIN + f.ungotten_count as i64 {
6133            ERRNO!() = EOVERFLOW;
6134            return -1;
6135        }
6136        adj_offset -= f.ungotten_count as i64;
6137    }
6138    if !f.wpos.is_null() && f.wpos != f.wbase {
6139        if flush_buf(stream) != 0 { return -1; }
6140    }
6141    f.wpos = core::ptr::null_mut();
6142    f.wbase = core::ptr::null_mut();
6143    f.wend = core::ptr::null_mut();
6144    if let Some(sfunc) = f.seek_fn {
6145        let r = sfunc(stream, adj_offset, whence);
6146        if r < 0 { return -1; }
6147    } else {
6148        ERRNO!() = EINVAL;
6149        return -1;
6150    }
6151    f.rpos = core::ptr::null_mut();
6152    f.rend = core::ptr::null_mut();
6153    f._eof = 0;
6154    f.ungotten_count = 0;
6155    0
6156}
6157
6158#[no_mangle]
6159pub unsafe extern "C" fn ftello(stream: *mut FILE) -> i64 {
6160    let f = &mut *stream;
6161    if f.flags & F_APP != 0 && !f.wpos.is_null() && f.wpos != f.wbase {
6162        if fflush(stream) != 0 { return -1; }
6163    }
6164    let sfunc = match f.seek_fn { Some(s) => s, None => return -1 };
6165    let pos = sfunc(stream, 0,
6166        if (f.flags & F_APP) != 0 && !f.wpos.is_null() && f.wpos != f.wbase { SEEK_END } else { SEEK_CUR });
6167    if pos < 0 { return -1; }
6168    let mut pos = pos;
6169    if !f.rpos.is_null() {
6170        pos += f.rpos as i64 - f.rend as i64;
6171    } else if !f.wbase.is_null() {
6172        let buffered = f.wpos as i64 - f.wbase as i64;
6173        if buffered > i64::MAX - pos {
6174            ERRNO!() = EOVERFLOW;
6175            return -1;
6176        }
6177        pos += buffered;
6178    }
6179    pos - f.ungotten_count as i64
6180}
6181
6182#[no_mangle]
6183pub unsafe extern "C" fn fgetpos(stream: *mut FILE, pos: *mut i64) -> c_int {
6184    let off = ftello(stream);
6185    if off < 0 { return -1; }
6186    *pos = off;
6187    0
6188}
6189
6190#[no_mangle]
6191pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const i64) -> c_int {
6192    fseeko(stream, *pos, SEEK_SET)
6193}
6194
6195// ============================================================
6196// fgetc / getc / getchar / ungetc
6197// ============================================================
6198
6199#[no_mangle]
6200pub unsafe extern "C" fn fgetc(stream: *mut FILE) -> c_int {
6201    let f = &mut *stream;
6202    if f.ungotten_count > 0 {
6203        f.ungotten_count -= 1;
6204        return f.ungotten[f.ungotten_count as usize];
6205    }
6206    if !f.rpos.is_null() && f.rpos < f.rend {
6207        let c = *f.rpos;
6208        f.rpos = f.rpos.add(1);
6209        return c as c_int;
6210    }
6211    if f._eof != 0 { return -1; }
6212    if let Some(rfunc) = f.read_fn {
6213        // Fill the stdio buffer in one read. Reading one byte per syscall is
6214        // not only slow, it is wrong for procfs files that only return their
6215        // contents on the first read: a second one-byte read sees EOF.
6216        if !f.buf.is_null() && f.buf_size > 1 {
6217            let n = rfunc(stream, f.buf, f.buf_size);
6218            if n == 0 {
6219                if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
6220                return -1;
6221            }
6222            f.rpos = f.buf;
6223            f.rend = f.buf.add(n);
6224            let c = *f.rpos;
6225            f.rpos = f.rpos.add(1);
6226            return c as c_int;
6227        }
6228        let mut buf = [0u8; 1];
6229        let n = rfunc(stream, buf.as_mut_ptr(), 1);
6230        if n == 0 {
6231            if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
6232            return -1;
6233        }
6234        buf[0] as c_int
6235    } else {
6236        f._eof = 1;
6237        -1
6238    }
6239}
6240
6241#[no_mangle]
6242pub unsafe extern "C" fn getc(stream: *mut FILE) -> c_int { fgetc(stream) }
6243
6244#[no_mangle]
6245pub unsafe extern "C" fn getchar() -> c_int { fgetc(stdin) }
6246
6247#[no_mangle]
6248pub unsafe extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int {
6249    if c == -1 { return -1; }
6250    let f = &mut *stream;
6251    if f.ungotten_count >= UNGET as c_int { return -1; }
6252    f.ungotten[f.ungotten_count as usize] = c;
6253    f.ungotten_count += 1;
6254    f._eof = 0;
6255    c
6256}
6257
6258// ============================================================
6259// fgets / fread
6260// ============================================================
6261
6262#[no_mangle]
6263pub unsafe extern "C" fn fgets(s: *mut c_char, n: c_int, stream: *mut FILE) -> *mut c_char {
6264    if n <= 0 { return null_mut(); }
6265    let max = (n - 1) as usize;
6266    let mut i = 0usize;
6267    while i < max {
6268        let c = fgetc(stream);
6269        if c == -1 { if i == 0 { return null_mut(); } break; }
6270        *s.add(i) = c as c_char;
6271        i += 1;
6272        if c == b'\n' as c_int { break; }
6273    }
6274    *s.add(i) = 0;
6275    s
6276}
6277
6278// gets() is inherently unsafe; kept for POSIX compatibility.
6279#[no_mangle]
6280pub unsafe extern "C" fn gets(s: *mut c_char) -> *mut c_char {
6281    let mut i = 0usize;
6282    loop {
6283        let c = fgetc(stdin);
6284        if c == -1 { if i == 0 { return null_mut(); } break; }
6285        if c == b'\n' as c_int { break; }
6286        *s.add(i) = c as c_char;
6287        i += 1;
6288    }
6289    *s.add(i) = 0;
6290    s
6291}
6292
6293#[no_mangle]
6294pub unsafe extern "C" fn fopen64(filename: *const c_char, mode: *const c_char) -> *mut FILE {
6295    fopen(filename, mode)
6296}
6297
6298// perror(): minimal implementation printing "msg: errno\n".
6299const PERROR_BUF_SIZE: usize = 64;
6300static mut PERROR_BUF: [u8; PERROR_BUF_SIZE] = [0; PERROR_BUF_SIZE];
6301
6302#[no_mangle]
6303pub unsafe extern "C" fn perror(msg: *const c_char) {
6304    let fd = (*stderr).fd;
6305    if !msg.is_null() && *msg != 0 {
6306        let len = strlen(msg as *const c_char);
6307        write_str(fd, msg as *const u8, len);
6308        write_str(fd, b": ".as_ptr(), 2);
6309    }
6310    let e = ERRNO!();
6311    let text = strerror(e) as *const u8;
6312    write_str(fd, text, strlen(text as *const c_char));
6313    write_str(fd, b"\n".as_ptr(), 1);
6314}
6315
6316#[no_mangle]
6317pub unsafe extern "C" fn fread(
6318    ptr: *mut c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
6319) -> SizeT {
6320    if size == 0 || nmemb == 0 { return 0; }
6321    let total = match size.checked_mul(nmemb) {
6322        Some(v) => v,
6323        None => { ERRNO!() = EINVAL; return 0; }
6324    };
6325    let mut rd = 0usize;
6326    while rd < total {
6327        let c = fgetc(stream);
6328        if c == -1 { break; }
6329        *(ptr as *mut u8).add(rd) = c as u8;
6330        rd += 1;
6331    }
6332    rd / size
6333}
6334
6335// ============================================================
6336// puts / fputs / fputc / putc / putchar / fwrite
6337// ============================================================
6338
6339unsafe fn write_str(fd: c_int, s: *const u8, len: usize) {
6340    let mut written = 0usize;
6341    while written < len {
6342        let n = sys_write(fd as i64, s.add(written), len - written);
6343        if n <= 0 { break; }
6344        written += n as usize;
6345    }
6346}
6347
6348#[no_mangle]
6349unsafe fn __overflow(f: *mut FILE, c: c_int) -> c_int {
6350    if (*f).wpos.is_null() {
6351        (*f).wbase = (*f).buf;
6352        (*f).wpos = (*f).buf;
6353        (*f).wend = (*f).buf.add((*f).buf_size);
6354    }
6355    if flush_buf(f) == -1 { return -1; }
6356    if (*f).wpos >= (*f).wend {
6357        if let Some(wfunc) = (*f).write_fn {
6358            let byte = c as u8;
6359            let ret = wfunc(f, &byte as *const u8, 1);
6360            if ret == 0 { return -1; }
6361        }
6362        return c;
6363    }
6364    *(*f).wpos = c as u8;
6365    (*f).wpos = (*f).wpos.add(1);
6366    if c == (*f).lbf || (*f).wpos >= (*f).wend { let _ = flush_buf(f); }
6367    c
6368}
6369
6370#[no_mangle]
6371pub unsafe extern "C" fn puts(s: *const c_char) -> c_int {
6372    let len = strlen(s as *const c_char);
6373    let _ = fwrite(s as *const c_void, 1, len, stdout);
6374    let _ = fwrite(b"\n".as_ptr() as *const c_void, 1, 1, stdout);
6375    let f = &mut *stdout;
6376    if f.lbf >= 0 { let _ = flush_buf(stdout); }
6377    (len + 1) as c_int
6378}
6379
6380#[no_mangle]
6381pub unsafe extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int {
6382    let len = strlen(s as *const c_char);
6383    fwrite(s as *const c_void, 1, len, stream) as c_int
6384}
6385
6386#[no_mangle]
6387pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int {
6388    let f = &mut *stream;
6389    if f.wpos.is_null() || f.wpos >= f.wend {
6390        if __overflow(f, c) == -1 { return -1; }
6391        return c;
6392    }
6393    *f.wpos = c as u8;
6394    f.wpos = f.wpos.add(1);
6395    if c == f.lbf || f.wpos >= f.wend { let _ = flush_buf(f); }
6396    c
6397}
6398
6399#[no_mangle]
6400pub unsafe extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int { fputc(c, stream) }
6401
6402#[no_mangle]
6403pub unsafe extern "C" fn putchar(c: c_int) -> c_int { fputc(c, stdout) }
6404
6405#[no_mangle]
6406pub unsafe extern "C" fn fwrite(
6407    ptr: *const c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
6408) -> SizeT {
6409    if size == 0 || nmemb == 0 { return 0; }
6410    let total = match size.checked_mul(nmemb) {
6411        Some(v) => v,
6412        None => { ERRNO!() = EINVAL; return 0; }
6413    };
6414    let f = &mut *stream;
6415    if f.buf_size == 0 {
6416        if let Some(wfunc) = f.write_fn {
6417            let ret = wfunc(stream, ptr as *const u8, total);
6418            if ret < total { f._err = 1; f.flags |= F_ERR; }
6419            return ret / size;
6420        }
6421        f._err = 1;
6422        f.flags |= F_ERR;
6423        return 0;
6424    }
6425    if f.wpos.is_null() {
6426        f.wbase = f.buf;
6427        f.wpos = f.buf;
6428        f.wend = f.buf.add(f.buf_size);
6429    }
6430    let mut remaining = total;
6431    let mut src = ptr as *const u8;
6432    while remaining > 0 {
6433        let space = f.wend as usize - f.wpos as usize;
6434        if space == 0 {
6435            if flush_buf(f as *mut FILE) == -1 { break; }
6436            continue;
6437        }
6438        let n = if remaining < space { remaining } else { space };
6439        core::ptr::copy_nonoverlapping(src, f.wpos, n);
6440        f.wpos = f.wpos.add(n);
6441        src = src.add(n);
6442        remaining -= n;
6443        if f.wpos >= f.wend { let _ = flush_buf(f as *mut FILE); }
6444    }
6445    if f.lbf >= 0 { let _ = flush_buf(f as *mut FILE); }
6446    (total - remaining) / size
6447}
6448
6449// ============================================================
6450// printf / fprintf / vprintf / vfprintf / dprintf / vdprintf
6451// ============================================================
6452
6453unsafe fn wide_to_mb(dst: *mut u8, cap: usize, src: *const wchar_t) -> usize {
6454    let mut o = 0usize;
6455    let mut i = 0usize;
6456    let mut st: c_uint = 0;
6457    while i < cap && *src.add(i) != 0 {
6458        let mut tmp = [0u8; 8];
6459        let n = wcrtomb(tmp.as_mut_ptr() as *mut c_char, *src.add(i), &mut st);
6460        if n == !0usize || n == 0 { break; }
6461        if o + n > cap { break; }
6462        core::ptr::copy_nonoverlapping(tmp.as_ptr(), dst.add(o), n);
6463        o += n;
6464        i += 1;
6465    }
6466    o
6467}
6468
6469const FMT_MAX_WIDTH: usize = 4096;
6470const FMT_MAX_PRECISION: i32 = 4096;
6471const FMT_MAX_INT_PRECISION: i32 = 1022;
6472const FMT_MAX_FLOAT_PRECISION: i32 = 1099;
6473const FMT_MAX_EG_PRECISION: i32 = 18;
6474const FMT_INT_BUF: usize = 4224;
6475
6476#[inline]
6477fn fmt_width(width: usize) -> usize {
6478    if width > FMT_MAX_WIDTH { FMT_MAX_WIDTH } else { width }
6479}
6480
6481#[inline]
6482fn fmt_precision(precision: i32) -> i32 {
6483    if precision > FMT_MAX_PRECISION { FMT_MAX_PRECISION } else { precision }
6484}
6485
6486#[inline]
6487fn fmt_star_width(width: c_int, flags: &mut u8) -> usize {
6488    if width < 0 {
6489        *flags |= FLAG_MINUS;
6490        fmt_width(width.unsigned_abs() as usize)
6491    } else {
6492        fmt_width(width as usize)
6493    }
6494}
6495
6496macro_rules! impl_format {
6497    ($fmt:expr, $args:expr, $write_char:expr, $write_str:expr) => {{
6498        let fmt = $fmt;
6499        let args = &mut $args;
6500        let mut count: usize = 0;
6501        let mut i = 0usize;
6502        loop {
6503            let c = *fmt.add(i) as u8;
6504            if c == 0 { break; }
6505            if c != b'%' {
6506                ($write_char)(c);
6507                count += 1; i += 1; continue;
6508            }
6509            i += 1;
6510            // Parse flags
6511            let mut flags: u8 = 0;
6512            loop {
6513                let fc = *fmt.add(i) as u8;
6514                match fc {
6515                    b'-' => { flags |= FLAG_MINUS; i += 1; }
6516                    b'+' => { flags |= FLAG_PLUS; i += 1; }
6517                    b' ' => { flags |= FLAG_SPACE; i += 1; }
6518                    b'0' => { flags |= FLAG_ZERO; i += 1; }
6519                    b'#' => { flags |= FLAG_HASH; i += 1; }
6520                    _ => break,
6521                }
6522            }
6523            // Parse width
6524            let mut width: usize = 0;
6525            if *fmt.add(i) as u8 == b'*' {
6526                width = fmt_star_width(args.next_arg::<c_int>(), &mut flags); i += 1;
6527            } else {
6528                while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
6529                    width = width.saturating_mul(10).saturating_add(((*fmt.add(i) as u8) - b'0') as usize); i += 1;
6530                }
6531            }
6532            width = fmt_width(width);
6533            // Parse precision
6534            let mut precision: i32 = -1;
6535            if *fmt.add(i) as u8 == b'.' {
6536                i += 1;
6537                if *fmt.add(i) as u8 == b'*' {
6538                    precision = args.next_arg::<c_int>(); i += 1;
6539                    if precision >= 0 { precision = fmt_precision(precision); }
6540                } else {
6541                    precision = 0;
6542                    while (*fmt.add(i) as u8) >= b'0' && (*fmt.add(i) as u8) <= b'9' {
6543                        precision = precision.saturating_mul(10).saturating_add(((*fmt.add(i) as u8) - b'0') as i32); i += 1;
6544                    }
6545                    precision = fmt_precision(precision);
6546                }
6547            }
6548            // Parse length modifier
6549            let len_mod = *fmt.add(i) as u8;
6550            let spec: u8;
6551            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' {
6552                i += 1;
6553                let len_mod2 = *fmt.add(i) as u8;
6554                if (len_mod == b'h' && len_mod2 == b'h') || (len_mod == b'l' && len_mod2 == b'l') {
6555                    i += 1;
6556                    spec = *fmt.add(i) as u8;
6557                    // Handle double-length modifiers
6558                    match (len_mod, len_mod2, spec) {
6559                        (b'h', b'h', b'n') => {
6560                            let p = args.next_arg::<*mut c_void>();
6561                            if !p.is_null() { *(p as *mut u8) = count as u8; }
6562                        }
6563                        (b'l', b'l', b'n') => {
6564                            let p = args.next_arg::<*mut c_void>();
6565                            if !p.is_null() { *(p as *mut c_longlong) = count as c_longlong; }
6566                        }
6567                        (b'h', b'h', b'd') | (b'h', b'h', b'i') => {
6568                            let val = args.next_arg::<c_int>() as i8 as c_int;
6569                            let neg = val < 0;
6570                            let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
6571                            let b = format_u64(abs);
6572                            let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6573                            let mut fbuf = [0u8; FMT_INT_BUF];
6574                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6575                            ($write_str)(fbuf.as_ptr(), len); count += len;
6576                        }
6577                        (b'h', b'h', b'u') => {
6578                            let val = args.next_arg::<c_uint>() as u8;
6579                            let b = format_u64(val as u64);
6580                            let mut fbuf = [0u8; FMT_INT_BUF];
6581                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6582                            ($write_str)(fbuf.as_ptr(), len); count += len;
6583                        }
6584                        (b'h', b'h', b'x') => {
6585                            let val = args.next_arg::<c_uint>() as u8;
6586                            let b = format_hex(val as u64, false);
6587                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6588                            let mut fbuf = [0u8; FMT_INT_BUF];
6589                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6590                            ($write_str)(fbuf.as_ptr(), len); count += len;
6591                        }
6592                        (b'h', b'h', b'X') => {
6593                            let val = args.next_arg::<c_uint>() as u8;
6594                            let b = format_hex(val as u64, true);
6595                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6596                            let mut fbuf = [0u8; FMT_INT_BUF];
6597                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6598                            ($write_str)(fbuf.as_ptr(), len); count += len;
6599                        }
6600                        (b'h', b'h', b'o') => {
6601                            let val = args.next_arg::<c_uint>() as u8;
6602                            let b = format_octal(val as u64, flags & FLAG_HASH != 0);
6603                            let mut fbuf = [0u8; FMT_INT_BUF];
6604                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6605                            ($write_str)(fbuf.as_ptr(), len); count += len;
6606                        }
6607                        (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
6608                            let val = args.next_arg::<c_longlong>();
6609                            let neg = val < 0;
6610                            let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
6611                            let b = format_u64(abs);
6612                            let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6613                            let mut fbuf = [0u8; FMT_INT_BUF];
6614                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6615                            ($write_str)(fbuf.as_ptr(), len); count += len;
6616                        }
6617                        (b'l', b'l', b'u') => {
6618                            let val = args.next_arg::<c_ulonglong>();
6619                            let b = format_u64(val as u64);
6620                            let mut fbuf = [0u8; FMT_INT_BUF];
6621                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6622                            ($write_str)(fbuf.as_ptr(), len); count += len;
6623                        }
6624                        (b'l', b'l', b'o') => {
6625                            let val = args.next_arg::<c_ulonglong>();
6626                            let b = format_octal(val as u64, flags & FLAG_HASH != 0);
6627                            let mut fbuf = [0u8; FMT_INT_BUF];
6628                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6629                            ($write_str)(fbuf.as_ptr(), len); count += len;
6630                        }
6631                        (b'l', b'l', b'x') => {
6632                            let val = args.next_arg::<c_ulonglong>();
6633                            let b = format_hex(val as u64, false);
6634                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6635                            let mut fbuf = [0u8; FMT_INT_BUF];
6636                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6637                            ($write_str)(fbuf.as_ptr(), len); count += len;
6638                        }
6639                        (b'l', b'l', b'X') => {
6640                            let val = args.next_arg::<c_ulonglong>();
6641                            let b = format_hex(val as u64, true);
6642                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6643                            let mut fbuf = [0u8; FMT_INT_BUF];
6644                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6645                            ($write_str)(fbuf.as_ptr(), len); count += len;
6646                        }
6647                        _ => { ($write_char)(b'%'); ($write_char)(len_mod); ($write_char)(len_mod2); ($write_char)(spec); count += 4; }
6648                    }
6649                } else {
6650                    spec = len_mod2;
6651                    // size_t/ptrdiff_t are 64-bit on all supported targets;
6652                    // treat %z/%t integer conversions like %l.
6653                    let lm = match len_mod {
6654                        b'z' | b't' if spec != b'n' => b'l',
6655                        // intmax_t is long on every target keel supports.
6656                        b'j' if spec != b'n' => b'l',
6657                        _ => len_mod,
6658                    };
6659                    match (lm, spec) {
6660                        (b'h', b'n') => {
6661                            let p = args.next_arg::<*mut c_void>();
6662                            if !p.is_null() { *(p as *mut u16) = count as u16; }
6663                        }
6664                        (b'l', b'n') => {
6665                            let p = args.next_arg::<*mut c_void>();
6666                            if !p.is_null() { *(p as *mut c_long) = count as c_long; }
6667                        }
6668                        (b'z', b'n') | (b't', b'n') => {
6669                            let p = args.next_arg::<*mut c_void>();
6670                            if !p.is_null() { *(p as *mut usize) = count; }
6671                        }
6672                        (b'j', b'n') => {
6673                            let p = args.next_arg::<*mut c_void>();
6674                            if !p.is_null() { *(p as *mut c_ulonglong) = count as c_ulonglong; }
6675                        }
6676                        (b'h', b'd') | (b'h', b'i') => {
6677                            let val = args.next_arg::<c_int>() as i16 as c_int;
6678                            let neg = val < 0;
6679                            let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
6680                            let b = format_u64(abs);
6681                            let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6682                            let mut fbuf = [0u8; FMT_INT_BUF];
6683                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6684                            ($write_str)(fbuf.as_ptr(), len); count += len;
6685                        }
6686                        (b'h', b'u') => {
6687                            let val = args.next_arg::<c_uint>() as u16;
6688                            let b = format_u64(val as u64);
6689                            let mut fbuf = [0u8; FMT_INT_BUF];
6690                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6691                            ($write_str)(fbuf.as_ptr(), len); count += len;
6692                        }
6693                        (b'h', b'x') => {
6694                            let val = args.next_arg::<c_uint>() as u16;
6695                            let b = format_hex(val as u64, false);
6696                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6697                            let mut fbuf = [0u8; FMT_INT_BUF];
6698                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6699                            ($write_str)(fbuf.as_ptr(), len); count += len;
6700                        }
6701                        (b'h', b'X') => {
6702                            let val = args.next_arg::<c_uint>() as u16;
6703                            let b = format_hex(val as u64, true);
6704                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6705                            let mut fbuf = [0u8; FMT_INT_BUF];
6706                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6707                            ($write_str)(fbuf.as_ptr(), len); count += len;
6708                        }
6709                        (b'h', b'o') => {
6710                            let val = args.next_arg::<c_uint>() as u16;
6711                            let b = format_octal(val as u64, flags & FLAG_HASH != 0);
6712                            let mut fbuf = [0u8; FMT_INT_BUF];
6713                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6714                            ($write_str)(fbuf.as_ptr(), len); count += len;
6715                        }
6716                        (b'l', b'd') | (b'l', b'i') => {
6717                            let val = args.next_arg::<c_long>();
6718                            let neg = val < 0;
6719                            let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
6720                            let b = format_u64(abs);
6721                            let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6722                            let mut fbuf = [0u8; FMT_INT_BUF];
6723                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6724                            ($write_str)(fbuf.as_ptr(), len); count += len;
6725                        }
6726                        (b'l', b'u') => {
6727                            let val = args.next_arg::<c_ulong>();
6728                            let b = format_u64(val as u64);
6729                            let mut fbuf = [0u8; FMT_INT_BUF];
6730                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6731                            ($write_str)(fbuf.as_ptr(), len); count += len;
6732                        }
6733                        (b'l', b's') => {
6734                            let p = args.next_arg::<*const wchar_t>();
6735                            if p.is_null() {
6736                                let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
6737                                let pad = width.saturating_sub(slen);
6738                                if flags & FLAG_MINUS != 0 { ($write_str)(b"(null)".as_ptr(), slen); for _ in 0..pad { ($write_char)(b' '); } }
6739                                else { for _ in 0..pad { ($write_char)(b' '); } ($write_str)(b"(null)".as_ptr(), slen); }
6740                                count += slen + pad;
6741                            } else {
6742                                let mut mb = [0u8; 4096];
6743                                let mut n = wide_to_mb(mb.as_mut_ptr(), mb.len(), p);
6744                                if precision >= 0 && (precision as usize) < n { n = precision as usize; }
6745                                let pad = width.saturating_sub(n);
6746                                if flags & FLAG_MINUS != 0 { ($write_str)(mb.as_ptr(), n); for _ in 0..pad { ($write_char)(b' '); } }
6747                                else { for _ in 0..pad { ($write_char)(b' '); } ($write_str)(mb.as_ptr(), n); }
6748                                count += n + pad;
6749                            }
6750                        }
6751                        (b'l', b'c') => {
6752                            let ch = args.next_arg::<c_int>();
6753                            let mut mb = [0u8; 8];
6754                            let mut st: c_uint = 0;
6755                            let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, ch, &mut st);
6756                            if n != !0usize {
6757                                let pad = width.saturating_sub(n);
6758                                if flags & FLAG_MINUS != 0 {
6759                                    ($write_str)(mb.as_ptr(), n);
6760                                    for _ in 0..pad { ($write_char)(b' '); }
6761                                } else {
6762                                    for _ in 0..pad { ($write_char)(b' '); }
6763                                    ($write_str)(mb.as_ptr(), n);
6764                                }
6765                                count += n + pad;
6766                            }
6767                        }
6768                        (b'l', b'x') => {
6769                            let val = args.next_arg::<c_ulong>();
6770                            let b = format_hex(val as u64, false);
6771                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6772                            let mut fbuf = [0u8; FMT_INT_BUF];
6773                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6774                            ($write_str)(fbuf.as_ptr(), len); count += len;
6775                        }
6776                        (b'l', b'X') => {
6777                            let val = args.next_arg::<c_ulong>();
6778                            let b = format_hex(val as u64, true);
6779                            let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6780                            let mut fbuf = [0u8; FMT_INT_BUF];
6781                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6782                            ($write_str)(fbuf.as_ptr(), len); count += len;
6783                        }
6784                        (b'l', b'o') => {
6785                            let val = args.next_arg::<c_ulong>();
6786                            let b = format_octal(val as u64, flags & FLAG_HASH != 0);
6787                            let mut fbuf = [0u8; FMT_INT_BUF];
6788                            let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6789                            ($write_str)(fbuf.as_ptr(), len); count += len;
6790                        }
6791                        (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
6792                        | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
6793                            let val = args.next_arg::<f64>();
6794                            let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6795                            let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6796                            let mut fbuf = [0u8; 4224];
6797                            let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6798                            let mut wbuf = [0u8; 4224];
6799                            let total = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
6800                            ($write_str)(wbuf.as_ptr(), total); count += total;
6801                        }
6802                        (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
6803                        | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
6804                            #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
6805                            let val = {
6806                                let lo: u64 = args.next_arg::<u64>();
6807                                let hi: u64 = args.next_arg::<u64>();
6808                                let combined: u128 = ((hi as u128) << 64) | (lo as u128);
6809                                f128::from_bits(combined) as f64
6810                            };
6811                            #[cfg(target_arch = "x86_64")]
6812                            let val = args.next_arg::<f64>();
6813                            let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6814                            let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6815                            let mut fbuf = [0u8; 4224];
6816                            let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6817                            let mut wbuf = [0u8; 4224];
6818                            let total = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
6819                            ($write_str)(wbuf.as_ptr(), total); count += total;
6820                        }
6821                        _ => { ($write_char)(b'%'); ($write_char)(len_mod); ($write_char)(spec); count += 3; }
6822                    }
6823                }
6824            } else {
6825                spec = *fmt.add(i) as u8;
6826                match spec {
6827                    b's' => {
6828                        let s = args.next_arg::<*const c_char>();
6829                        if s.is_null() {
6830                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
6831                            let padded_len = if width > slen { width } else { slen };
6832                            let pad = padded_len - slen;
6833                            if flags & FLAG_MINUS != 0 {
6834                                ($write_str)(b"(null)".as_ptr(), slen);
6835                                for _ in 0..pad { ($write_char)(b' '); }
6836                            } else {
6837                                for _ in 0..pad { ($write_char)(b' '); }
6838                                ($write_str)(b"(null)".as_ptr(), slen);
6839                            }
6840                            count += padded_len;
6841                        } else {
6842                            let full_len = strlen(s as *const c_char);
6843                            let slen = if precision >= 0 { (precision as usize).min(full_len) } else { full_len };
6844                            let padded_len = if width > slen { width } else { slen };
6845                            let pad = padded_len - slen;
6846                            if flags & FLAG_MINUS != 0 {
6847                                ($write_str)(s as *const u8, slen);
6848                                for _ in 0..pad { ($write_char)(b' '); }
6849                            } else {
6850                                for _ in 0..pad { ($write_char)(b' '); }
6851                                ($write_str)(s as *const u8, slen);
6852                            }
6853                            count += padded_len;
6854                        }
6855                    }
6856                    b'd' | b'i' => {
6857                        let d = args.next_arg::<c_int>();
6858                        let neg = d < 0;
6859                        let abs = if neg { d.wrapping_neg() as u64 } else { d as u64 };
6860                        let b = format_u64(abs);
6861                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
6862                        let mut fbuf = [0u8; FMT_INT_BUF];
6863                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
6864                        ($write_str)(fbuf.as_ptr(), len); count += len;
6865                    }
6866                    b'u' => {
6867                        let u = args.next_arg::<c_uint>();
6868                        let b = format_u64(u as u64);
6869                        let mut fbuf = [0u8; FMT_INT_BUF];
6870                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
6871                        ($write_str)(fbuf.as_ptr(), len); count += len;
6872                    }
6873                    b'x' => {
6874                        let x = args.next_arg::<c_uint>();
6875                        let b = format_hex(x as u64, false);
6876                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
6877                        let mut fbuf = [0u8; FMT_INT_BUF];
6878                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6879                        ($write_str)(fbuf.as_ptr(), len); count += len;
6880                    }
6881                    b'X' => {
6882                        let x = args.next_arg::<c_uint>();
6883                        let b = format_hex(x as u64, true);
6884                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
6885                        let mut fbuf = [0u8; FMT_INT_BUF];
6886                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
6887                        ($write_str)(fbuf.as_ptr(), len); count += len;
6888                    }
6889                    b'o' => {
6890                        let o = args.next_arg::<c_uint>();
6891                        let b = format_octal(o as u64, flags & FLAG_HASH != 0);
6892                        let mut fbuf = [0u8; FMT_INT_BUF];
6893                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
6894                        ($write_str)(fbuf.as_ptr(), len); count += len;
6895                    }
6896                    b'c' => {
6897                        let ch = args.next_arg::<c_int>();
6898                        if width > 1 {
6899                            let pad = width - 1;
6900                            if flags & FLAG_MINUS != 0 {
6901                                ($write_char)(ch as u8); count += 1;
6902                                for _ in 0..pad { ($write_char)(b' '); count += 1; }
6903                            } else {
6904                                for _ in 0..pad { ($write_char)(b' '); count += 1; }
6905                                ($write_char)(ch as u8); count += 1;
6906                            }
6907                        } else {
6908                            ($write_char)(ch as u8); count += 1;
6909                        }
6910                    }
6911                    b'p' => {
6912                        let p = args.next_arg::<*const c_void>();
6913                        let mut fbuf = [0u8; 20];
6914                        fbuf[0] = b'0'; fbuf[1] = b'x';
6915                        let b = format_hex(p as u64, false);
6916                        core::ptr::copy_nonoverlapping(b.0.as_ptr(), fbuf.as_mut_ptr().add(2), b.1);
6917                        ($write_str)(fbuf.as_ptr(), b.1 + 2); count += b.1 + 2;
6918                    }
6919                    b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
6920                        let val = args.next_arg::<f64>();
6921                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
6922                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
6923                        let mut fbuf = [0u8; 4224];
6924                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
6925                        let mut wbuf = [0u8; 4224];
6926                        let total = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
6927                        ($write_str)(wbuf.as_ptr(), total); count += total;
6928                    }
6929                    b'%' => { ($write_char)(b'%'); count += 1; }
6930                    b'n' => {
6931                        let p = args.next_arg::<*mut c_void>();
6932                        if !p.is_null() { *(p as *mut c_int) = count as c_int; }
6933                    }
6934                    _ => { ($write_char)(b'%'); ($write_char)(spec); count += 2; }
6935                }
6936            }
6937            i += 1;
6938        }
6939        count as c_int
6940    }};
6941}
6942
6943unsafe fn format_u64(mut val: u64) -> ([u8; 20], usize) {
6944    let mut buf = [0u8; 20];
6945    if val == 0 { buf[0] = b'0'; return (buf, 1); }
6946    let mut tmp = [0u8; 20];
6947    let mut pos = 20;
6948    while val > 0 { pos -= 1; tmp[pos] = b'0' + (val % 10) as u8; val /= 10; }
6949    let len = 20 - pos;
6950    core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6951    (buf, len)
6952}
6953
6954
6955unsafe fn format_hex(mut val: u64, uppercase: bool) -> ([u8; 16], usize) {
6956    let digits = if uppercase { b"0123456789ABCDEF" } else { b"0123456789abcdef" };
6957    let mut buf = [0u8; 16];
6958    if val == 0 { buf[0] = b'0'; return (buf, 1); }
6959    let mut tmp = [0u8; 16];
6960    let mut pos = 16;
6961    while val > 0 { pos -= 1; tmp[pos] = digits[(val & 0xf) as usize]; val >>= 4; }
6962    let len = 16 - pos;
6963    core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6964    (buf, len)
6965}
6966
6967unsafe fn format_octal(mut val: u64, alt: bool) -> ([u8; 24], usize) {
6968    let mut buf = [0u8; 24];
6969    if val == 0 {
6970        buf[0] = b'0';
6971        return (buf, 1);
6972    }
6973    let mut tmp = [0u8; 24];
6974    let mut pos = 24;
6975    while val > 0 {
6976        pos -= 1;
6977        tmp[pos] = b'0' + (val & 7) as u8;
6978        val >>= 3;
6979    }
6980    let len = 24 - pos;
6981    if alt {
6982        tmp[pos - 1] = b'0';
6983        core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos - 1), buf.as_mut_ptr(), len + 1);
6984        (buf, len + 1)
6985    } else {
6986        core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
6987        (buf, len)
6988    }
6989}
6990
6991unsafe fn format_int(
6992    dst: *mut u8,
6993    digits: *const u8,
6994    digits_len: usize,
6995    sign: Option<u8>,
6996    prefix: Option<u8>,
6997    precision: i32,
6998    width: usize,
6999    flags: u8,
7000    octal_alt: bool,
7001) -> usize {
7002    let precision = if precision > FMT_MAX_INT_PRECISION { FMT_MAX_INT_PRECISION } else { precision };
7003    let num_digits = if precision == 0 && digits_len == 1 && *digits == b'0' && !octal_alt {
7004        0
7005    } else {
7006        digits_len
7007    };
7008    let prec = precision as usize;
7009    let zero_pad = if precision >= 0 && prec > num_digits { prec - num_digits } else { 0 };
7010
7011    let sign_len = sign.map_or(0, |_| 1);
7012    let prefix_len = prefix.map_or(0, |_| 2);
7013    let content_len = sign_len + prefix_len + zero_pad + num_digits;
7014
7015    let mut buf = [0u8; FMT_INT_BUF];
7016    let mut pos = 0usize;
7017    if let Some(c) = sign { buf[pos] = c; pos += 1; }
7018    if let Some(c) = prefix { buf[pos] = b'0'; pos += 1; buf[pos] = c; pos += 1; }
7019    for _ in 0..zero_pad { buf[pos] = b'0'; pos += 1; }
7020    if num_digits > 0 {
7021        core::ptr::copy_nonoverlapping(digits, buf.as_mut_ptr().add(pos), num_digits);
7022    }
7023
7024    if content_len >= width {
7025        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, content_len);
7026        return content_len;
7027    }
7028    let pad = width - content_len;
7029    if flags & FLAG_MINUS != 0 {
7030        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, content_len);
7031        for i in 0..pad { *dst.add(content_len + i) = b' '; }
7032    } else if flags & FLAG_ZERO != 0 && precision < 0 {
7033        let fixed = sign_len + prefix_len;
7034        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, fixed);
7035        for i in fixed..width - num_digits { *dst.add(i) = b'0'; }
7036        if num_digits > 0 {
7037            core::ptr::copy_nonoverlapping(digits, dst.add(width - num_digits), num_digits);
7038        }
7039    } else {
7040        for i in 0..pad { *dst.add(i) = b' '; }
7041        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst.add(pad), content_len);
7042    }
7043    width
7044}
7045
7046
7047// Float format specifier type
7048const FMT_F: u8 = 0;
7049const FMT_E: u8 = 1;
7050const FMT_G: u8 = 2;
7051const FMT_A: u8 = 3;
7052
7053const FLAG_HASH: u8 = 1;
7054const FLAG_PLUS: u8 = 2;
7055const FLAG_SPACE: u8 = 4;
7056const FLAG_ZERO: u8 = 8;
7057const FLAG_MINUS: u8 = 16;
7058
7059// === %f formatting helpers ===
7060
7061/// Convert (mant << shift) to decimal string. Returns byte count written to buf.
7062/// mant is a 53-bit significand, shift is the left-shift amount (can be 0..~971).
7063unsafe fn bigint_to_decimal(buf: *mut u8, mant: u64, shift: u32) -> usize {
7064    // Store as little-endian u32 limbs. Max bits: 53 + 971 ≈ 1024 → 32 limbs.
7065    let nlimbs = (2 + (shift + 31) / 32) as usize;
7066    let mut limbs = [0u32; 36];
7067    limbs[0] = mant as u32;
7068    limbs[1] = (mant >> 32) as u32;
7069
7070    let ws = (shift / 32) as usize;
7071    let bs = shift % 32;
7072
7073    // Word-level shift left
7074    if ws > 0 {
7075        let mut i = 1usize;
7076        loop {
7077            limbs[i + ws] = limbs[i];
7078            if i == 0 { break; }
7079            i -= 1;
7080        }
7081        for j in 0..ws { limbs[j] = 0; }
7082    }
7083    // Bit-level shift left
7084    if bs > 0 {
7085        let mut carry = 0u32;
7086        let end = nlimbs.min(ws + 3);
7087        for i in ws..end {
7088            let new_val = (limbs[i] << bs) | carry;
7089            carry = limbs[i] >> (32 - bs);
7090            limbs[i] = new_val;
7091        }
7092    }
7093
7094    // Find highest non-zero limb
7095    let mut used = nlimbs;
7096    while used > 0 && limbs[used - 1] == 0 { used -= 1; }
7097    if used == 0 { *buf = b'0'; return 1; }
7098
7099    // Repeated division by 10 to extract decimal digits
7100    let mut digits = [0u8; 400];
7101    let mut nd = 0usize;
7102    loop {
7103        let mut all_zero = true;
7104        for i in 0..used { if limbs[i] != 0 { all_zero = false; break; } }
7105        if all_zero { break; }
7106        let mut rem = 0u64;
7107        for i in (0..used).rev() {
7108            let val = (rem << 32) | limbs[i] as u64;
7109            limbs[i] = (val / 10) as u32;
7110            rem = val % 10;
7111        }
7112        digits[nd] = rem as u8;
7113        nd += 1;
7114    }
7115    // Write digits in big-endian order
7116    for i in 0..nd { *buf.add(i) = b'0' + digits[nd - 1 - i]; }
7117    nd
7118}
7119
7120/// Compute `count` fractional digits of frac_bits / 2^shift using u128 arithmetic.
7121/// shift must be <= 124. Returns true if any value remains after the last digit.
7122unsafe fn frac_digits_u128(buf: *mut u8, frac_bits: u64, shift: u32, count: usize) -> bool {
7123    let mask: u128 = (1u128 << shift) - 1;
7124    let mut rem = frac_bits as u128;
7125    for i in 0..count {
7126        rem *= 10;
7127        let digit = (rem >> shift) as u8;
7128        rem &= mask;
7129        *buf.add(i) = digit;
7130    }
7131    rem != 0
7132}
7133
7134/// Compute `count` fractional digits of frac_bits / 2^shift using big-integer arithmetic.
7135/// For shift > 124 (up to ~1074). Returns true if any value remains after the last digit.
7136unsafe fn frac_digits_bigint(buf: *mut u8, frac_bits: u64, shift: u32, count: usize) -> bool {
7137    let nlimbs = ((shift + 31) / 32) as usize;
7138    let mut rem = [0u32; 36]; // enough for shift up to 1088
7139    rem[0] = frac_bits as u32;
7140    if nlimbs > 1 { rem[1] = (frac_bits >> 32) as u32; }
7141    // Mask to exactly `shift` bits
7142    let hi_word = (shift / 32) as usize;
7143    let hi_bit = shift % 32;
7144    if hi_bit > 0 && hi_word < nlimbs {
7145        rem[hi_word] &= (1u32 << hi_bit) - 1;
7146    }
7147    // Zero upper limbs beyond shift
7148    let clear_from = if hi_bit > 0 { hi_word + 1 } else { hi_word };
7149    for j in clear_from..nlimbs { rem[j] = 0; }
7150
7151    for i in 0..count {
7152        // Multiply remainder by 10
7153        let mut carry = 0u64;
7154        for j in 0..nlimbs {
7155            let val = rem[j] as u64 * 10 + carry;
7156            rem[j] = val as u32;
7157            carry = val >> 32;
7158        }
7159        // Extract digit from bit position `shift`
7160        let digit: u32;
7161        if hi_bit == 0 {
7162            digit = if hi_word < nlimbs { rem[hi_word] } else { carry as u32 };
7163        } else {
7164            let mut d = if hi_word < nlimbs { rem[hi_word] >> hi_bit } else { 0 };
7165            if hi_word + 1 < nlimbs {
7166                d |= rem[hi_word + 1] << (32 - hi_bit);
7167            } else if carry > 0 {
7168                d |= (carry as u32) << (32 - hi_bit);
7169            }
7170            digit = d;
7171        }
7172        *buf.add(i) = digit.min(9) as u8;
7173        // Clear bits from position `shift` upward (keep remainder < 2^shift)
7174        if hi_bit == 0 {
7175            if hi_word < nlimbs { rem[hi_word] = 0; }
7176        } else {
7177            if hi_word < nlimbs {
7178                rem[hi_word] &= (1u32 << hi_bit) - 1;
7179            }
7180            for j in (hi_word + 1)..nlimbs { rem[j] = 0; }
7181        }
7182    }
7183    // Check if remainder is non-zero
7184    for i in 0..nlimbs { if rem[i] != 0 { return true; } }
7185    false
7186}
7187
7188/// Increment a decimal string stored at buf[0..*len] in-place.
7189unsafe fn increment_decimal(buf: *mut u8, len: &mut usize) {
7190    let mut j = *len;
7191    loop {
7192        if j == 0 {
7193            // Shift right and prepend '1'
7194            let l = *len;
7195            for i in (0..l).rev() { *buf.add(i + 1) = *buf.add(i); }
7196            *buf = b'1';
7197            *len = l + 1;
7198            return;
7199        }
7200        j -= 1;
7201        let d = *buf.add(j);
7202        if d < b'9' { *buf.add(j) = d + 1; return; }
7203        *buf.add(j) = b'0';
7204    }
7205}
7206
7207// Write float to dst. Returns bytes written. Does NOT handle width/flags padding.
7208unsafe fn format_f64_full(
7209    dst: *mut u8, val: f64, fmt_type: u8, precision: i32, flags: u8, uppercase: bool,
7210) -> usize {
7211    let precision = match fmt_type {
7212        FMT_E | FMT_G => precision.min(FMT_MAX_EG_PRECISION),
7213        _ => precision.min(FMT_MAX_FLOAT_PRECISION),
7214    };
7215    let mut pos = 0usize;
7216
7217    // NaN
7218    if val.is_nan() {
7219        let nan_s: &[u8] = if uppercase { b"NAN" } else { b"nan" };
7220        core::ptr::copy_nonoverlapping(nan_s.as_ptr(), dst, 3);
7221        return 3;
7222    }
7223    let neg = val.is_sign_negative();
7224    let v = if neg { -val } else { val };
7225
7226    // Inf
7227    if v.is_infinite() {
7228        if neg { *dst.add(pos) = b'-'; pos += 1; }
7229        else if flags & FLAG_PLUS != 0 { *dst.add(pos) = b'+'; pos += 1; }
7230        else if flags & FLAG_SPACE != 0 { *dst.add(pos) = b' '; pos += 1; }
7231        let inf_s: &[u8] = if uppercase { b"INF" } else { b"inf" };
7232        core::ptr::copy_nonoverlapping(inf_s.as_ptr(), dst.add(pos), 3);
7233        return pos + 3;
7234    }
7235
7236    // Sign
7237    if neg { *dst.add(pos) = b'-'; pos += 1; }
7238    else if flags & FLAG_PLUS != 0 { *dst.add(pos) = b'+'; pos += 1; }
7239    else if flags & FLAG_SPACE != 0 { *dst.add(pos) = b' '; pos += 1; }
7240
7241    // === Hex float ===
7242    if fmt_type == FMT_A {
7243        return pos + fmt_hex_float(dst.add(pos), val, precision, flags, uppercase);
7244    }
7245
7246    // === Decimal formats ===
7247    let p: usize;
7248    let mut exp: i32;
7249    let use_f: bool;
7250
7251    match fmt_type {
7252        FMT_G => {
7253            let gp = if precision < 0 { 6usize } else if precision == 0 { 1usize } else { precision as usize };
7254            exp = if v > 0.0 { compute_exp10(v) } else { 0 };
7255            use_f = exp >= -4 && exp < gp as i32;
7256            if use_f {
7257                p = if exp < 0 { gp + ((-exp) as usize - 1) }
7258                    else if (exp as usize) < gp { gp - exp as usize - 1 }
7259                    else { 0 };
7260            } else {
7261                p = gp - 1;
7262            }
7263        }
7264        FMT_E => {
7265            p = if precision < 0 { 6usize } else { precision as usize };
7266            exp = if v > 0.0 { compute_exp10(v) } else { 0 };
7267            use_f = false;
7268        }
7269        _ => {
7270            p = if precision < 0 { 6usize } else { precision as usize };
7271            exp = 0;
7272            use_f = true;
7273        }
7274    }
7275
7276    if v == 0.0 {
7277        *dst.add(pos) = b'0'; pos += 1;
7278        if !(fmt_type == FMT_G && flags & FLAG_HASH == 0) {
7279            if p > 0 || flags & FLAG_HASH != 0 {
7280                *dst.add(pos) = b'.'; pos += 1;
7281                for _ in 0..p { *dst.add(pos) = b'0'; pos += 1; }
7282            }
7283        }
7284        if !use_f {
7285            let ec = if uppercase { b'E' } else { b'e' };
7286            *dst.add(pos) = ec; pos += 1;
7287            *dst.add(pos) = b'+'; pos += 1;
7288            *dst.add(pos) = b'0'; pos += 1;
7289            *dst.add(pos) = b'0'; pos += 1;
7290        }
7291        return pos;
7292    }
7293
7294    // === %f format: exact bit-based arithmetic, returns early ===
7295    if use_f {
7296        let bits = v.to_bits();
7297        let raw_mant = bits & 0x000FFFFFFFFFFFFF;
7298        let raw_exp_bits = ((bits >> 52) & 0x7FF) as i32;
7299        let (mant_b, bin_exp) = if raw_exp_bits == 0 {
7300            (raw_mant, -1022i32)
7301        } else {
7302            (raw_mant | (1u64 << 52), raw_exp_bits - 1023)
7303        };
7304
7305        // Integer part as decimal string
7306        let mut ibuf = [0u8; 400];
7307        let mut ilen: usize;
7308        if bin_exp < 0 {
7309            ibuf[0] = b'0'; ilen = 1;
7310        } else if bin_exp <= 63 {
7311            let int_val = if bin_exp <= 52 { mant_b >> (52 - bin_exp) }
7312                          else { mant_b << (bin_exp - 52) };
7313            let (buf2, len2) = format_u64(int_val);
7314            ibuf[..len2].copy_from_slice(&buf2[..len2]);
7315            ilen = len2;
7316        } else {
7317            ilen = bigint_to_decimal(ibuf.as_mut_ptr(), mant_b, (bin_exp - 52) as u32);
7318        }
7319
7320        // Fractional digits
7321        let mut fbuf = [0u8; 1100];
7322        let mut has_rest = false;
7323        if p > 0 && bin_exp < 52 {
7324            let shift = (52 - bin_exp) as u32;
7325            let frac_bits = if bin_exp >= 0 { mant_b & ((1u64 << shift) - 1) } else { mant_b };
7326            if shift <= 124 {
7327                has_rest = frac_digits_u128(fbuf.as_mut_ptr(), frac_bits, shift, p + 1);
7328            } else {
7329                has_rest = frac_digits_bigint(fbuf.as_mut_ptr(), frac_bits, shift, p + 1);
7330            }
7331        }
7332
7333        // Rounding
7334        if p > 0 && bin_exp < 52 {
7335            let next_d = fbuf[p];
7336            let last_d = fbuf[p - 1];
7337            if next_d > 5 || (next_d == 5 && (has_rest || last_d & 1 != 0)) {
7338                let mut carry = true;
7339                for j in (0..p).rev() {
7340                    if !carry { break; }
7341                    fbuf[j] += 1;
7342                    if fbuf[j] < 10 { carry = false; break; }
7343                    fbuf[j] = 0;
7344                }
7345                if carry { increment_decimal(ibuf.as_mut_ptr(), &mut ilen); }
7346            }
7347        } else if p == 0 {
7348            // %.0f: round integer based on fractional part
7349            if bin_exp >= 0 && bin_exp < 52 {
7350                let shift = (52 - bin_exp) as u32;
7351                let frac_bits = mant_b & ((1u64 << shift) - 1);
7352                let half = 1u64 << (shift - 1);
7353                let last_d = ibuf[ilen - 1] - b'0';
7354                if frac_bits > half || (frac_bits == half && last_d & 1 != 0) {
7355                    increment_decimal(ibuf.as_mut_ptr(), &mut ilen);
7356                }
7357            }
7358        }
7359
7360        // Output
7361        core::ptr::copy_nonoverlapping(ibuf.as_ptr(), dst.add(pos), ilen);
7362        pos += ilen;
7363        if p > 0 || flags & FLAG_HASH != 0 {
7364            *dst.add(pos) = b'.'; pos += 1;
7365            for i in 0..p { *dst.add(pos) = b'0' + fbuf[i]; pos += 1; }
7366        }
7367        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7368            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7369            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7370        }
7371        return pos;
7372    }
7373
7374    // === %e/%g format: exact big-integer digit extraction ===
7375    // D = floor(v * 10^(p+1-exp)), using v = mant_b * 2^(bin_exp-52)
7376    let mut fbuf = [0u8; 20];
7377    let mut int_part: u64;
7378    {
7379        let bits_v = v.to_bits();
7380        let raw_mant_v = bits_v & 0x000FFFFFFFFFFFFF;
7381        let raw_exp_v = ((bits_v >> 52) & 0x7FF) as i32;
7382        let (mant_b_v, bin_exp_v) = if raw_exp_v == 0 {
7383            (raw_mant_v, -1022i32)
7384        } else {
7385            (raw_mant_v | (1u64 << 52), raw_exp_v - 1023)
7386        };
7387
7388        let s: i32 = (p as i32) + 1 - exp;
7389        let bs: i32 = bin_exp_v - 52 + s;
7390
7391        let mut limbs = [0u32; 40];
7392        limbs[0] = mant_b_v as u32;
7393        limbs[1] = (mant_b_v >> 32) as u32;
7394        let mut nlimbs: usize = if limbs[1] != 0 { 2 } else { 1 };
7395
7396        if s > 0 {
7397            for _ in 0..(s as usize) {
7398                let mut carry = 0u64;
7399                for j in 0..nlimbs {
7400                    let val = limbs[j] as u64 * 5 + carry;
7401                    limbs[j] = val as u32;
7402                    carry = val >> 32;
7403                }
7404                if carry > 0 { limbs[nlimbs] = carry as u32; nlimbs += 1; }
7405            }
7406        }
7407
7408        if bs > 0 {
7409            let ws = (bs as u32 / 32) as usize;
7410            let bit = bs as u32 % 32;
7411            if ws > 0 {
7412                let mut i = nlimbs;
7413                while i > 0 { i -= 1; if i + ws < 40 { limbs[i + ws] = limbs[i]; } limbs[i] = 0; }
7414                nlimbs += ws;
7415            }
7416            if bit > 0 {
7417                let mut carry = 0u32;
7418                for i in ws..nlimbs {
7419                    let new_val = (limbs[i] << bit) | carry;
7420                    carry = limbs[i] >> (32 - bit);
7421                    limbs[i] = new_val;
7422                }
7423                if carry > 0 && nlimbs < 40 { limbs[nlimbs] = carry; nlimbs += 1; }
7424            }
7425        }
7426
7427        let mut has_rest = false;
7428        if s < 0 {
7429            for _ in 0..(-s as usize) {
7430                let mut rem = 0u64;
7431                for i in (0..nlimbs).rev() {
7432                    let val = (rem << 32) | limbs[i] as u64;
7433                    limbs[i] = (val / 5) as u32;
7434                    rem = val % 5;
7435                }
7436                if rem != 0 { has_rest = true; }
7437            }
7438        }
7439
7440        if bs < 0 {
7441            let rshift = (-bs) as u32;
7442            let ws = (rshift / 32) as usize;
7443            let bit = rshift % 32;
7444            if ws > 0 {
7445                for j in 0..ws.min(nlimbs) { if limbs[j] != 0 { has_rest = true; } }
7446                for i in ws..nlimbs { limbs[i - ws] = limbs[i]; }
7447                nlimbs = nlimbs.saturating_sub(ws);
7448            }
7449            if bit > 0 && nlimbs > 0 {
7450                let mask = (1u32 << bit) - 1;
7451                if limbs[0] & mask != 0 { has_rest = true; }
7452                for i in 0..nlimbs - 1 {
7453                    limbs[i] = (limbs[i] >> bit) | (limbs[i + 1] << (32 - bit));
7454                }
7455                limbs[nlimbs - 1] >>= bit;
7456            }
7457        }
7458
7459        while nlimbs > 0 && limbs[nlimbs - 1] == 0 { nlimbs -= 1; }
7460
7461        let ndigits = p + 2;
7462        let mut all_digits = [0u8; 25];
7463        let mut nd = 0usize;
7464        if nlimbs > 0 {
7465            loop {
7466                let mut all_zero = true;
7467                for i in 0..nlimbs { if limbs[i] != 0 { all_zero = false; break; } }
7468                if all_zero { break; }
7469                let mut rem64 = 0u64;
7470                for i in (0..nlimbs).rev() {
7471                    let val = (rem64 << 32) | limbs[i] as u64;
7472                    limbs[i] = (val / 10) as u32;
7473                    rem64 = val % 10;
7474                }
7475                if nd < 25 { all_digits[nd] = rem64 as u8; }
7476                nd += 1;
7477            }
7478        }
7479
7480        if nd >= ndigits {
7481            for i in 0..ndigits { fbuf[ndigits - 1 - i] = all_digits[i]; }
7482        } else {
7483            for i in 0..nd { fbuf[ndigits - 1 - i] = all_digits[i]; }
7484            for i in nd..ndigits { fbuf[ndigits - 1 - i] = 0; }
7485        }
7486
7487        int_part = fbuf[0] as u64;
7488
7489        // Round half to even: next_d is the rounding digit beyond precision
7490        if p > 0 {
7491            let next_d = fbuf[p + 1];
7492            let last_d = fbuf[p];
7493            if next_d > 5 || (next_d == 5 && (has_rest || last_d & 1 != 0)) {
7494                let mut carry = true;
7495                for j in (1..=p).rev() {
7496                    if !carry { break; }
7497                    let d = fbuf[j] + 1;
7498                    if d < 10 { fbuf[j] = d; carry = false; break; }
7499                    fbuf[j] = 0;
7500                }
7501                if carry { int_part += 1; }
7502            }
7503        } else {
7504            let next_d = fbuf[1];
7505            if next_d > 5 || (next_d == 5 && (has_rest || int_part & 1 != 0)) {
7506                int_part += 1;
7507            }
7508        }
7509
7510        // fbuf[1..=p] are now the fractional digits for output
7511        // Shift them to fbuf[0..p] so output code can index fbuf[0..p]
7512        for i in 0..p { fbuf[i] = fbuf[i + 1]; }
7513    }
7514
7515    if !use_f && int_part >= 10 {
7516        exp += 1;
7517        int_part = 1;
7518    }
7519
7520    // Format output
7521    if use_f {
7522        // %f style
7523        let (ibuf, ilen) = format_u64(int_part);
7524        core::ptr::copy_nonoverlapping(ibuf.as_ptr(), dst.add(pos), ilen);
7525        pos += ilen;
7526        if p > 0 || flags & FLAG_HASH != 0 {
7527            *dst.add(pos) = b'.'; pos += 1;
7528            for idx in 0..p { *dst.add(pos) = b'0' + fbuf[idx]; pos += 1; }
7529        }
7530        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7531            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7532            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7533        }
7534    } else {
7535        // %e style
7536        *dst.add(pos) = b'0' + int_part as u8; pos += 1;
7537        if p > 0 || flags & FLAG_HASH != 0 {
7538            *dst.add(pos) = b'.'; pos += 1;
7539            for idx in 0..p { *dst.add(pos) = b'0' + fbuf[idx]; pos += 1; }
7540        }
7541        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7542            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7543            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7544        }
7545        let ec = if uppercase { b'E' } else { b'e' };
7546        *dst.add(pos) = ec; pos += 1;
7547        *dst.add(pos) = if exp < 0 { b'-' } else { b'+' }; pos += 1;
7548        let eabs = if exp < 0 { (-exp) as u32 } else { exp as u32 };
7549        if eabs < 10 { *dst.add(pos) = b'0'; pos += 1; }
7550        let (ebuf, elen) = format_u64(eabs as u64);
7551        core::ptr::copy_nonoverlapping(ebuf.as_ptr(), dst.add(pos), elen);
7552        pos += elen;
7553    }
7554
7555    pos
7556}
7557
7558// Compute decimal exponent: floor(log10(v)) with correction
7559unsafe fn compute_exp10(v: f64) -> i32 {
7560    let e = libm::floor(libm::log10(v)) as i32;
7561    let probe = v / libm::pow(10.0, e as f64);
7562    if probe >= 10.0 { e + 1 }
7563    else if probe < 1.0 { e - 1 }
7564    else { e }
7565}
7566
7567// Write hex float to dst. Returns bytes written.
7568unsafe fn fmt_hex_float(dst: *mut u8, val: f64, precision: i32, _flags: u8, uppercase: bool) -> usize {
7569    // Handle zero (and negative zero) specially
7570    if val.to_bits() & 0x7FFFFFFFFFFFFFFF == 0 {
7571        let lc = !uppercase;
7572        let pfx: &[u8] = if lc { b"0x" } else { b"0X" };
7573        let p = if precision < 0 { 0usize } else { precision as usize };
7574        let mut pos = 0usize;
7575        core::ptr::copy_nonoverlapping(pfx.as_ptr(), dst.add(pos), 2); pos += 2;
7576        *dst.add(pos) = b'0'; pos += 1;
7577        if p > 0 {
7578            *dst.add(pos) = b'.'; pos += 1;
7579            for _ in 0..p { *dst.add(pos) = b'0'; pos += 1; }
7580        }
7581        let pc = if lc { b'p' } else { b'P' };
7582        *dst.add(pos) = pc; pos += 1;
7583        *dst.add(pos) = b'+'; pos += 1;
7584        *dst.add(pos) = b'0'; pos += 1;
7585        return pos;
7586    }
7587    let bits = val.to_bits();
7588    let exp_bits = ((bits >> 52) & 0x7FF) as i32;
7589    let mant_bits = bits & 0x000FFFFFFFFFFFFF;
7590    let (mut e, mut m) = if exp_bits == 0 { (1 - 1023, mant_bits) } else { (exp_bits - 1023, mant_bits | (1u64 << 52)) };
7591    // musl normalizes subnormals so the leading digit is always 1, which
7592    // lets the exponent go below -1022 (e.g. 0x1p-1074 for the smallest).
7593    if exp_bits == 0 && m != 0 {
7594        let shift = m.leading_zeros() as i32 - 11;
7595        m <<= shift;
7596        e -= shift;
7597    }
7598    let explicit = precision >= 0;
7599    let p = if explicit { precision as usize } else { 13usize };
7600    let mut pos = 0usize;
7601    let lc = !uppercase;
7602    let pfx: &[u8] = if lc { b"0x" } else { b"0X" };
7603    core::ptr::copy_nonoverlapping(pfx.as_ptr(), dst.add(pos), 2); pos += 2;
7604
7605    // Leading digit from bit 52 (1 for every normalized value).
7606    let lead_pos = pos;
7607    let mut lead = ((m >> 52) & 0xF) as u8;
7608    *dst.add(pos) = hex_digit_char(lead, lc); pos += 1;
7609    let mut frac_start = pos;
7610    if p > 0 {
7611        *dst.add(pos) = b'.'; pos += 1;
7612        frac_start = pos;
7613    }
7614
7615    // Extract p hex digits from the fraction, most significant nibble first.
7616    let mut rm = m;
7617    for _ in 0..p {
7618        let nib = ((rm >> 48) & 0xF) as u8;
7619        *dst.add(pos) = hex_digit_char(nib, lc); pos += 1;
7620        rm <<= 4;
7621    }
7622
7623    // Round to nearest, ties to even, based on the next nibble.
7624    let round_nib = ((rm >> 48) & 0xF) as u8;
7625    let rest = rm & 0x0000FFFFFFFFFFFF;
7626    let last_nib = if p > 0 {
7627        hex_val(*dst.add(pos - 1)).unwrap_or(0)
7628    } else {
7629        lead
7630    };
7631    let should_round = round_nib > 8 || (round_nib == 8 && (rest != 0 || (last_nib & 1) != 0));
7632    if should_round {
7633        let mut j = pos;
7634        loop {
7635            if j == frac_start {
7636                // Carry out of the fraction into the leading digit.
7637                lead += 1;
7638                *dst.add(lead_pos) = hex_digit_char(lead, lc);
7639                break;
7640            }
7641            j -= 1;
7642            let v = hex_val(*dst.add(j)).unwrap_or(0);
7643            if v < 15 {
7644                *dst.add(j) = hex_digit_char(v + 1, lc);
7645                break;
7646            }
7647            *dst.add(j) = b'0';
7648        }
7649    }
7650
7651    // With no explicit precision, print the shortest exact representation:
7652    // trim trailing fractional zeros and drop the radix point if empty.
7653    if !explicit {
7654        while pos > frac_start && *dst.add(pos - 1) == b'0' {
7655            pos -= 1;
7656        }
7657        if pos == frac_start {
7658            pos = frac_start - 1;
7659        }
7660    }
7661
7662    // Exponent
7663    let pc = if lc { b'p' } else { b'P' };
7664    *dst.add(pos) = pc; pos += 1;
7665    *dst.add(pos) = if e < 0 { b'-' } else { b'+' }; pos += 1;
7666    let eabs = if e < 0 { (-e) as u32 } else { e as u32 };
7667    let (ebuf, elen) = format_u64(eabs as u64);
7668    core::ptr::copy_nonoverlapping(ebuf.as_ptr(), dst.add(pos), elen);
7669    pos += elen;
7670    pos
7671}
7672
7673#[inline]
7674fn hex_digit_char(v: u8, lowercase: bool) -> u8 {
7675    if v < 10 { b'0' + v }
7676    else if lowercase { b'a' + v - 10 }
7677    else { b'A' + v - 10 }
7678}
7679
7680#[inline]
7681
7682// Apply width and flags padding to a formatted string in buf[0..len].
7683// Writes the final result to dst. Returns total bytes written.
7684unsafe fn apply_width_flags(
7685    dst: *mut u8, buf: *const u8, len: usize, width: usize, flags: u8,
7686) -> usize {
7687    if len >= width {
7688        core::ptr::copy_nonoverlapping(buf, dst, len);
7689        return len;
7690    }
7691    let pad = width - len;
7692    let pad_char = if flags & FLAG_ZERO != 0 && flags & FLAG_MINUS == 0 { b'0' } else { b' ' };
7693    if flags & FLAG_MINUS != 0 {
7694        // Left align
7695        core::ptr::copy_nonoverlapping(buf, dst, len);
7696        for i in 0..pad { *dst.add(len + i) = pad_char; }
7697    } else {
7698        // Right align
7699        // For zero-padded numbers, sign goes before zeros
7700        if flags & FLAG_ZERO != 0 && len > 0 {
7701            let first = *buf;
7702            if first == b'-' || first == b'+' || first == b' ' {
7703                *dst = first;
7704                for i in 0..pad { *dst.add(1 + i) = pad_char; }
7705                core::ptr::copy_nonoverlapping(buf.add(1), dst.add(1 + pad), len - 1);
7706                return width;
7707            }
7708        }
7709        for i in 0..pad { *dst.add(i) = pad_char; }
7710        core::ptr::copy_nonoverlapping(buf, dst.add(pad), len);
7711    }
7712    width
7713}
7714
7715#[no_mangle]
7716pub unsafe extern "C" fn vprintf(fmt: *const c_char, mut args: VaList) -> c_int {
7717    impl_format!(fmt, args,
7718        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stdout); },
7719        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stdout); }
7720    )
7721}
7722
7723#[no_mangle]
7724pub unsafe extern "C" fn vfprintf(stream: *mut FILE, fmt: *const c_char, mut args: VaList) -> c_int {
7725    impl_format!(fmt, args,
7726        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stream); },
7727        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stream); }
7728    )
7729}
7730
7731#[no_mangle]
7732pub unsafe extern "C" fn printf(fmt: *const c_char, mut args: ...) -> c_int {
7733    impl_format!(fmt, args,
7734        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stdout); },
7735        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stdout); }
7736    )
7737}
7738
7739#[no_mangle]
7740pub unsafe extern "C" fn fprintf(stream: *mut FILE, fmt: *const c_char, mut args: ...) -> c_int {
7741    impl_format!(fmt, args,
7742        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stream); },
7743        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stream); }
7744    )
7745}
7746
7747unsafe fn format_write_fd(fd: c_int, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
7748    // cgroupfs (and some other pseudo-filesystems) parse one command per
7749    // write() call, so the whole formatted string must go out at once.
7750    let mut stack = [0u8; 4096];
7751    let mut a1 = args.clone();
7752    let n = format_to_buf(stack.as_mut_ptr(), stack.len(), fmt, &mut a1);
7753    if n < 0 { return -1; }
7754    if (n as usize) < stack.len() {
7755        let w = crate::write(fd, stack.as_ptr() as *const c_void, n as usize);
7756        if w < 0 { return -1; }
7757        return n;
7758    }
7759    let heap = crate::malloc(n as usize + 1) as *mut u8;
7760    if heap.is_null() { return -1; }
7761    let mut a2 = args.clone();
7762    let n2 = format_to_buf(heap, n as usize + 1, fmt, &mut a2);
7763    if n2 < 0 { crate::free(heap as *mut c_void); return -1; }
7764    let w = crate::write(fd, heap as *const c_void, n2 as usize);
7765    crate::free(heap as *mut c_void);
7766    if w < 0 { return -1; }
7767    n2
7768}
7769
7770#[no_mangle]
7771pub unsafe extern "C" fn dprintf(fd: c_int, fmt: *const c_char, mut args: ...) -> c_int {
7772    format_write_fd(fd, fmt, &mut args)
7773}
7774
7775#[no_mangle]
7776pub unsafe extern "C" fn vdprintf(fd: c_int, fmt: *const c_char, mut args: VaList) -> c_int {
7777    format_write_fd(fd, fmt, &mut args)
7778}
7779
7780// ============================================================
7781// sprintf / snprintf / vsprintf / vsnprintf
7782// ============================================================
7783
7784unsafe fn format_to_buf(buf: *mut u8, cap: usize, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
7785    // Reuse the shared format engine with buffer writer closures instead of
7786    // maintaining a second copy of the conversion table.
7787    let pos = core::cell::Cell::new(0usize);
7788    let write_char = |c: u8| {
7789        let p = pos.get();
7790        if p < cap { *buf.add(p) = c; }
7791        pos.set(p + 1);
7792    };
7793    let write_str = |s: *const u8, len: usize| {
7794        let p = pos.get();
7795        for k in 0..len {
7796            if p + k < cap { *buf.add(p + k) = *s.add(k); }
7797        }
7798        pos.set(p + len);
7799    };
7800    let count = impl_format!(fmt, *args, write_char, write_str);
7801    if cap > 0 {
7802        let end = core::cmp::min(count as usize, cap - 1);
7803        *buf.add(end) = 0;
7804    }
7805    count
7806}
7807
7808#[no_mangle]
7809pub unsafe extern "C" fn vsprintf(buf: *mut c_char, fmt: *const c_char, mut args: VaList) -> c_int {
7810    format_to_buf(buf as *mut u8, usize::MAX, fmt, &mut args)
7811}
7812
7813#[no_mangle]
7814pub unsafe extern "C" fn vsnprintf(buf: *mut c_char, size: usize, fmt: *const c_char, mut args: VaList) -> c_int {
7815    format_to_buf(buf as *mut u8, size, fmt, &mut args)
7816}
7817
7818#[no_mangle]
7819pub unsafe extern "C" fn sprintf(buf: *mut c_char, fmt: *const c_char, mut args: ...) -> c_int {
7820    format_to_buf(buf as *mut u8, usize::MAX, fmt, &mut args)
7821}
7822
7823#[no_mangle]
7824pub unsafe extern "C" fn snprintf(buf: *mut c_char, size: usize, fmt: *const c_char, mut args: ...) -> c_int {
7825    format_to_buf(buf as *mut u8, size, fmt, &mut args)
7826}
7827
7828#[no_mangle]
7829pub unsafe extern "C" fn vasprintf(strp: *mut *mut c_char, fmt: *const c_char, ap: VaList) -> c_int {
7830    if strp.is_null() {
7831        ERRNO!() = EINVAL;
7832        return -1;
7833    }
7834    let len = vsnprintf(core::ptr::null_mut(), 0, fmt, ap.clone());
7835    if len < 0 {
7836        *strp = core::ptr::null_mut();
7837        return -1;
7838    }
7839    let p = malloc((len as usize) + 1) as *mut c_char;
7840    if p.is_null() {
7841        *strp = core::ptr::null_mut();
7842        return -1;
7843    }
7844    let ret = vsnprintf(p, (len as usize) + 1, fmt, ap.clone());
7845    if ret < 0 {
7846        free(p as *mut c_void);
7847        *strp = core::ptr::null_mut();
7848        return -1;
7849    }
7850    *strp = p;
7851    ret
7852}
7853
7854#[no_mangle]
7855pub unsafe extern "C" fn asprintf(strp: *mut *mut c_char, fmt: *const c_char, args: ...) -> c_int {
7856    vasprintf(strp, fmt, args)
7857}
7858
7859// ============================================================
7860// scanf / vscanf / fscanf / vfscanf / sscanf / vsscanf
7861// ============================================================
7862
7863
7864#[inline]
7865fn is_ws_byte(c: u8) -> bool {
7866    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == 0x0b || c == 0x0c
7867}
7868
7869// Scan integer with position tracking. Returns (value, is_negative, success).
7870// base: 0=auto, 8=octal, 10=decimal, 16=hex
7871unsafe fn scan_int_val(
7872    buf: *const u8, pos: &mut usize, buf_len: usize, base: u32, width: usize,
7873) -> (u64, bool, bool) {
7874    let start = *pos;
7875    let max = if width > 0 { (start + width).min(buf_len) } else { buf_len };
7876    let neg = if *pos < max && *buf.add(*pos) == b'-' { *pos += 1; true }
7877    else if *pos < max && *buf.add(*pos) == b'+' { *pos += 1; false }
7878    else { false };
7879    if *pos >= max { *pos = start; return (0, false, false); }
7880    let mut base = base;
7881    let mut val: u64 = 0;
7882    // Auto-detect base / handle 0x prefix
7883    if (base == 0 || base == 16) && *pos < max && *buf.add(*pos) == b'0' {
7884        *pos += 1;
7885        if *pos < max && (*buf.add(*pos) == b'x' || *buf.add(*pos) == b'X') {
7886            *pos += 1;
7887            if *pos < max {
7888                if let Some(d) = hex_val(*buf.add(*pos)) {
7889                    val = d as u64; *pos += 1;
7890                    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; } }
7891                    return (val, neg, true);
7892                }
7893            }
7894            return (0, neg, false);
7895        } else if base == 0 {
7896            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; } }
7897            return (val, neg, true);
7898        } else {
7899            // base 16 with a leading zero ("00000000"): the zero is part of
7900            // the number, not a prefix that ends the conversion.
7901            while *pos < max {
7902                if let Some(d) = hex_val(*buf.add(*pos)) {
7903                    val = val.wrapping_mul(16).wrapping_add(d as u64);
7904                    *pos += 1;
7905                } else {
7906                    break;
7907                }
7908            }
7909            return (val, neg, true);
7910        }
7911    }
7912    if base == 0 { base = 10; }
7913    let mut found = false;
7914    while *pos < max {
7915        let c = *buf.add(*pos);
7916        let d: Option<u64> = match base {
7917            8 => if c >= b'0' && c <= b'7' { Some((c - b'0') as u64) } else { None },
7918            10 => if c >= b'0' && c <= b'9' { Some((c - b'0') as u64) } else { None },
7919            16 => hex_val(c).map(|v| v as u64),
7920            _ => None,
7921        };
7922        match d { Some(digit) => { val = val.wrapping_mul(base as u64).wrapping_add(digit); *pos += 1; found = true; } None => break }
7923    }
7924    if !found { *pos = start; return (0, false, false); }
7925    (val, neg, true)
7926}
7927
7928// Scan float with position tracking. Returns (value, success).
7929unsafe fn scan_float_val(
7930    buf: *const u8, pos: &mut usize, buf_len: usize, width: usize,
7931) -> (f64, bool) {
7932    let start = *pos;
7933    let max = if width > 0 { (start + width).min(buf_len) } else { buf_len };
7934    let neg = if *pos < max && *buf.add(*pos) == b'-' { *pos += 1; true }
7935    else if *pos < max && *buf.add(*pos) == b'+' { *pos += 1; false }
7936    else { false };
7937    // inf/nan
7938    if *pos + 2 < max {
7939        let (c0,c1,c2) = (*buf.add(*pos), *buf.add(*pos+1), *buf.add(*pos+2));
7940        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); }
7941        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); }
7942    }
7943    // hex float
7944    if *pos+1 < max && *buf.add(*pos)==b'0' && (*buf.add(*pos+1)==b'x'||*buf.add(*pos+1)==b'X') {
7945        *pos += 2;
7946        let mut val: f64 = 0.0; let mut found = false; let mut frac_scale = 1.0f64; let mut in_frac = false;
7947        while *pos < max {
7948            if let Some(d) = hex_val(*buf.add(*pos)) {
7949                if in_frac { frac_scale /= 16.0; val += d as f64 * frac_scale; } else { val = val * 16.0 + d as f64; }
7950                *pos += 1; found = true;
7951            } else if *buf.add(*pos)==b'.' && !in_frac { in_frac = true; *pos += 1; } else { break; }
7952        }
7953        if !found { *pos = start; return (0.0, false); }
7954        // p exponent
7955        if *pos < max && (*buf.add(*pos)==b'p'||*buf.add(*pos)==b'P') {
7956            *pos += 1;
7957            let mut eneg = false;
7958            if *pos<max && *buf.add(*pos)==b'-' { eneg=true; *pos+=1; }
7959            else if *pos<max && *buf.add(*pos)==b'+' { *pos+=1; }
7960            let mut ev: i32 = 0; let mut ef = false;
7961            while *pos<max && *buf.add(*pos)>=b'0' && *buf.add(*pos)<=b'9' {
7962                ev = ev.saturating_mul(10).saturating_add((*buf.add(*pos)-b'0') as i32).min(1_000_000);
7963                *pos+=1; ef=true;
7964            }
7965            if !ef { return (0.0, false); }
7966            if eneg { ev = -ev; }
7967            val *= libm::pow(2.0, ev as f64);
7968        }
7969        return (if neg{-val}else{val}, true);
7970    }
7971    let token_start = start;
7972    let mut i = start;
7973    let mut saw_digit = false;
7974    let mut saw_dot = false;
7975    let mut saw_exp = false;
7976    let mut first = true;
7977    while i < max {
7978        let c = *buf.add(i);
7979        if (c == b'+' || c == b'-') && first {
7980            i += 1; first = false; continue;
7981        }
7982        if c >= b'0' && c <= b'9' {
7983            saw_digit = true; i += 1; first = false; continue;
7984        }
7985        if c == b'.' && !saw_dot && !saw_exp {
7986            saw_dot = true; i += 1; first = false; continue;
7987        }
7988        if (c == b'e' || c == b'E') && !saw_exp && saw_digit {
7989            saw_exp = true; i += 1; first = true; continue;
7990        }
7991        break;
7992    }
7993    if !saw_digit { return (0.0, false); }
7994    let s = core::str::from_utf8_unchecked(core::slice::from_raw_parts(buf.add(token_start), i - token_start));
7995    match <f64 as core::str::FromStr>::from_str(s) {
7996        Ok(v) => { *pos = i; return (v, true); }
7997        Err(_) => { return (0.0, false); }
7998    }
7999}
8000
8001// Comprehensive scanf parser with position tracking.
8002// consumed: if non-null, stores number of bytes consumed from buf.
8003/// Store a scanned integer with the width selected by the length modifier.
8004/// Without this, `%ld`/`%lu` silently truncate to 32 bits.
8005unsafe fn store_scan_int(dest: *mut c_void, len_mod: u8, val: u64, neg: bool) {
8006    let sv: i64 = if neg { (val as i64).wrapping_neg() } else { val as i64 };
8007    match len_mod {
8008        2 => *(dest as *mut i8) = sv as i8,
8009        1 => *(dest as *mut i16) = sv as i16,
8010        3 | 4 => *(dest as *mut i64) = sv,
8011        _ => *(dest as *mut i32) = sv as i32,
8012    }
8013}
8014
8015unsafe fn do_vsscanf(
8016    buf: *const u8, buf_len: usize, fmt: *const c_char, args: &mut VaList<'_>, consumed: *mut usize,
8017) -> c_int {
8018    let mut p = 0usize;
8019    let mut fi = 0usize;
8020    let mut assigned = 0i32;
8021    let mut input_eof = false;
8022    loop {
8023        let fc = *fmt.add(fi) as u8;
8024        if fc == 0 { break; }
8025        if is_ws_byte(fc) {
8026            while is_ws_byte(*fmt.add(fi) as u8) { fi += 1; }
8027            while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8028            continue;
8029        }
8030        if fc != b'%' {
8031            if p >= buf_len { input_eof = true; break; }
8032            if *buf.add(p) != fc { break; }
8033            p += 1; fi += 1; continue;
8034        }
8035        fi += 1;
8036        // %%
8037        if *fmt.add(fi) as u8 == b'%' {
8038            if p >= buf_len { input_eof = true; break; }
8039            if *buf.add(p) != b'%' { break; }
8040            p += 1; fi += 1; continue;
8041        }
8042        let suppress = if *fmt.add(fi) as u8 == b'*' { fi += 1; true } else { false };
8043        let mut width: usize = 0;
8044        let mut width_overflow = false;
8045        while (*fmt.add(fi) as u8) >= b'0' && (*fmt.add(fi) as u8) <= b'9' {
8046            let digit = ((*fmt.add(fi) as u8) - b'0') as usize;
8047            if width > (c_int::MAX as usize - digit) / 10 {
8048                width_overflow = true;
8049                break;
8050            }
8051            width = width * 10 + digit;
8052            fi += 1;
8053        }
8054        if width_overflow { input_eof = true; break; }
8055        let mut alloc = false;
8056        if *fmt.add(fi) as u8 == b'm' {
8057            alloc = !suppress;
8058            fi += 1;
8059        }
8060        let mut len_mod = 0u8;
8061        match *fmt.add(fi) as u8 {
8062            b'h' => { fi += 1; if *fmt.add(fi) as u8 == b'h' { fi += 1; len_mod = 2; } else { len_mod = 1; } }
8063            b'l' => { fi += 1; if *fmt.add(fi) as u8 == b'l' { fi += 1; len_mod = 4; } else { len_mod = 3; } }
8064            b'j' => { fi += 1; len_mod = 4; }
8065            b'z' | b't' => { fi += 1; len_mod = 3; }
8066            b'L' => { fi += 1; len_mod = 5; }
8067            _ => {}
8068        }
8069        let spec = *fmt.add(fi) as u8;
8070        let (real_spec, _real_len) = if spec==b'C' {(b'c',3u8)} else if spec==b'S' {(b's',3u8)} else {(spec,len_mod)};
8071        match real_spec {
8072            b'n' => {
8073                if !suppress {
8074                    let out = args.next_arg::<*mut c_void>();
8075                    if !out.is_null() {
8076                        match len_mod {
8077                            1 => *(out as *mut i16) = p as i16,
8078                            2 => *(out as *mut i8) = p as i8,
8079                            3 | 4 => *(out as *mut i64) = p as i64,
8080                            _ => *(out as *mut c_int) = p as c_int,
8081                        }
8082                    }
8083                }
8084            }
8085            b'd' | b'u' => {
8086                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8087                if p >= buf_len { input_eof = true; break; }
8088                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8089                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 10, width);
8090                if !ok { break; }
8091                if let Some(out) = dest { if !out.is_null() {
8092                    store_scan_int(out, len_mod, val, neg);
8093                }}
8094                if !suppress { assigned += 1; }
8095            }
8096            b'i' => {
8097                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8098                if p >= buf_len { input_eof = true; break; }
8099                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8100                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 0, width);
8101                if !ok { break; }
8102                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8103                if !suppress { assigned += 1; }
8104            }
8105            b'o' => {
8106                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8107                if p >= buf_len { input_eof = true; break; }
8108                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8109                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 8, width);
8110                if !ok { break; }
8111                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8112                if !suppress { assigned += 1; }
8113            }
8114            b'x' | b'X' => {
8115                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8116                if p >= buf_len { input_eof = true; break; }
8117                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8118                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 16, width);
8119                if !ok { break; }
8120                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8121                if !suppress { assigned += 1; }
8122            }
8123            b'p' => {
8124                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8125                if p >= buf_len { input_eof = true; break; }
8126                let dest = if !suppress { Some(args.next_arg::<*mut *mut c_void>()) } else { None };
8127                let (val, _, ok) = scan_int_val(buf, &mut p, buf_len, 16, width);
8128                if !ok { break; }
8129                if let Some(out) = dest { if !out.is_null() { *out = val as usize as *mut c_void; } }
8130                if !suppress { assigned += 1; }
8131            }
8132            b'a' | b'e' | b'f' | b'g' | b'A' | b'E' | b'F' | b'G' => {
8133                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8134                if p >= buf_len { input_eof = true; break; }
8135                let (val, ok) = scan_float_val(buf, &mut p, buf_len, width);
8136                if !ok { break; }
8137                if !suppress {
8138                    if _real_len == 3 {
8139                        let out = args.next_arg::<*mut f64>(); if !out.is_null() { *out = val; }
8140                    } else if _real_len == 5 {
8141                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
8142                        { let out = args.next_arg::<*mut f128>(); if !out.is_null() { *out = val as f128; } }
8143                        #[cfg(target_arch = "x86_64")]
8144                        { let out = args.next_arg::<*mut f64>(); if !out.is_null() { *out = val; } }
8145                    } else {
8146                        let out = args.next_arg::<*mut f32>(); if !out.is_null() { *out = val as f32; }
8147                    }
8148                }
8149                if !suppress { assigned += 1; }
8150            }
8151            b'c' => {
8152                let w = if width > 0 { width } else { 1 };
8153                if p >= buf_len { input_eof = true; break; }
8154                let start_p = p;
8155                let mut j = 0usize;
8156                if alloc {
8157                    let out = args.next_arg::<*mut *mut c_char>();
8158                    let s = crate::malloc(w + 1) as *mut c_char;
8159                    if s.is_null() {
8160                        if !consumed.is_null() { *consumed = p; }
8161                        return if assigned == 0 { -1 } else { assigned };
8162                    }
8163                    while j < w && p < buf_len {
8164                        *s.add(j) = *buf.add(p) as c_char;
8165                        p += 1; j += 1;
8166                    }
8167                    if j != w {
8168                        crate::free(s as *mut c_void);
8169                        p = start_p;
8170                        input_eof = true;
8171                        break;
8172                    }
8173                    if !out.is_null() { *out = s; } else { crate::free(s as *mut c_void); }
8174                    if !suppress { assigned += 1; }
8175                } else {
8176                    let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8177                    while j < w && p < buf_len {
8178                        if !dest_ptr.is_null() { *dest_ptr.add(j) = *buf.add(p) as c_char; }
8179                        p += 1; j += 1;
8180                    }
8181                    if j != w { p = start_p; input_eof = true; break; }
8182                    if !suppress { assigned += 1; }
8183                }
8184            }
8185            b's' => {
8186                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8187                if p >= buf_len { input_eof = true; break; }
8188                let w = if width > 0 { width } else { usize::MAX };
8189                if alloc {
8190                    let out = args.next_arg::<*mut *mut c_char>();
8191                    let mut k = 31usize;
8192                    let mut s = crate::malloc(k) as *mut u8;
8193                    if s.is_null() {
8194                        if !consumed.is_null() { *consumed = p; }
8195                        return if assigned == 0 { -1 } else { assigned };
8196                    }
8197                    let mut j = 0usize;
8198                    let mut failed = false;
8199                    while p < buf_len && *buf.add(p) != 0 && !is_ws_byte(*buf.add(p)) && j < w {
8200                        *s.add(j) = *buf.add(p);
8201                        j += 1;
8202                        p += 1;
8203                        if j == k {
8204                            let nk = k * 2 + 1;
8205                            let ns = crate::realloc(s as *mut c_void, nk) as *mut u8;
8206                            if ns.is_null() { failed = true; break; }
8207                            s = ns;
8208                            k = nk;
8209                        }
8210                    }
8211                    if failed {
8212                        crate::free(s as *mut c_void);
8213                        if !consumed.is_null() { *consumed = p; }
8214                        return if assigned == 0 { -1 } else { assigned };
8215                    }
8216                    if j == 0 { crate::free(s as *mut c_void); break; }
8217                    *s.add(j) = 0;
8218                    if !out.is_null() { *out = s as *mut c_char; } else { crate::free(s as *mut c_void); }
8219                    if !suppress { assigned += 1; }
8220                } else {
8221                    let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8222                    let mut j = 0usize;
8223                    while p < buf_len && *buf.add(p) != 0 && !is_ws_byte(*buf.add(p)) && j < w {
8224                        if !dest_ptr.is_null() { *dest_ptr.add(j) = *buf.add(p) as c_char; }
8225                        p += 1; j += 1;
8226                    }
8227                    if j == 0 { break; }
8228                    if !dest_ptr.is_null() { *dest_ptr.add(j) = 0; }
8229                    if !suppress { assigned += 1; }
8230                }
8231            }
8232            b'[' => {
8233                fi += 1;
8234                let negate = if *fmt.add(fi) as u8 == b'^' { fi += 1; true } else { false };
8235                let mut charset = [0u8; 256];
8236                let mut prev: Option<u8> = None;
8237                if *fmt.add(fi) as u8 == b']' {
8238                    charset[b']' as usize] = 1;
8239                    prev = Some(b']');
8240                    fi += 1;
8241                }
8242                loop {
8243                    let c = *fmt.add(fi) as u8;
8244                    if c == b']' || c == 0 { break; }
8245                    // "a-z" is a range; a '-' next to ']' or at the start/end
8246                    // of the set is a literal.
8247                    if c == b'-' && prev.is_some() {
8248                        let hi = *fmt.add(fi + 1) as u8;
8249                        if hi != b']' && hi != 0 {
8250                            let lo = prev.unwrap();
8251                            let mut k = lo;
8252                            while k <= hi {
8253                                charset[k as usize] = 1;
8254                                if k == 255 { break; }
8255                                k += 1;
8256                            }
8257                            prev = None;
8258                            fi += 2;
8259                            continue;
8260                        }
8261                    }
8262                    charset[c as usize] = 1;
8263                    prev = Some(c);
8264                    fi += 1;
8265                }
8266                if *fmt.add(fi) as u8 == b']' { fi += 1; }
8267                fi -= 1; // common fi += 1 will advance past the closing ]
8268                if p >= buf_len { input_eof = true; break; }
8269                let w = if width > 0 { width } else { usize::MAX };
8270                if alloc {
8271                    let out = args.next_arg::<*mut *mut c_char>();
8272                    let mut k = 31usize;
8273                    let mut s = crate::malloc(k) as *mut u8;
8274                    if s.is_null() {
8275                        if !consumed.is_null() { *consumed = p; }
8276                        return if assigned == 0 { -1 } else { assigned };
8277                    }
8278                    let mut j = 0usize;
8279                    let mut failed = false;
8280                    while p < buf_len && *buf.add(p) != 0 && j < w {
8281                        let c = *buf.add(p);
8282                        let in_set = charset[c as usize] != 0;
8283                        if negate { if in_set { break; } } else if !in_set { break; }
8284                        *s.add(j) = c;
8285                        j += 1;
8286                        p += 1;
8287                        if j == k {
8288                            let nk = k * 2 + 1;
8289                            let ns = crate::realloc(s as *mut c_void, nk) as *mut u8;
8290                            if ns.is_null() { failed = true; break; }
8291                            s = ns;
8292                            k = nk;
8293                        }
8294                    }
8295                    if failed {
8296                        crate::free(s as *mut c_void);
8297                        if !consumed.is_null() { *consumed = p; }
8298                        return if assigned == 0 { -1 } else { assigned };
8299                    }
8300                    if j == 0 { crate::free(s as *mut c_void); break; }
8301                    *s.add(j) = 0;
8302                    if !out.is_null() { *out = s as *mut c_char; } else { crate::free(s as *mut c_void); }
8303                    if !suppress { assigned += 1; }
8304                } else {
8305                    let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8306                    let mut j = 0usize;
8307                    while p < buf_len && *buf.add(p) != 0 && j < w {
8308                        let c = *buf.add(p);
8309                        let in_set = charset[c as usize] != 0;
8310                        if negate { if in_set { break; } } else if !in_set { break; }
8311                        if !dest_ptr.is_null() { *dest_ptr.add(j) = c as c_char; }
8312                        p += 1; j += 1;
8313                    }
8314                    if j == 0 { break; }
8315                    if !dest_ptr.is_null() { *dest_ptr.add(j) = 0; }
8316                    if !suppress { assigned += 1; }
8317                }
8318            }
8319            _ => break,
8320        }
8321        fi += 1;
8322    }
8323    if !consumed.is_null() { *consumed = p; }
8324    if assigned == 0 && input_eof { -1 } else { assigned }
8325}
8326
8327unsafe fn vsscanf_inner(buf: *const u8, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
8328    let len = strlen(buf as *const c_char);
8329    do_vsscanf(buf, len, fmt, args, core::ptr::null_mut())
8330}
8331
8332#[no_mangle]
8333pub unsafe extern "C" fn vsscanf(buf: *const c_char, fmt: *const c_char, mut args: VaList) -> c_int {
8334    vsscanf_inner(buf as *const u8, fmt, &mut args)
8335}
8336
8337unsafe fn scan_buf_grow(buf: &mut *mut u8, cap: &mut usize, need: usize) -> bool {
8338    if need <= *cap {
8339        return true;
8340    }
8341    let mut next = core::cmp::max(*cap, 256);
8342    while next < need {
8343        next = match next.checked_mul(2) {
8344            Some(v) => v,
8345            None => return false,
8346        };
8347    }
8348    let grown = crate::realloc(*buf as *mut c_void, next) as *mut u8;
8349    if grown.is_null() {
8350        return false;
8351    }
8352    *buf = grown;
8353    *cap = next;
8354    true
8355}
8356
8357#[no_mangle]
8358pub unsafe extern "C" fn vfscanf(stream: *mut FILE, fmt: *const c_char, mut args: VaList) -> c_int {
8359    let f = &mut *stream;
8360    let start_ungotten_count = f.ungotten_count as usize;
8361    let ungotten_saved = f.ungotten;
8362    let sfunc = f.seek_fn;
8363    // Logical position, not the raw fd offset: fgetc may have read ahead.
8364    let start_pos = if sfunc.is_some() { ftello(stream) } else { -1 };
8365
8366    let mut cap = 4096usize;
8367    let mut line = crate::malloc(cap) as *mut u8;
8368    if line.is_null() {
8369        ERRNO!() = ENOMEM;
8370        return -1;
8371    }
8372    let mut pos = 0usize;
8373
8374    if start_pos >= 0 {
8375        // Seekable: read via fgetc until newline or EOF.
8376        loop {
8377            if !scan_buf_grow(&mut line, &mut cap, pos + 1) {
8378                crate::free(line as *mut c_void);
8379                ERRNO!() = ENOMEM;
8380                return -1;
8381            }
8382            let c = fgetc(stream);
8383            if c == -1 { break; }
8384            *line.add(pos) = c as u8;
8385            pos += 1;
8386            if c == b'\n' as c_int { break; }
8387        }
8388    } else {
8389        // Non-seekable (pipe/socket): drain pushback, then read all available
8390        // data non-blocking so we don't stop at newline boundaries.
8391
8392        // 1. Drain ungotten bytes (LIFO order)
8393        while f.ungotten_count > 0 {
8394            if !scan_buf_grow(&mut line, &mut cap, pos + 1) {
8395                crate::free(line as *mut c_void);
8396                ERRNO!() = ENOMEM;
8397                return -1;
8398            }
8399            f.ungotten_count -= 1;
8400            *line.add(pos) = f.ungotten[f.ungotten_count as usize] as u8;
8401            pos += 1;
8402        }
8403        // 2. Drain rpos/rend pushback buffer
8404        while !f.rpos.is_null() && f.rpos < f.rend {
8405            if !scan_buf_grow(&mut line, &mut cap, pos + 1) {
8406                crate::free(line as *mut c_void);
8407                ERRNO!() = ENOMEM;
8408                return -1;
8409            }
8410            *line.add(pos) = *f.rpos;
8411            f.rpos = f.rpos.add(1);
8412            pos += 1;
8413        }
8414        // 3. Wait for the first byte (blocking), then drain whatever else is
8415        // available without waiting. A pure non-blocking read would race with
8416        // a producer such as popen() that has not written yet.
8417        let fd = f.fd;
8418        if pos == 0 {
8419            let n = sys_read(fd as i64, line, 1);
8420            if n == 1 { pos = 1; }
8421        }
8422        let old_flags = sys_fcntl(fd, F_GETFL, 0);
8423        if old_flags >= 0 {
8424            let _ = sys_fcntl(fd, F_SETFL, old_flags | O_NONBLOCK as i64);
8425        }
8426        loop {
8427            if pos + 1 >= cap && !scan_buf_grow(&mut line, &mut cap, pos + 2) {
8428                if old_flags >= 0 { let _ = sys_fcntl(fd, F_SETFL, old_flags); }
8429                crate::free(line as *mut c_void);
8430                ERRNO!() = ENOMEM;
8431                return -1;
8432            }
8433            let n = sys_read(fd as i64, line.add(pos), cap - 1 - pos);
8434            if n <= 0 { break; }
8435            pos += n as usize;
8436        }
8437        if old_flags >= 0 {
8438            let _ = sys_fcntl(fd, F_SETFL, old_flags);
8439        }
8440        // Clear flags that the failed non-blocking read may have set
8441        f._eof = 0;
8442        f._err = 0;
8443        f.flags &= !(F_EOF | F_ERR);
8444    }
8445
8446    *line.add(pos) = 0;
8447    if pos == 0 {
8448        crate::free(line as *mut c_void);
8449        return 0;
8450    }
8451
8452    let mut consumed = 0usize;
8453    let assigned = do_vsscanf(line, pos, fmt, &mut args, &mut consumed);
8454
8455    if start_pos >= 0 {
8456        // Seek back to the logical position just past the consumed bytes and
8457        // restore any ungetc pushback the scan did not consume.
8458        let remaining = start_ungotten_count.saturating_sub(consumed);
8459        // The restored ungetc bytes will be subtracted by ftello(), so the
8460        // raw fd offset must include them.
8461        let target = start_pos + consumed as i64 + remaining as i64;
8462        if let Some(sfunc) = sfunc {
8463            sfunc(stream, target, SEEK_SET);
8464        }
8465        f.rpos = core::ptr::null_mut();
8466        f.rend = core::ptr::null_mut();
8467        if consumed < pos { f._eof = 0; }
8468        f.ungotten_count = 0;
8469        for i in 0..remaining {
8470            f.ungotten[f.ungotten_count as usize] = ungotten_saved[i];
8471            f.ungotten_count += 1;
8472        }
8473    } else {
8474        // Non-seekable: push back unconsumed bytes into FILE read buffer
8475        let unconsumed = pos.saturating_sub(consumed);
8476        if unconsumed > 0 && !f.buf.is_null() {
8477            let copy_count = core::cmp::min(unconsumed, f.buf_size);
8478            core::ptr::copy(
8479                line.add(consumed),
8480                f.buf,
8481                copy_count,
8482            );
8483            f.rpos = f.buf;
8484            f.rend = f.buf.add(copy_count);
8485        }
8486        f.ungotten_count = 0;
8487        f._eof = 0;
8488        f.flags &= !F_EOF;
8489    }
8490    crate::free(line as *mut c_void);
8491    assigned
8492}
8493
8494#[no_mangle]
8495pub unsafe extern "C" fn vscanf(fmt: *const c_char, args: VaList) -> c_int {
8496    vfscanf(stdin, fmt, args)
8497}
8498
8499#[no_mangle]
8500pub unsafe extern "C" fn sscanf(buf: *const c_char, fmt: *const c_char, mut args: ...) -> c_int {
8501    vsscanf_inner(buf as *const u8, fmt, &mut args)
8502}
8503
8504#[no_mangle]
8505pub unsafe extern "C" fn fscanf(stream: *mut FILE, fmt: *const c_char, args: ...) -> c_int {
8506    vfscanf(stream, fmt, args)
8507}
8508
8509#[no_mangle]
8510pub unsafe extern "C" fn scanf(fmt: *const c_char, args: ...) -> c_int {
8511    vfscanf(stdin, fmt, args)
8512}
8513
8514// ============================================================
8515// getdelim / getline
8516// ============================================================
8517
8518#[no_mangle]
8519pub unsafe extern "C" fn getdelim(
8520    lineptr: *mut *mut c_char, n: *mut usize, delim: c_int, stream: *mut FILE,
8521) -> isize {
8522    if lineptr.is_null() || n.is_null() {
8523        ERRNO!() = EINVAL;
8524        return -1;
8525    }
8526    let mut cap = *n;
8527    let mut buf = *lineptr;
8528    if buf.is_null() || cap == 0 {
8529        cap = 128;
8530        buf = realloc(buf as *mut c_void, cap) as *mut c_char;
8531        if buf.is_null() { return -1; }
8532        *lineptr = buf;
8533        *n = cap;
8534    }
8535    let mut len = 0usize;
8536    loop {
8537        let c = fgetc(stream);
8538        if c == -1 { if len == 0 { return -1; } break; }
8539        if len >= cap - 1 {
8540            let new_cap = match cap.checked_mul(2) {
8541                Some(v) => v,
8542                None => {
8543                    ERRNO!() = ENOMEM;
8544                    return -1;
8545                }
8546            };
8547            let new_buf = realloc(buf as *mut c_void, new_cap) as *mut c_char;
8548            if new_buf.is_null() {
8549                ERRNO!() = ENOMEM;
8550                return -1;
8551            }
8552            buf = new_buf; cap = new_cap;
8553            *lineptr = buf; *n = cap;
8554        }
8555        *buf.add(len) = c as c_char;
8556        len += 1;
8557        if c == delim { break; }
8558    }
8559    *buf.add(len) = 0;
8560    len as isize
8561}
8562
8563#[no_mangle]
8564pub unsafe extern "C" fn getline(lineptr: *mut *mut c_char, n: *mut usize, stream: *mut FILE) -> isize {
8565    getdelim(lineptr, n, b'\n' as c_int, stream)
8566}
8567
8568// ============================================================
8569// popen / pclose
8570// ============================================================
8571
8572#[no_mangle]
8573pub unsafe extern "C" fn popen(cmd: *const c_char, mode: *const c_char) -> *mut FILE {
8574    if cmd.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
8575    let m = *mode;
8576    if (m != b'r' as c_char && m != b'w' as c_char) || *mode.add(1) != 0 {
8577        ERRNO!() = EINVAL;
8578        return core::ptr::null_mut();
8579    }
8580    let mut p: [c_int; 2] = [0; 2];
8581    let pipe_ret = sys_pipe2(p.as_mut_ptr(), O_CLOEXEC);
8582    if pipe_ret < 0 {
8583        ERRNO!() = (-pipe_ret) as c_int;
8584        return core::ptr::null_mut();
8585    }
8586    let op = if m == b'r' as c_char { 0 } else { 1 };
8587    let child_fd = p[1 - op];
8588    let f = fdopen(p[op], mode);
8589    if f.is_null() { sys_close(p[0] as i64); sys_close(p[1] as i64); return core::ptr::null_mut(); }
8590    let pid = sys_fork();
8591    if pid < 0 {
8592        let e = (-pid) as c_int;
8593        fclose(f); sys_close(child_fd as i64);
8594        ERRNO!() = e;
8595        return core::ptr::null_mut();
8596    }
8597    if pid == 0 {
8598        sys_close(p[op] as i64);
8599        if child_fd != (1 - op) as c_int { sys_dup3(child_fd, (1 - op) as c_int, 0); sys_close(child_fd as i64); }
8600        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
8601        let argv = [b"sh\0".as_ptr() as *const c_char, b"-c\0".as_ptr() as *const c_char, cmd, core::ptr::null()];
8602        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
8603        _exit(127);
8604    }
8605    sys_close(child_fd as i64);
8606    (*f).pipe_pid = pid as c_int;
8607    f
8608}
8609
8610#[no_mangle]
8611pub unsafe extern "C" fn pclose(f: *mut FILE) -> c_int {
8612    if f.is_null() { ERRNO!() = EINVAL; return -1; }
8613    let pid = (*f).pipe_pid;
8614    if pid <= 0 { ERRNO!() = EINVAL; return -1; }
8615    let r = fclose(f);
8616    let mut status: c_int = 0;
8617    let w = loop {
8618        let w = waitpid(pid, &mut status, 0);
8619        if w >= 0 || ERRNO!() != EINTR { break w; }
8620    };
8621    if w < 0 || r != 0 { return -1; }
8622    status
8623}
8624
8625// ============================================================
8626// tmpfile / tmpnam / remove / rename
8627// ============================================================
8628
8629const L_TMPNAM: usize = 20;
8630static TMPNAM_COUNTER: AtomicU32 = AtomicU32::new(0);
8631
8632unsafe fn tmp_seed() -> c_uint {
8633    let mut ts: timespec = core::mem::zeroed();
8634    if sys_clock_gettime(CLOCK_REALTIME, &mut ts) < 0 {
8635        let mut v: u32 = 0;
8636        crate::getrandom(&mut v as *mut u32 as *mut u8, core::mem::size_of::<u32>(), 0);
8637        return v;
8638    }
8639    ts.tv_nsec as u32
8640}
8641
8642unsafe fn fill_tmpname(out: *mut c_char, seed: c_uint) {
8643    let prefix = b"/tmp/tmp\0";
8644    let mut k = 0;
8645    while k < prefix.len() - 1 { *out.add(k) = prefix[k] as c_char; k += 1; }
8646    let (buf, len) = format_hex(seed as u64, false);
8647    for j in 0..len.min(L_TMPNAM - k - 1) { *out.add(k + j) = buf[j] as c_char; k += 1; }
8648    *out.add(k) = 0;
8649}
8650
8651#[no_mangle]
8652pub unsafe extern "C" fn tmpfile() -> *mut FILE {
8653    let mut name = [0u8; L_TMPNAM];
8654    let mut ctr: c_uint = 0;
8655    loop {
8656        ctr = ctr.wrapping_add(1);
8657        let seed = tmp_seed().wrapping_add(ctr);
8658        fill_tmpname(name.as_mut_ptr() as *mut c_char, seed);
8659        let fd = sys_open(name.as_ptr(), (O_RDWR | O_CREAT | O_EXCL) as i64, 0o600);
8660        if fd >= 0 {
8661            sys_unlinkat(AT_FDCWD, name.as_ptr(), 0);
8662            let f = fdopen(fd as c_int, b"w+\0".as_ptr() as *const c_char);
8663            if f.is_null() { sys_close(fd); }
8664            return f;
8665        }
8666        if ctr > 100 { return core::ptr::null_mut(); }
8667    }
8668}
8669
8670#[no_mangle]
8671pub unsafe extern "C" fn tmpnam(s: *mut c_char) -> *mut c_char {
8672    static mut BUF: [c_char; L_TMPNAM] = [0; L_TMPNAM];
8673    let out = if s.is_null() { core::ptr::addr_of_mut!(BUF) as *mut c_char } else { s };
8674    let counter = TMPNAM_COUNTER.fetch_add(1, Ordering::Relaxed);
8675    let seed = tmp_seed().wrapping_add(counter);
8676    fill_tmpname(out, seed);
8677    out
8678}
8679
8680#[no_mangle]
8681pub unsafe extern "C" fn remove(path: *const c_char) -> c_int {
8682    if path.is_null() { ERRNO!() = EINVAL; return -1; }
8683    let r = sys_unlinkat(AT_FDCWD, path as *const u8, 0);
8684    if r == 0 {
8685        return 0;
8686    }
8687    // POSIX remove() also removes directories; musl falls back to rmdir only
8688    // when unlink reports EISDIR.
8689    if (-r) as c_int == 21 {
8690        return rmdir(path);
8691    }
8692    ERRNO!() = (-r) as c_int;
8693    -1
8694}
8695
8696#[no_mangle]
8697pub unsafe extern "C" fn rename(old: *const c_char, new_: *const c_char) -> c_int {
8698    if old.is_null() || new_.is_null() { ERRNO!() = EINVAL; return -1; }
8699    let r = sys_renameat2(AT_FDCWD, old as *const u8, AT_FDCWD, new_ as *const u8, 0);
8700    if r == 0 { 0 } else { ERRNO!() = (-r) as c_int; -1 }
8701}
8702
8703// ============================================================
8704// Allocator basics
8705// ============================================================
8706
8707const MMAP_FAILED: *mut u8 = !0usize as *mut u8;
8708const PAGE: usize = 4096;
8709
8710// ============================================================
8711// Process: exit / _exit / _Exit
8712// ============================================================
8713
8714#[no_mangle]
8715pub unsafe extern "C" fn _exit(code: c_int) -> ! {
8716    sys_exit_group(code)
8717}
8718
8719#[inline]
8720unsafe fn sys_exit_group(code: c_int) -> ! {
8721    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT_GROUP, code as i64)
8722}
8723
8724#[inline]
8725unsafe fn sys_exit_thread(code: c_int) -> ! {
8726    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT, code as i64)
8727}
8728
8729#[no_mangle]
8730pub unsafe extern "C" fn _Exit(code: c_int) -> ! {
8731    _exit(code);
8732}
8733
8734#[no_mangle]
8735pub unsafe extern "C" fn exit(code: c_int) -> ! {
8736    fflush(core::ptr::null_mut());
8737    __funcs_on_exit();
8738    _exit(code);
8739}
8740
8741#[no_mangle]
8742pub unsafe extern "C" fn abort() -> ! {
8743    raise(6); // SIGABRT
8744    _exit(128 + 6);
8745}
8746
8747// aarch64 GCC accesses the stack canary via the global __stack_chk_guard
8748// symbol (GOT-based for PIE). Export it so the dynamic linker can resolve it.
8749#[no_mangle]
8750pub static mut __stack_chk_guard: usize = 0;
8751
8752#[no_mangle]
8753pub unsafe extern "C" fn __stack_chk_fail() -> ! {
8754    const MSG: &[u8] = b"*** stack smashing detected ***: terminated\n";
8755    let _ = sys_write(2, MSG.as_ptr(), MSG.len());
8756    abort();
8757}
8758
8759#[no_mangle]
8760pub unsafe extern "C" fn __stack_chk_fail_local() -> ! {
8761    __stack_chk_fail()
8762}
8763
8764// ============================================================
8765// qsort / qsort_r (smoothsort, O(1) aux, adaptive)
8766// ============================================================
8767
8768type CmpRfn = unsafe extern "C" fn(*const c_void, *const c_void, *mut c_void) -> c_int;
8769
8770const AR_LEN: usize = 16 * core::mem::size_of::<usize>();
8771const AR_MASK: usize = AR_LEN - 1;
8772
8773unsafe fn qsort_pntz(p: &[usize; 2]) -> i32 {
8774    if p[0] != 1 {
8775        p[0].wrapping_sub(1).trailing_zeros() as i32
8776    } else if p[1] != 0 {
8777        (8 * core::mem::size_of::<usize>()) as i32 + p[1].trailing_zeros() as i32
8778    } else {
8779        0
8780    }
8781}
8782
8783unsafe fn qsort_cycle(width: usize, ar: &mut [*mut u8; AR_LEN], n: usize) {
8784    if n < 2 { return; }
8785    let mut tmp = [0u8; 256];
8786    ar[n] = tmp.as_mut_ptr();
8787    let mut w = width;
8788    while w > 0 {
8789        let l = if 256 < w { 256 } else { w };
8790        core::ptr::copy_nonoverlapping(ar[0], ar[n], l);
8791        for i in 0..n {
8792            core::ptr::copy_nonoverlapping(ar[i + 1], ar[i], l);
8793            ar[i] = ar[i].add(l);
8794        }
8795        w -= l;
8796    }
8797}
8798
8799unsafe fn qsort_shl(p: &mut [usize; 2], n: i32) {
8800    let bits = (8 * core::mem::size_of::<usize>()) as i32;
8801    if n >= bits {
8802        p[1] = p[0];
8803        p[0] = 0;
8804        let n = n - bits;
8805        if n == 0 { return; }
8806    }
8807    p[1] = (p[1] << n) | (p[0] >> (bits - n));
8808    p[0] <<= n;
8809}
8810
8811unsafe fn qsort_shr(p: &mut [usize; 2], n: i32) {
8812    let bits = (8 * core::mem::size_of::<usize>()) as i32;
8813    if n >= bits {
8814        p[0] = p[1];
8815        p[1] = 0;
8816        let n = n - bits;
8817        if n == 0 { return; }
8818    }
8819    p[0] = (p[0] >> n) | (p[1] << (bits - n));
8820    p[1] >>= n;
8821}
8822
8823unsafe fn qsort_sift(
8824    head: *mut u8, width: usize,
8825    cmp: CmpRfn, arg: *mut c_void,
8826    pshift: i32, lp: &[usize],
8827) {
8828    let mut ar: [*mut u8; AR_LEN] = [core::ptr::null_mut(); AR_LEN];
8829    ar[0] = head;
8830    let mut i = 1usize;
8831    let mut h = head;
8832    let mut ps = pshift;
8833
8834    while ps > 1 {
8835        let rt = h.sub(width);
8836        let lf = h.sub(width + lp[(ps - 2) as usize]);
8837
8838        if cmp(ar[0] as *const c_void, lf as *const c_void, arg) >= 0
8839            && cmp(ar[0] as *const c_void, rt as *const c_void, arg) >= 0
8840        {
8841            break;
8842        }
8843        if cmp(lf as *const c_void, rt as *const c_void, arg) >= 0 {
8844            ar[i & AR_MASK] = lf;
8845            i += 1;
8846            h = lf;
8847            ps -= 1;
8848        } else {
8849            ar[i & AR_MASK] = rt;
8850            i += 1;
8851            h = rt;
8852            ps -= 2;
8853        }
8854    }
8855    qsort_cycle(width, &mut ar, i & AR_MASK);
8856}
8857
8858unsafe fn qsort_trinkle(
8859    head: *mut u8, width: usize,
8860    cmp: CmpRfn, arg: *mut c_void,
8861    pp: &[usize; 2], pshift: i32, trusty: i32,
8862    lp: &[usize],
8863) {
8864    let mut ar: [*mut u8; AR_LEN] = [core::ptr::null_mut(); AR_LEN];
8865    let mut p = *pp;
8866    ar[0] = head;
8867    let mut i = 1usize;
8868    let mut h = head;
8869    let mut ps = pshift;
8870    let mut t = trusty;
8871
8872    while p[0] != 1 || p[1] != 0 {
8873        let stepson = h.sub(lp[ps as usize]);
8874        if cmp(stepson as *const c_void, ar[0] as *const c_void, arg) <= 0 {
8875            break;
8876        }
8877        if t == 0 && ps > 1 {
8878            let rt = h.sub(width);
8879            let lf = h.sub(width + lp[(ps - 2) as usize]);
8880            if cmp(rt as *const c_void, stepson as *const c_void, arg) >= 0
8881                || cmp(lf as *const c_void, stepson as *const c_void, arg) >= 0
8882            {
8883                break;
8884            }
8885        }
8886
8887        ar[i & AR_MASK] = stepson;
8888        i += 1;
8889        h = stepson;
8890        let trail = qsort_pntz(&p);
8891        qsort_shr(&mut p, trail);
8892        ps += trail;
8893        t = 0;
8894    }
8895    if t == 0 {
8896        qsort_cycle(width, &mut ar, i & AR_MASK);
8897        qsort_sift(h, width, cmp, arg, ps, lp);
8898    }
8899}
8900
8901#[no_mangle]
8902pub unsafe extern "C" fn __qsort_r(
8903    base: *mut c_void,
8904    nel: usize,
8905    width: usize,
8906    cmp: CmpRfn,
8907    arg: *mut c_void,
8908) {
8909    let size = match width.checked_mul(nel) {
8910        Some(v) => v,
8911        None => return,
8912    };
8913    if size == 0 { return; }
8914
8915    let mut lp = [0usize; 96];
8916    lp[0] = width;
8917    lp[1] = width;
8918    let mut li = 2;
8919    while li + 1 < lp.len() {
8920        lp[li] = match lp[li - 2]
8921            .checked_add(lp[li - 1])
8922            .and_then(|v| v.checked_add(width))
8923        {
8924            Some(v) => v,
8925            None => break,
8926        };
8927        if lp[li] >= size { break; }
8928        li += 1;
8929    }
8930
8931    let mut head = base as *mut u8;
8932    let high = head.add(size - width);
8933    let mut p: [usize; 2] = [1, 0];
8934    let mut pshift: i32 = 1;
8935
8936    while head < high {
8937        if (p[0] & 3) == 3 {
8938            qsort_sift(head, width, cmp, arg, pshift, &lp);
8939            qsort_shr(&mut p, 2);
8940            pshift += 2;
8941        } else {
8942            if lp[(pshift - 1) as usize] >= (high as usize) - (head as usize) {
8943                qsort_trinkle(head, width, cmp, arg, &p, pshift, 0, &lp);
8944            } else {
8945                qsort_sift(head, width, cmp, arg, pshift, &lp);
8946            }
8947
8948            if pshift == 1 {
8949                qsort_shl(&mut p, 1);
8950                pshift = 0;
8951            } else {
8952                qsort_shl(&mut p, pshift - 1);
8953                pshift = 1;
8954            }
8955        }
8956
8957        p[0] |= 1;
8958        head = head.add(width);
8959    }
8960
8961    qsort_trinkle(head, width, cmp, arg, &p, pshift, 0, &lp);
8962
8963    while pshift != 1 || p[0] != 1 || p[1] != 0 {
8964        if pshift <= 1 {
8965            let trail = qsort_pntz(&p);
8966            qsort_shr(&mut p, trail);
8967            pshift += trail;
8968        } else {
8969            qsort_shl(&mut p, 2);
8970            pshift -= 2;
8971            p[0] ^= 7;
8972            qsort_shr(&mut p, 1);
8973            qsort_trinkle(
8974                head.sub(lp[pshift as usize] + width),
8975                width, cmp, arg, &p, pshift + 1, 1, &lp,
8976            );
8977            qsort_shl(&mut p, 1);
8978            p[0] |= 1;
8979            qsort_trinkle(head.sub(width), width, cmp, arg, &p, pshift, 1, &lp);
8980        }
8981        head = head.sub(width);
8982    }
8983}
8984
8985#[no_mangle]
8986pub unsafe extern "C" fn qsort_r(
8987    base: *mut c_void,
8988    nel: usize,
8989    width: usize,
8990    cmp: CmpRfn,
8991    arg: *mut c_void,
8992) {
8993    __qsort_r(base, nel, width, cmp, arg);
8994}
8995
8996unsafe extern "C" fn qsort_wrap_cmp(
8997    a: *const c_void,
8998    b: *const c_void,
8999    cmp_ctx: *mut c_void,
9000) -> c_int {
9001    let cmp: CmpFn = core::mem::transmute(cmp_ctx);
9002    cmp(a, b)
9003}
9004
9005#[no_mangle]
9006pub unsafe extern "C" fn qsort(
9007    base: *mut c_void,
9008    nel: usize,
9009    width: usize,
9010    cmp: CmpFn,
9011) {
9012    __qsort_r(base, nel, width, qsort_wrap_cmp, cmp as *mut c_void);
9013}
9014
9015// ============================================================
9016// atexit / __cxa_atexit / __funcs_on_exit
9017// ============================================================
9018
9019const ATEXIT_COUNT: usize = 32;
9020
9021#[repr(C)]
9022struct AtExitBlock {
9023    next: *mut AtExitBlock,
9024    f: [Option<unsafe extern "C" fn(*mut c_void)>; ATEXIT_COUNT],
9025    a: [*mut c_void; ATEXIT_COUNT],
9026}
9027
9028static mut ATEXIT_BUILTIN: AtExitBlock = AtExitBlock {
9029    next: core::ptr::null_mut(),
9030    f: [None; ATEXIT_COUNT],
9031    a: [core::ptr::null_mut(); ATEXIT_COUNT],
9032};
9033static mut ATEXIT_HEAD: *mut AtExitBlock = core::ptr::null_mut();
9034static mut ATEXIT_SLOT: usize = 0;
9035static mut ATEXIT_FINISHED: bool = false;
9036
9037#[no_mangle]
9038pub unsafe extern "C" fn __funcs_on_exit() {
9039    while !ATEXIT_HEAD.is_null() {
9040        let head = ATEXIT_HEAD;
9041        while ATEXIT_SLOT > 0 {
9042            ATEXIT_SLOT -= 1;
9043            if let Some(f) = (*head).f[ATEXIT_SLOT] {
9044                let a = (*head).a[ATEXIT_SLOT];
9045                f(a);
9046            }
9047        }
9048        ATEXIT_HEAD = (*head).next;
9049        ATEXIT_SLOT = ATEXIT_COUNT;
9050    }
9051    ATEXIT_FINISHED = true;
9052}
9053
9054#[no_mangle]
9055pub unsafe extern "C" fn __cxa_atexit(
9056    func: unsafe extern "C" fn(*mut c_void),
9057    arg: *mut c_void,
9058    _dso: *mut c_void,
9059) -> c_int {
9060    if ATEXIT_FINISHED {
9061        return -1;
9062    }
9063    if ATEXIT_HEAD.is_null() {
9064        ATEXIT_HEAD = core::ptr::addr_of_mut!(ATEXIT_BUILTIN);
9065    }
9066    if ATEXIT_SLOT == ATEXIT_COUNT {
9067        let new = calloc(1, core::mem::size_of::<AtExitBlock>()) as *mut AtExitBlock;
9068        if new.is_null() {
9069            return -1;
9070        }
9071        (*new).next = ATEXIT_HEAD;
9072        ATEXIT_HEAD = new;
9073        ATEXIT_SLOT = 0;
9074    }
9075    (*ATEXIT_HEAD).f[ATEXIT_SLOT] = Some(func);
9076    (*ATEXIT_HEAD).a[ATEXIT_SLOT] = arg;
9077    ATEXIT_SLOT += 1;
9078    0
9079}
9080
9081unsafe extern "C" fn atexit_caller(arg: *mut c_void) {
9082    let func: unsafe extern "C" fn() = core::mem::transmute(arg);
9083    func();
9084}
9085
9086#[no_mangle]
9087pub unsafe extern "C" fn atexit(func: unsafe extern "C" fn()) -> c_int {
9088    __cxa_atexit(atexit_caller, func as *mut c_void, core::ptr::null_mut())
9089}
9090
9091#[no_mangle]
9092pub unsafe extern "C" fn __cxa_finalize(_dso: *mut c_void) {
9093    // Modules are never unloaded (dlclose is a no-op), so there is nothing
9094    // to finalize here.
9095}
9096
9097// ============================================================
9098// getenv / setenv / putenv / unsetenv / clearenv
9099// ============================================================
9100
9101#[no_mangle]
9102pub static mut __environ: *mut *mut c_char = core::ptr::null_mut();
9103
9104// Growable tracking of strings allocated by setenv/putenv.  Realloc keeps
9105// this unbounded; if it fails the new string is simply left untracked.
9106static mut ENV_ALLOCED: *mut *mut c_char = core::ptr::null_mut();
9107static mut ENV_ALLOCED_N: usize = 0;
9108static mut ENV_ALLOCED_CAP: usize = 0;
9109
9110unsafe fn env_rm_add(old: *mut c_char, mut new: *mut c_char) {
9111    for i in 0..ENV_ALLOCED_N {
9112        if (*ENV_ALLOCED.add(i)) == old {
9113            *ENV_ALLOCED.add(i) = new;
9114            if !old.is_null() {
9115                free(old as *mut c_void);
9116            }
9117            return;
9118        } else if (*ENV_ALLOCED.add(i)).is_null() && !new.is_null() {
9119            *ENV_ALLOCED.add(i) = new;
9120            new = core::ptr::null_mut();
9121        }
9122    }
9123    if !new.is_null() {
9124        if ENV_ALLOCED_N == ENV_ALLOCED_CAP {
9125            let new_cap = if ENV_ALLOCED_CAP == 0 { 16 } else { ENV_ALLOCED_CAP * 2 };
9126            let grown = realloc(
9127                ENV_ALLOCED as *mut c_void,
9128                new_cap * core::mem::size_of::<*mut c_char>(),
9129            ) as *mut *mut c_char;
9130            if grown.is_null() {
9131                return;
9132            }
9133            ENV_ALLOCED = grown;
9134            ENV_ALLOCED_CAP = new_cap;
9135        }
9136        *ENV_ALLOCED.add(ENV_ALLOCED_N) = new;
9137        ENV_ALLOCED_N += 1;
9138    }
9139}
9140
9141unsafe fn strchrnul_u8(s: *const u8, c: u8) -> *const u8 {
9142    let mut p = s;
9143    while *p != 0 && *p != c {
9144        p = p.add(1);
9145    }
9146    p
9147}
9148
9149#[no_mangle]
9150pub unsafe extern "C" fn getenv(name: *const c_char) -> *mut c_char {
9151    if __environ.is_null() || name.is_null() {
9152        return core::ptr::null_mut();
9153    }
9154    let name = name as *const u8;
9155    let l = strchrnul_u8(name, b'=') as usize - name as usize;
9156    if l == 0 || *name.add(l) != 0 {
9157        return core::ptr::null_mut();
9158    }
9159    let mut e = __environ;
9160    while !(*e).is_null() {
9161        let entry = *e as *const u8;
9162        if strncmp(entry, name, l) == 0 && *entry.add(l) == b'=' {
9163            return entry.add(l + 1) as *mut c_char;
9164        }
9165        e = e.add(1);
9166    }
9167    core::ptr::null_mut()
9168}
9169
9170#[no_mangle]
9171pub unsafe extern "C" fn setenv(
9172    var: *const c_char,
9173    value: *const c_char,
9174    overwrite: c_int,
9175) -> c_int {
9176    if var.is_null() || value.is_null() {
9177        ERRNO!() = EINVAL;
9178        return -1;
9179    }
9180    let var = var as *const u8;
9181    let l1 = strchrnul_u8(var, b'=') as usize - var as usize;
9182    if l1 == 0 || *var.add(l1) != 0 {
9183        ERRNO!() = EINVAL;
9184        return -1;
9185    }
9186    if overwrite == 0 && !getenv(var as *const c_char).is_null() {
9187        return 0;
9188    }
9189    let l2 = strlen(value as *const c_char);
9190    let s = malloc(l1 + l2 + 2) as *mut u8;
9191    if s.is_null() {
9192        return -1;
9193    }
9194    core::ptr::copy_nonoverlapping(var, s, l1);
9195    *s.add(l1) = b'=';
9196    core::ptr::copy_nonoverlapping(value as *const u8, s.add(l1 + 1), l2 + 1);
9197    putenv_internal(s as *mut c_char, l1, s as *mut c_char)
9198}
9199
9200unsafe fn putenv_internal(s: *mut c_char, l: usize, r: *mut c_char) -> c_int {
9201    let mut i = 0;
9202    if !__environ.is_null() {
9203        let mut e = __environ;
9204        while !(*e).is_null() {
9205            if strncmp(s as *const u8, *e as *const u8, l + 1) == 0 {
9206                let tmp = *e;
9207                *e = s;
9208                env_rm_add(tmp, r);
9209                return 0;
9210            }
9211            e = e.add(1);
9212            i += 1;
9213        }
9214    }
9215    let newenv = malloc(core::mem::size_of::<*mut c_char>() * (i + 2)) as *mut *mut c_char;
9216    if newenv.is_null() {
9217        if !r.is_null() { free(r as *mut c_void); }
9218        return -1;
9219    }
9220    if i > 0 && !__environ.is_null() {
9221        core::ptr::copy_nonoverlapping(__environ, newenv, i);
9222    }
9223    *newenv.add(i) = s;
9224    *newenv.add(i + 1) = core::ptr::null_mut();
9225    // don't free old __environ (may not be from our malloc)
9226    __environ = newenv;
9227    environ = __environ;
9228    if !r.is_null() {
9229        env_rm_add(core::ptr::null_mut(), r);
9230    }
9231    0
9232}
9233
9234#[no_mangle]
9235pub unsafe extern "C" fn putenv(s: *mut c_char) -> c_int {
9236    if s.is_null() { return -1; }
9237    let l = strchrnul_u8(s as *const u8, b'=') as usize - s as *const u8 as usize;
9238    if l == 0 || *s.add(l) as u8 == 0 {
9239        return unsetenv(s);
9240    }
9241    putenv_internal(s, l, core::ptr::null_mut())
9242}
9243
9244#[no_mangle]
9245pub unsafe extern "C" fn unsetenv(name: *const c_char) -> c_int {
9246    if name.is_null() {
9247        ERRNO!() = EINVAL;
9248        return -1;
9249    }
9250    let name = name as *const u8;
9251    let l = strchrnul_u8(name, b'=') as usize - name as usize;
9252    if l == 0 || *name.add(l) != 0 {
9253        ERRNO!() = EINVAL;
9254        return -1;
9255    }
9256    if __environ.is_null() {
9257        return 0;
9258    }
9259    let mut e = __environ;
9260    let mut eo = e;
9261    while !(*e).is_null() {
9262        if strncmp(name, *e as *const u8, l) == 0 && *(*e as *const u8).add(l) == b'=' {
9263            env_rm_add(*e, core::ptr::null_mut());
9264        } else {
9265            if eo != e {
9266                *eo = *e;
9267            }
9268            eo = eo.add(1);
9269        }
9270        e = e.add(1);
9271    }
9272    if eo != e {
9273        *eo = core::ptr::null_mut();
9274    }
9275    environ = __environ;
9276    0
9277}
9278
9279#[no_mangle]
9280pub unsafe extern "C" fn clearenv() -> c_int {
9281    let e = __environ;
9282    __environ = core::ptr::null_mut();
9283    environ = core::ptr::null_mut();
9284    if !e.is_null() {
9285        let mut p = e;
9286        while !(*p).is_null() {
9287            env_rm_add(*p, core::ptr::null_mut());
9288            p = p.add(1);
9289        }
9290    }
9291    0
9292}
9293
9294// ============================================================
9295// random / srandom / initstate / setstate (BSD lagged fibonacci)
9296// musl serializes the process-global state with a lock; keel currently
9297// does not, so concurrent callers must provide their own serialization.
9298// ============================================================
9299
9300static mut RANDOM_INIT: [u32; 32] = [
9301    0x00000000,0x5851f42d,0xc0b18ccf,0xcbb5f646,
9302    0xc7033129,0x30705b04,0x20fd5db4,0x9a8b7f78,
9303    0x502959d8,0xab894868,0x6c0356a7,0x88cdb7ff,
9304    0xb477d43f,0x70a3a52b,0xa8e4baf1,0xfd8341fc,
9305    0x8ae16fd9,0x742d2f7a,0x0d1f0796,0x76035e09,
9306    0x40f7702c,0x6fa72ca5,0xaaa84157,0x58a0df74,
9307    0xc74a0364,0xae533cc4,0x04185faf,0x6de3b115,
9308    0x0cab8628,0xf043bfa4,0x398150e9,0x37521657,
9309];
9310
9311static mut RANDOM_N: i32 = 31;
9312static mut RANDOM_I: i32 = 3;
9313static mut RANDOM_J: i32 = 0;
9314static mut RANDOM_X: *mut u32 = unsafe { core::ptr::addr_of_mut!(RANDOM_INIT).cast::<u32>().add(1) };
9315
9316unsafe fn random_lcg31(x: u32) -> u32 {
9317    (1103515245u32.wrapping_mul(x).wrapping_add(12345)) & 0x7fffffff
9318}
9319
9320unsafe fn random_lcg64(x: u64) -> u64 {
9321    6364136223846793005u64.wrapping_mul(x).wrapping_add(1)
9322}
9323
9324unsafe fn random_savestate() -> *mut u8 {
9325    (*RANDOM_X.offset(-1)) = ((RANDOM_N as u32) << 16) | ((RANDOM_I as u32) << 8) | (RANDOM_J as u32);
9326    RANDOM_X.offset(-1) as *mut u8
9327}
9328
9329unsafe fn random_loadstate(state: *mut u32) {
9330    RANDOM_X = state.add(1);
9331    RANDOM_N = ((*RANDOM_X.offset(-1)) >> 16) as i32;
9332    RANDOM_I = (((*RANDOM_X.offset(-1)) >> 8) & 0xff) as i32;
9333    RANDOM_J = ((*RANDOM_X.offset(-1)) & 0xff) as i32;
9334}
9335
9336unsafe fn random_srandom_inner(seed: u32) {
9337    let mut s = seed as u64;
9338    if RANDOM_N == 0 {
9339        *RANDOM_X = s as u32;
9340        return;
9341    }
9342    RANDOM_I = if RANDOM_N == 31 || RANDOM_N == 7 { 3 } else { 1 };
9343    RANDOM_J = 0;
9344    for k in 0..RANDOM_N as usize {
9345        s = random_lcg64(s);
9346        *RANDOM_X.add(k) = (s >> 32) as u32;
9347    }
9348    *RANDOM_X |= 1;
9349}
9350
9351#[no_mangle]
9352pub unsafe extern "C" fn srandom(seed: c_uint) {
9353    random_srandom_inner(seed);
9354}
9355
9356#[no_mangle]
9357pub unsafe extern "C" fn initstate(seed: c_uint, state: *mut c_char, size: usize) -> *mut c_char {
9358    if size < 8 { return core::ptr::null_mut(); }
9359    let old = random_savestate();
9360    RANDOM_N = if size < 32 { 0 }
9361        else if size < 64 { 7 }
9362        else if size < 128 { 15 }
9363        else if size < 256 { 31 }
9364        else { 63 };
9365    RANDOM_X = (state as *mut u32).add(1);
9366    random_srandom_inner(seed);
9367    random_savestate();
9368    old as *mut c_char
9369}
9370
9371#[no_mangle]
9372pub unsafe extern "C" fn setstate(state: *mut c_char) -> *mut c_char {
9373    let old = random_savestate();
9374    random_loadstate(state as *mut u32);
9375    old as *mut c_char
9376}
9377
9378#[no_mangle]
9379pub unsafe extern "C" fn random() -> c_long {
9380    let k: c_long;
9381    if RANDOM_N == 0 {
9382        *RANDOM_X = random_lcg31(*RANDOM_X);
9383        k = *RANDOM_X as c_long;
9384    } else {
9385        *RANDOM_X.add(RANDOM_I as usize) = (*RANDOM_X.add(RANDOM_I as usize)).wrapping_add(*RANDOM_X.add(RANDOM_J as usize));
9386        k = (*RANDOM_X.add(RANDOM_I as usize) >> 1) as c_long;
9387        RANDOM_I += 1;
9388        if RANDOM_I == RANDOM_N { RANDOM_I = 0; }
9389        RANDOM_J += 1;
9390        if RANDOM_J == RANDOM_N { RANDOM_J = 0; }
9391    }
9392    k
9393}
9394
9395// ============================================================
9396// multibyte (UTF-8, musl state machine)
9397// ============================================================
9398
9399const SA: u8 = 0xC2;
9400const SB: u8 = 0xF4;
9401
9402const BITTAB: [u32; 51] = [
9403    0xC000_0002, 0xC000_0003, 0xC000_0004, 0xC000_0005, 0xC000_0006, 0xC000_0007,
9404    0xC000_0008, 0xC000_0009, 0xC000_000A, 0xC000_000B, 0xC000_000C, 0xC000_000D,
9405    0xC000_000E, 0xC000_000F, 0xC000_0010, 0xC000_0011, 0xC000_0012, 0xC000_0013,
9406    0xC000_0014, 0xC000_0015, 0xC000_0016, 0xC000_0017, 0xC000_0018, 0xC000_0019,
9407    0xC000_001A, 0xC000_001B, 0xC000_001C, 0xC000_001D, 0xC000_001E, 0xC000_001F,
9408    0xB300_0000, 0xC300_0001, 0xC300_0002, 0xC300_0003, 0xC300_0004, 0xC300_0005,
9409    0xC300_0006, 0xC300_0007, 0xC300_0008, 0xC300_0009, 0xC300_000A, 0xC300_000B,
9410    0xC300_000C, 0xD300_000D, 0xC300_000E, 0xC300_000F, 0xBB0C_0000, 0xC30C_0001,
9411    0xC30C_0002, 0xC30C_0003, 0xDB0C_0004,
9412];
9413
9414#[inline]
9415fn mb_oob(c: u32, b: u8) -> u32 {
9416    let b3 = (b >> 3) as u32;
9417    ((b3.wrapping_sub(0x10)) | (b3.wrapping_add((c as i32 >> 26) as u32))) & !7
9418}
9419
9420static mut MB_STATE: c_uint = 0;
9421
9422const MB_CUR_MAX_VAL_UTF8: usize = 4;
9423const MB_CUR_MAX_VAL_C: usize = 1;
9424
9425#[no_mangle]
9426pub extern "C" fn __ctype_get_mb_cur_max() -> usize {
9427    unsafe { if LOCALE_CTYPE_UTF8 { MB_CUR_MAX_VAL_UTF8 } else { MB_CUR_MAX_VAL_C } }
9428}
9429
9430#[no_mangle]
9431pub unsafe extern "C" fn mbrtowc(
9432    wc: *mut c_int,
9433    src: *const c_char,
9434    n: usize,
9435    st: *mut c_uint,
9436) -> usize {
9437    let s = src as *const u8;
9438    let n0 = n;
9439    let mut dummy: c_int = 0;
9440    let wc = if wc.is_null() { &mut dummy } else { &mut *wc };
9441    let st: &mut c_uint = if st.is_null() { &mut *(&raw mut MB_STATE) } else { &mut *st };
9442
9443    let mut c: u32 = *st;
9444    let mut s = s;
9445    let mut n = n;
9446
9447    if s.is_null() {
9448        if c != 0 { *st = 0; ERRNO!() = EILSEQ; return !0usize; }
9449        return 0;
9450    }
9451
9452    if n == 0 { return !1usize; }
9453
9454    if unsafe { !LOCALE_CTYPE_UTF8 } {
9455        let b = *s;
9456        *wc = c_locale_codeunit(b) as c_int;
9457        return if b == 0 { 0 } else { 1 };
9458    }
9459
9460    if c == 0 {
9461        if *s < 0x80 {
9462            let r = if *s == 0 { 0 } else { 1 };
9463            *wc = *s as c_int;
9464            return r;
9465        }
9466        if (*s).wrapping_sub(SA) as u32 > (SB - SA) as u32 {
9467            *st = 0; ERRNO!() = EILSEQ; return !0usize;
9468        }
9469        c = BITTAB[*s as usize - SA as usize];
9470        s = s.add(1);
9471        n -= 1;
9472    }
9473
9474    if n > 0 {
9475        if mb_oob(c, *s) != 0 {
9476            *st = 0; ERRNO!() = EILSEQ; return !0usize;
9477        }
9478        loop {
9479            c = (c << 6) | (*s as u32).wrapping_sub(0x80);
9480            s = s.add(1);
9481            n -= 1;
9482            if c & (1u32 << 31) == 0 {
9483                *st = 0;
9484                *wc = c as c_int;
9485                return n0 - n;
9486            }
9487            if n == 0 { break; }
9488            if (*s).wrapping_sub(0x80) >= 0x40 {
9489                *st = 0; ERRNO!() = EILSEQ; return !0usize;
9490            }
9491        }
9492    }
9493
9494    *st = c;
9495    !1usize
9496}
9497
9498#[no_mangle]
9499pub unsafe extern "C" fn wcrtomb(
9500    s: *mut c_char,
9501    wc: c_int,
9502    _st: *mut c_uint,
9503) -> usize {
9504    if s.is_null() { return 1; }
9505    let wc_u = wc as u32;
9506    if unsafe { !LOCALE_CTYPE_UTF8 } {
9507        if wc_u < 0x80 {
9508            *s = wc as c_char;
9509            return 1;
9510        }
9511        if c_locale_is_codeunit(wc_u) {
9512            *s = (wc_u & 0xFF) as c_char;
9513            return 1;
9514        }
9515        ERRNO!() = EILSEQ;
9516        return !0usize;
9517    }
9518    if wc_u < 0x80 {
9519        *s = wc as c_char;
9520        return 1;
9521    }
9522    if wc_u < 0x800 {
9523        *s = (0xC0 | (wc_u >> 6)) as c_char;
9524        *s.add(1) = (0x80 | (wc_u & 0x3F)) as c_char;
9525        return 2;
9526    }
9527    if wc_u < 0xD800 || wc_u.wrapping_sub(0xE000) < 0x2000 {
9528        *s = (0xE0 | (wc_u >> 12)) as c_char;
9529        *s.add(1) = (0x80 | ((wc_u >> 6) & 0x3F)) as c_char;
9530        *s.add(2) = (0x80 | (wc_u & 0x3F)) as c_char;
9531        return 3;
9532    }
9533    if wc_u.wrapping_sub(0x10000) < 0x100000 {
9534        *s = (0xF0 | (wc_u >> 18)) as c_char;
9535        *s.add(1) = (0x80 | ((wc_u >> 12) & 0x3F)) as c_char;
9536        *s.add(2) = (0x80 | ((wc_u >> 6) & 0x3F)) as c_char;
9537        *s.add(3) = (0x80 | (wc_u & 0x3F)) as c_char;
9538        return 4;
9539    }
9540    ERRNO!() = EILSEQ;
9541    !0usize
9542}
9543
9544#[no_mangle]
9545pub unsafe extern "C" fn mblen(s: *const c_char, n: usize) -> c_int {
9546    if s.is_null() { return 0; }
9547    mbtowc(core::ptr::null_mut(), s, n)
9548}
9549
9550#[no_mangle]
9551pub unsafe extern "C" fn mbtowc(
9552    wc: *mut c_int,
9553    src: *const c_char,
9554    n: usize,
9555) -> c_int {
9556    if src.is_null() { return 0; }
9557    if n == 0 { ERRNO!() = EILSEQ; return -1; }
9558    let mut state: c_uint = 0;
9559    let mut w: c_int = 0;
9560    let r = mbrtowc(&mut w, src, n, &mut state);
9561    if r == !0usize { return -1; }
9562    if !wc.is_null() { *wc = w; }
9563    r as c_int
9564}
9565
9566#[no_mangle]
9567pub unsafe extern "C" fn wctomb(s: *mut c_char, wc: c_int) -> c_int {
9568    if s.is_null() { return 0; }
9569    wcrtomb(s, wc, core::ptr::null_mut()) as c_int
9570}
9571
9572#[no_mangle]
9573pub unsafe extern "C" fn mbsrtowcs(
9574    ws: *mut c_int,
9575    src: *mut *const c_char,
9576    wn: usize,
9577    st: *mut c_uint,
9578) -> usize {
9579    let st: &mut c_uint = if st.is_null() { &mut *(&raw mut MB_STATE) } else { &mut *st };
9580    let mut s = *src as *const u8;
9581    let wn0 = wn;
9582    let mut wn = wn;
9583
9584    if ws.is_null() {
9585        while *s != 0 {
9586            if *s < 0x80 {
9587                s = s.add(1);
9588                wn = wn.wrapping_sub(1);
9589                continue;
9590            }
9591            let mut wc: c_int = 0;
9592            let r = mbrtowc(&mut wc, s as *const c_char, 4, st);
9593            if r == !0usize { return !0usize; }
9594            if r == !1usize { return wn0 - wn; }
9595            s = s.add(r);
9596            wn = wn.wrapping_sub(1);
9597        }
9598        wn0 - wn
9599    } else {
9600        let mut w = ws;
9601        while wn > 0 {
9602            if *s < 0x80 {
9603                let c = *s as c_int;
9604                *w = c;
9605                if c == 0 {
9606                    *src = core::ptr::null();
9607                    return wn0 - wn;
9608                }
9609                w = w.add(1);
9610                s = s.add(1);
9611                wn -= 1;
9612                continue;
9613            }
9614            let mut wc: c_int = 0;
9615            let r = mbrtowc(&mut wc, s as *const c_char, 4, st);
9616            if r == !0usize {
9617                *src = s as *const c_char;
9618                return !0usize;
9619            }
9620            if r == !1usize {
9621                *src = s as *const c_char;
9622                return wn0 - wn;
9623            }
9624            *w = wc;
9625            w = w.add(1);
9626            s = s.add(r);
9627            wn -= 1;
9628        }
9629        *src = s as *const c_char;
9630        wn0 - wn
9631    }
9632}
9633
9634#[no_mangle]
9635pub unsafe extern "C" fn wcsrtombs(
9636    s: *mut c_char,
9637    ws: *mut *const c_int,
9638    n: usize,
9639    _st: *mut c_uint,
9640) -> usize {
9641    let mut w = *ws;
9642    let n0 = n;
9643    let mut n = n;
9644
9645    if s.is_null() {
9646        let mut count = 0usize;
9647        while *w != 0 {
9648            if (*w as u32) < 0x80 {
9649                count += 1;
9650            } else {
9651                let mut buf = [0u8; 4];
9652                let r = wcrtomb(buf.as_mut_ptr() as *mut c_char, *w, core::ptr::null_mut());
9653                if r == !0usize { return !0usize; }
9654                count += r;
9655            }
9656            w = w.add(1);
9657        }
9658        return count;
9659    }
9660
9661    let mut dst = s;
9662    while n > 0 {
9663        if (*w as u32) < 0x80 {
9664            *dst = *w as c_char;
9665            if *w == 0 {
9666                *ws = core::ptr::null();
9667                return n0 - n;
9668            }
9669            dst = dst.add(1);
9670            n -= 1;
9671        } else {
9672            let r = wcrtomb(dst, *w, core::ptr::null_mut());
9673            if r == !0usize {
9674                *ws = w;
9675                return !0usize;
9676            }
9677            if r > n {
9678                *ws = w;
9679                return n0 - n;
9680            }
9681            dst = dst.add(r);
9682            n -= r;
9683        }
9684        w = w.add(1);
9685    }
9686    *ws = w;
9687    n0
9688}
9689
9690#[no_mangle]
9691pub unsafe extern "C" fn mbstowcs(
9692    ws: *mut c_int,
9693    src: *const c_char,
9694    wn: usize,
9695) -> usize {
9696    let mut src_ptr = src;
9697    mbsrtowcs(ws, &mut src_ptr, wn, core::ptr::null_mut())
9698}
9699
9700#[no_mangle]
9701pub unsafe extern "C" fn wcstombs(
9702    s: *mut c_char,
9703    ws: *const c_int,
9704    n: usize,
9705) -> usize {
9706    let mut ws_ptr = ws;
9707    wcsrtombs(s, &mut ws_ptr, n, core::ptr::null_mut())
9708}
9709
9710// ============================================================
9711// wchar: btowc / wctob / mbsinit / mbrlen
9712// ============================================================
9713
9714// musl's C locale represents bytes >= 0x80 as the single-byte "code units"
9715// 0xDF80..0xDFFF so they are distinct from Unicode code points.
9716#[inline]
9717fn c_locale_codeunit(b: u8) -> u32 {
9718    0xdfff & (b as i8 as i32) as u32
9719}
9720
9721#[inline]
9722fn c_locale_is_codeunit(c: u32) -> bool {
9723    c.wrapping_sub(0xDF80) < 0x80
9724}
9725
9726#[no_mangle]
9727pub extern "C" fn btowc(c: c_int) -> wint_t {
9728    if c == -1 { return WEOF; }
9729    unsafe {
9730        if LOCALE_CTYPE_UTF8 {
9731            if (c as u32) < 128 { c as wint_t } else { WEOF }
9732        } else {
9733            c_locale_codeunit(c as u8) as wint_t
9734        }
9735    }
9736}
9737
9738#[no_mangle]
9739pub extern "C" fn wctob(c: wint_t) -> c_int {
9740    unsafe {
9741        if LOCALE_CTYPE_UTF8 {
9742            if c < 128 { c as c_int } else { -1 }
9743        } else if c < 128 {
9744            c as c_int
9745        } else if c_locale_is_codeunit(c) {
9746            (c & 0xFF) as c_int
9747        } else {
9748            -1
9749        }
9750    }
9751}
9752
9753#[no_mangle]
9754pub unsafe extern "C" fn mbsinit(s: *const c_uint) -> c_int {
9755    if s.is_null() || *s == 0 { 1 } else { 0 }
9756}
9757
9758#[no_mangle]
9759pub unsafe extern "C" fn mbrlen(s: *const c_char, n: usize, ps: *mut c_uint) -> usize {
9760    mbrtowc(core::ptr::null_mut(), s, n, ps)
9761}
9762
9763// ============================================================
9764// wchar: wide string functions
9765// ============================================================
9766
9767#[no_mangle]
9768pub unsafe extern "C" fn wcslen(s: *const wchar_t) -> usize {
9769    let mut len = 0;
9770    while *s.add(len) != 0 { len += 1; }
9771    len
9772}
9773
9774#[no_mangle]
9775pub unsafe extern "C" fn wcschr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
9776    let mut i = 0;
9777    loop {
9778        let ch = *s.add(i);
9779        if ch == c { return s.add(i) as *mut wchar_t; }
9780        if ch == 0 { return null_mut(); }
9781        i += 1;
9782    }
9783}
9784
9785#[no_mangle]
9786pub unsafe extern "C" fn wcsrchr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
9787    let mut i = 0;
9788    let mut last: *mut wchar_t = null_mut();
9789    loop {
9790        let ch = *s.add(i);
9791        if ch == c { last = s.add(i) as *mut wchar_t; }
9792        if ch == 0 { return last; }
9793        i += 1;
9794    }
9795}
9796
9797#[no_mangle]
9798pub unsafe extern "C" fn wcsstr(haystack: *const wchar_t, needle: *const wchar_t) -> *mut wchar_t {
9799    if *needle == 0 { return haystack as *mut wchar_t; }
9800    let mut i = 0;
9801    loop {
9802        let h = *haystack.add(i);
9803        if h == 0 { return null_mut(); }
9804        if h == *needle {
9805            let mut j = 0;
9806            loop {
9807                let n = *needle.add(j);
9808                if n == 0 { return haystack.add(i) as *mut wchar_t; }
9809                if *haystack.add(i + j) != n { break; }
9810                j += 1;
9811            }
9812        }
9813        i += 1;
9814    }
9815}
9816
9817#[no_mangle]
9818pub unsafe extern "C" fn wcscmp(s1: *const wchar_t, s2: *const wchar_t) -> c_int {
9819    let mut i = 0;
9820    loop {
9821        let a = *s1.add(i);
9822        let b = *s2.add(i);
9823        if a != b { return a - b; }
9824        if a == 0 { return 0; }
9825        i += 1;
9826    }
9827}
9828
9829#[no_mangle]
9830pub unsafe extern "C" fn wcsncmp(s1: *const wchar_t, s2: *const wchar_t, n: usize) -> c_int {
9831    let mut i = 0;
9832    while i < n {
9833        let a = *s1.add(i);
9834        let b = *s2.add(i);
9835        if a != b { return a - b; }
9836        if a == 0 { return 0; }
9837        i += 1;
9838    }
9839    0
9840}
9841
9842#[no_mangle]
9843pub unsafe extern "C" fn wcscpy(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
9844    let mut i = 0;
9845    loop {
9846        let c = *src.add(i);
9847        *dst.add(i) = c;
9848        if c == 0 { break; }
9849        i += 1;
9850    }
9851    dst
9852}
9853
9854#[no_mangle]
9855pub unsafe extern "C" fn wcsncpy(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
9856    let mut i = 0;
9857    while i < n && *src.add(i) != 0 { *dst.add(i) = *src.add(i); i += 1; }
9858    while i < n { *dst.add(i) = 0; i += 1; }
9859    dst
9860}
9861
9862#[no_mangle]
9863pub unsafe extern "C" fn wcscat(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
9864    let mut i = 0;
9865    while *dst.add(i) != 0 { i += 1; }
9866    let mut j = 0;
9867    loop {
9868        let c = *src.add(j);
9869        *dst.add(i + j) = c;
9870        if c == 0 { break; }
9871        j += 1;
9872    }
9873    dst
9874}
9875
9876#[no_mangle]
9877pub unsafe extern "C" fn wcsncat(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
9878    let mut i = 0;
9879    while *dst.add(i) != 0 { i += 1; }
9880    let mut j = 0;
9881    while j < n && *src.add(j) != 0 { *dst.add(i + j) = *src.add(j); j += 1; }
9882    *dst.add(i + j) = 0;
9883    dst
9884}
9885
9886#[no_mangle]
9887pub unsafe extern "C" fn wcsdup(s: *const wchar_t) -> *mut wchar_t {
9888    let len = wcslen(s);
9889    let p = malloc((len + 1) * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
9890    if p.is_null() { return null_mut(); }
9891    core::ptr::copy_nonoverlapping(s, p, len + 1);
9892    p
9893}
9894
9895#[no_mangle]
9896pub unsafe extern "C" fn wcsnlen(s: *const wchar_t, maxlen: usize) -> usize {
9897    let mut i = 0;
9898    while i < maxlen && *s.add(i) != 0 { i += 1; }
9899    i
9900}
9901
9902#[no_mangle]
9903pub unsafe extern "C" fn wcsspn(s: *const wchar_t, accept: *const wchar_t) -> usize {
9904    let mut i = 0;
9905    loop {
9906        let c = *s.add(i);
9907        if c == 0 { return i; }
9908        let mut found = false;
9909        let mut j = 0;
9910        loop {
9911            let a = *accept.add(j);
9912            if a == 0 { break; }
9913            if c == a { found = true; break; }
9914            j += 1;
9915        }
9916        if !found { return i; }
9917        i += 1;
9918    }
9919}
9920
9921#[no_mangle]
9922pub unsafe extern "C" fn wcscspn(s: *const wchar_t, reject: *const wchar_t) -> usize {
9923    let mut i = 0;
9924    loop {
9925        let c = *s.add(i);
9926        if c == 0 { return i; }
9927        let mut j = 0;
9928        loop {
9929            let r = *reject.add(j);
9930            if r == 0 { break; }
9931            if c == r { return i; }
9932            j += 1;
9933        }
9934        i += 1;
9935    }
9936}
9937
9938#[no_mangle]
9939pub unsafe extern "C" fn wcspbrk(s: *const wchar_t, accept: *const wchar_t) -> *mut wchar_t {
9940    let mut i = 0;
9941    loop {
9942        let c = *s.add(i);
9943        if c == 0 { return null_mut(); }
9944        let mut j = 0;
9945        loop {
9946            let a = *accept.add(j);
9947            if a == 0 { break; }
9948            if c == a { return s.add(i) as *mut wchar_t; }
9949            j += 1;
9950        }
9951        i += 1;
9952    }
9953}
9954
9955#[no_mangle]
9956pub unsafe extern "C" fn wcsxfrm(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> usize {
9957    let len = wcslen(src);
9958    if !dst.is_null() {
9959        let copy = if len < n { len } else { if n > 0 { n - 1 } else { 0 } };
9960        for i in 0..copy { *dst.add(i) = *src.add(i); }
9961        if n > 0 { *dst.add(copy) = 0; }
9962    }
9963    len
9964}
9965
9966// ============================================================
9967// wchar: wcsto* number conversions
9968// ============================================================
9969
9970unsafe fn wcs_to_bytes(ws: *const wchar_t, buf: *mut u8, bufsz: usize) -> usize {
9971    let mut i = 0;
9972    while i < bufsz - 1 {
9973        let c = *ws.add(i);
9974        if c == 0 { break; }
9975        if (c as u32) > 127 { break; }
9976        *buf.add(i) = c as u8;
9977        i += 1;
9978    }
9979    *buf.add(i) = 0;
9980    i
9981}
9982
9983macro_rules! wcsto_int {
9984    ($name:ident, $ret:ty, $conv:ident) => {
9985        #[no_mangle]
9986        pub unsafe extern "C" fn $name(
9987            s: *const wchar_t,
9988            endptr: *mut *mut wchar_t,
9989            base: c_int,
9990        ) -> $ret {
9991            let cap = wcslen(s).saturating_add(1);
9992            let heap = cap > 256;
9993            let mut stack = [0u8; 256];
9994            let buf = if heap {
9995                crate::malloc(cap) as *mut u8
9996            } else {
9997                stack.as_mut_ptr()
9998            };
9999            if buf.is_null() {
10000                ERRNO!() = ENOMEM;
10001                return 0;
10002            }
10003            wcs_to_bytes(s, buf, cap);
10004            let mut end: *mut c_char = core::ptr::null_mut();
10005            let r = $conv(buf as *const c_char, &mut end, base);
10006            if !endptr.is_null() {
10007                let offset = end as usize - buf as usize;
10008                *endptr = s.add(offset) as *mut wchar_t;
10009            }
10010            if heap {
10011                crate::free(buf as *mut c_void);
10012            }
10013            r
10014        }
10015    };
10016}
10017
10018wcsto_int!(wcstol, c_long, strtol);
10019wcsto_int!(wcstoul, c_ulong, strtoul);
10020wcsto_int!(wcstoll, c_longlong, strtoll);
10021wcsto_int!(wcstoull, c_ulonglong, strtoull);
10022
10023#[no_mangle]
10024pub unsafe extern "C" fn wcstod(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 {
10025    let cap = wcslen(s).saturating_add(1);
10026    let heap = cap > 256;
10027    let mut stack = [0u8; 256];
10028    let buf = if heap {
10029        crate::malloc(cap) as *mut u8
10030    } else {
10031        stack.as_mut_ptr()
10032    };
10033    if buf.is_null() {
10034        ERRNO!() = ENOMEM;
10035        return 0.0;
10036    }
10037    wcs_to_bytes(s, buf, cap);
10038    let mut end: *mut c_char = core::ptr::null_mut();
10039    let r = strtod(buf as *const c_char, &mut end);
10040    if !endptr.is_null() {
10041        let offset = end as usize - buf as usize;
10042        *endptr = s.add(offset) as *mut wchar_t;
10043    }
10044    if heap {
10045        crate::free(buf as *mut c_void);
10046    }
10047    r
10048}
10049
10050#[no_mangle]
10051pub unsafe extern "C" fn wcstof(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f32 { wcstod(s, endptr) as f32 }
10052
10053#[no_mangle]
10054#[cfg(target_arch = "x86_64")]
10055pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 { wcstod(s, endptr) }
10056
10057#[no_mangle]
10058#[cfg(target_arch = "aarch64")]
10059pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { wcstod(s, endptr) as f128 }
10060
10061#[no_mangle]
10062#[cfg(target_arch = "riscv64")]
10063pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { wcstod(s, endptr) as f128 }
10064
10065#[no_mangle]
10066pub unsafe extern "C" fn wcstoimax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_longlong { wcstoll(s, endptr, base) }
10067
10068#[no_mangle]
10069pub unsafe extern "C" fn wcstoumax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulonglong { wcstoull(s, endptr, base) }
10070
10071// ============================================================
10072// wctype: classification functions
10073// ============================================================
10074
10075const WC_ALPHA: c_int = 1;
10076const WC_DIGIT: c_int = 2;
10077const WC_SPACE: c_int = 4;
10078const WC_UPPER: c_int = 8;
10079const WC_LOWER: c_int = 16;
10080const WC_ALNUM: c_int = WC_ALPHA | WC_DIGIT;
10081const WC_BLANK: c_int = 32;
10082const WC_CNTRL: c_int = 64;
10083const WC_PUNCT: c_int = 128;
10084const WC_GRAPH: c_int = WC_ALNUM | WC_PUNCT;
10085const WC_PRINT: c_int = WC_GRAPH | WC_BLANK;
10086const WC_XDIGIT: c_int = 256;
10087
10088#[inline]
10089fn wctable_bit(table: &[u8], wc: wint_t) -> bool {
10090    let wc = wc as u32;
10091    let page = table[(wc >> 8) as usize] as usize;
10092    (table[page * 32 + ((wc & 255) >> 3) as usize] >> (wc & 7)) & 1 != 0
10093}
10094
10095/// Port of musl's iswalpha: table lookup below U+20000, then a broad
10096/// alphabetic range up to U+2FFFD.
10097#[no_mangle]
10098pub extern "C" fn iswalpha(c: wint_t) -> c_int {
10099    let wc = c as u32;
10100    if wc < 0x20000 {
10101        return wctable_bit(&WCTYPE_ALPHA_TABLE, c) as c_int;
10102    }
10103    if wc < 0x2fffe { 1 } else { 0 }
10104}
10105
10106/// Port of musl's iswpunct.
10107#[no_mangle]
10108pub extern "C" fn iswpunct(c: wint_t) -> c_int {
10109    let wc = c as u32;
10110    if wc < 0x20000 {
10111        wctable_bit(&WCTYPE_PUNCT_TABLE, c) as c_int
10112    } else {
10113        0
10114    }
10115}
10116
10117/// Port of musl's iswprint.
10118#[no_mangle]
10119pub extern "C" fn iswprint(c: wint_t) -> c_int {
10120    let wc = c as u32;
10121    if wc < 0xff {
10122        return (((wc + 1) & 0x7f) >= 0x21) as c_int;
10123    }
10124    if wc < 0x2028
10125        || wc.wrapping_sub(0x202a) < 0xd800 - 0x202a
10126        || wc.wrapping_sub(0xe000) < 0xfff9 - 0xe000
10127    {
10128        return 1;
10129    }
10130    if wc.wrapping_sub(0xfffc) > 0x10ffff - 0xfffc || (wc & 0xfffe) == 0xfffe {
10131        return 0;
10132    }
10133    1
10134}
10135
10136/// Port of musl's iswspace: Unicode White_Space minus U+00A0/U+2007/U+202F,
10137/// plus U+1680 and U+180E are excluded (they have non-blank glyphs).
10138#[no_mangle]
10139pub extern "C" fn iswspace(c: wint_t) -> c_int {
10140    matches!(
10141        c as u32,
10142        0x20 | 0x09 | 0x0a | 0x0d | 0x0b | 0x0c | 0x85
10143            | 0x2000..=0x2006 | 0x2008..=0x200a
10144            | 0x2028 | 0x2029 | 0x205f | 0x3000
10145    ) as c_int
10146}
10147
10148/// Port of musl's iswcntrl.
10149#[no_mangle]
10150pub extern "C" fn iswcntrl(c: wint_t) -> c_int {
10151    let wc = c as u32;
10152    ((wc < 32)
10153        || wc.wrapping_sub(0x7f) < 33
10154        || wc.wrapping_sub(0x2028) < 2
10155        || wc.wrapping_sub(0xfff9) < 3) as c_int
10156}
10157
10158#[no_mangle]
10159pub extern "C" fn iswdigit(c: wint_t) -> c_int {
10160    ((c as u32).wrapping_sub(b'0' as u32) < 10) as c_int
10161}
10162
10163#[no_mangle]
10164pub extern "C" fn iswxdigit(c: wint_t) -> c_int {
10165    let wc = c as u32;
10166    ((wc.wrapping_sub(b'0' as u32) < 10) || ((wc | 32).wrapping_sub(b'a' as u32) < 6)) as c_int
10167}
10168
10169#[no_mangle]
10170pub extern "C" fn iswalnum(c: wint_t) -> c_int {
10171    (iswdigit(c) != 0 || iswalpha(c) != 0) as c_int
10172}
10173
10174#[no_mangle]
10175pub extern "C" fn iswblank(c: wint_t) -> c_int {
10176    (c == b' ' as wint_t || c == b'\t' as wint_t) as c_int
10177}
10178
10179#[no_mangle]
10180pub extern "C" fn iswgraph(c: wint_t) -> c_int {
10181    (iswspace(c) == 0 && iswprint(c) != 0) as c_int
10182}
10183
10184#[no_mangle]
10185pub extern "C" fn iswlower(c: wint_t) -> c_int {
10186    (unsafe { towupper(c) } != c) as c_int
10187}
10188
10189#[no_mangle]
10190pub extern "C" fn iswupper(c: wint_t) -> c_int {
10191    (unsafe { towlower(c) } != c) as c_int
10192}
10193
10194static WCTYPE_ALNUM: c_int = WC_ALNUM;
10195static WCTYPE_ALPHA: c_int = WC_ALPHA;
10196static WCTYPE_BLANK: c_int = WC_BLANK;
10197static WCTYPE_CNTRL: c_int = WC_CNTRL;
10198static WCTYPE_DIGIT: c_int = WC_DIGIT;
10199static WCTYPE_GRAPH: c_int = WC_GRAPH;
10200static WCTYPE_LOWER: c_int = WC_LOWER;
10201static WCTYPE_PRINT: c_int = WC_PRINT;
10202static WCTYPE_PUNCT: c_int = WC_PUNCT;
10203static WCTYPE_SPACE: c_int = WC_SPACE;
10204static WCTYPE_UPPER: c_int = WC_UPPER;
10205static WCTYPE_XDIGIT: c_int = WC_XDIGIT;
10206
10207#[no_mangle]
10208pub unsafe extern "C" fn wctype(name: *const c_char) -> wctype_t {
10209    if name.is_null() { return core::ptr::null(); }
10210    let n = name as *const u8;
10211    if strcmp(n, b"alnum\0".as_ptr()) == 0 { return &WCTYPE_ALNUM; }
10212    if strcmp(n, b"alpha\0".as_ptr()) == 0 { return &WCTYPE_ALPHA; }
10213    if strcmp(n, b"blank\0".as_ptr()) == 0 { return &WCTYPE_BLANK; }
10214    if strcmp(n, b"cntrl\0".as_ptr()) == 0 { return &WCTYPE_CNTRL; }
10215    if strcmp(n, b"digit\0".as_ptr()) == 0 { return &WCTYPE_DIGIT; }
10216    if strcmp(n, b"graph\0".as_ptr()) == 0 { return &WCTYPE_GRAPH; }
10217    if strcmp(n, b"lower\0".as_ptr()) == 0 { return &WCTYPE_LOWER; }
10218    if strcmp(n, b"print\0".as_ptr()) == 0 { return &WCTYPE_PRINT; }
10219    if strcmp(n, b"punct\0".as_ptr()) == 0 { return &WCTYPE_PUNCT; }
10220    if strcmp(n, b"space\0".as_ptr()) == 0 { return &WCTYPE_SPACE; }
10221    if strcmp(n, b"upper\0".as_ptr()) == 0 { return &WCTYPE_UPPER; }
10222    if strcmp(n, b"xdigit\0".as_ptr()) == 0 { return &WCTYPE_XDIGIT; }
10223    core::ptr::null()
10224}
10225
10226#[no_mangle]
10227pub unsafe extern "C" fn iswctype(c: wint_t, desc: wctype_t) -> c_int {
10228    if desc.is_null() { return 0; }
10229    if desc == core::ptr::addr_of!(WCTYPE_ALNUM) { return iswalnum(c); }
10230    if desc == core::ptr::addr_of!(WCTYPE_ALPHA) { return iswalpha(c); }
10231    if desc == core::ptr::addr_of!(WCTYPE_BLANK) { return iswblank(c); }
10232    if desc == core::ptr::addr_of!(WCTYPE_CNTRL) { return iswcntrl(c); }
10233    if desc == core::ptr::addr_of!(WCTYPE_DIGIT) { return iswdigit(c); }
10234    if desc == core::ptr::addr_of!(WCTYPE_GRAPH) { return iswgraph(c); }
10235    if desc == core::ptr::addr_of!(WCTYPE_LOWER) { return iswlower(c); }
10236    if desc == core::ptr::addr_of!(WCTYPE_PRINT) { return iswprint(c); }
10237    if desc == core::ptr::addr_of!(WCTYPE_PUNCT) { return iswpunct(c); }
10238    if desc == core::ptr::addr_of!(WCTYPE_SPACE) { return iswspace(c); }
10239    if desc == core::ptr::addr_of!(WCTYPE_UPPER) { return iswupper(c); }
10240    if desc == core::ptr::addr_of!(WCTYPE_XDIGIT) { return iswxdigit(c); }
10241    0
10242}
10243
10244static WCTRANS_LOWER: c_int = 1;
10245static WCTRANS_UPPER: c_int = 2;
10246
10247/// Port of musl's casemap() from ctype/towctrans.c.
10248fn casemap(c: wint_t, dir: i32) -> wint_t {
10249    let c0 = c;
10250    if c0 >= 0x20000 {
10251        return c0;
10252    }
10253    let b = (c0 >> 8) as usize;
10254    let cc = c0 & 255;
10255    let x = (cc / 3) as usize;
10256    let y = (cc % 3) as usize;
10257    const MT: [u32; 3] = [2048, 342, 57];
10258    let v = WCTYPE_CASEMAP_TAB[WCTYPE_CASEMAP_TAB[b] as usize * 86 + x] as u32;
10259    let v = (v * MT[y] >> 11) % 6;
10260    let r = WCTYPE_CASEMAP_RULES[(WCTYPE_CASEMAP_RULEBASES[b] + v as u8) as usize];
10261    let rt = (r & 255) as i32;
10262    let rd = r >> 8;
10263    if rt < 2 {
10264        return (c0 as i32 + (rd & -((rt) ^ dir))) as wint_t;
10265    }
10266    let mut xn = (rd & 0xff) as u32;
10267    let mut xb = (rd as u32) >> 8;
10268    while xn != 0 {
10269        let idx = (xb + xn / 2) as usize;
10270        let try_ = WCTYPE_CASEMAP_EXCEPTIONS[idx][0] as u32;
10271        if try_ == cc {
10272            let r2 = WCTYPE_CASEMAP_RULES[WCTYPE_CASEMAP_EXCEPTIONS[idx][1] as usize];
10273            let rt2 = (r2 & 255) as i32;
10274            let rd2 = r2 >> 8;
10275            if rt2 < 2 {
10276                return (c0 as i32 + (rd2 & -((rt2) ^ dir))) as wint_t;
10277            }
10278            return (c0 as i32 + if dir != 0 { -1 } else { 1 }) as wint_t;
10279        } else if try_ > cc {
10280            xn /= 2;
10281        } else {
10282            xb += xn / 2;
10283            xn -= xn / 2;
10284        }
10285    }
10286    c0
10287}
10288
10289#[no_mangle]
10290pub unsafe extern "C" fn towlower(c: wint_t) -> wint_t {
10291    casemap(c, 0)
10292}
10293
10294#[no_mangle]
10295pub unsafe extern "C" fn towupper(c: wint_t) -> wint_t {
10296    casemap(c, 1)
10297}
10298
10299#[no_mangle]
10300pub unsafe extern "C" fn wctrans(name: *const c_char) -> wctrans_t {
10301    if name.is_null() { return core::ptr::null(); }
10302    let n = name as *const u8;
10303    if strcmp(n, b"tolower\0".as_ptr()) == 0 { return &WCTRANS_LOWER; }
10304    if strcmp(n, b"toupper\0".as_ptr()) == 0 { return &WCTRANS_UPPER; }
10305    core::ptr::null()
10306}
10307
10308#[no_mangle]
10309pub unsafe extern "C" fn towctrans(c: wint_t, desc: wctrans_t) -> wint_t {
10310    if desc.is_null() { return c; }
10311    match *desc {
10312        1 => towlower(c),
10313        2 => towupper(c),
10314        _ => c,
10315    }
10316}
10317
10318// ============================================================
10319// wchar: wide stdio
10320// ============================================================
10321
10322#[no_mangle]
10323pub unsafe extern "C" fn fgetwc(f: *mut FILE) -> wint_t {
10324    let mut state: c_uint = 0;
10325    let mut wc: wchar_t = 0;
10326    let mut buf = [0u8; 4];
10327    let c = fgetc(f);
10328    if c == -1 { return WEOF; }
10329    buf[0] = c as u8;
10330    if buf[0] < 0x80 { return buf[0] as wint_t; }
10331    let len = if buf[0] < 0xE0 { 2 } else if buf[0] < 0xF0 { 3 } else { 4 };
10332    let mut n = 1usize;
10333    while n < len {
10334        let c2 = fgetc(f);
10335        if c2 == -1 {
10336            // Put the partial sequence back so a later read sees it.
10337            while n > 1 {
10338                n -= 1;
10339                ungetc(buf[n] as c_int, f);
10340            }
10341            return WEOF;
10342        }
10343        buf[n] = c2 as u8;
10344        n += 1;
10345    }
10346    let r = mbrtowc(&mut wc, buf.as_ptr() as *const c_char, n, &mut state);
10347    if r == !0usize {
10348        ERRNO!() = EILSEQ;
10349        WEOF
10350    } else if r == !1usize {
10351        while n > 0 {
10352            n -= 1;
10353            ungetc(buf[n] as c_int, f);
10354        }
10355        WEOF
10356    } else {
10357        wc as wint_t
10358    }
10359}
10360
10361#[no_mangle]
10362pub unsafe extern "C" fn fputwc(c: wchar_t, f: *mut FILE) -> wint_t {
10363    let mut buf = [0u8; 4];
10364    let n = wcrtomb(buf.as_mut_ptr() as *mut c_char, c, core::ptr::null_mut());
10365    if n == !0usize || n == 0 { return WEOF; }
10366    if fwrite(buf.as_ptr() as *const c_void, 1, n, f) != n { return WEOF; }
10367    c as wint_t
10368}
10369
10370#[no_mangle]
10371pub unsafe extern "C" fn fputws(s: *const wchar_t, f: *mut FILE) -> c_int {
10372    let mut i = 0;
10373    while *s.add(i) != 0 {
10374        if fputwc(*s.add(i), f) == WEOF { return -1; }
10375        i += 1;
10376    }
10377    0
10378}
10379
10380#[no_mangle]
10381pub unsafe extern "C" fn ungetwc(c: wint_t, f: *mut FILE) -> wint_t {
10382    if c == WEOF { return WEOF; }
10383    let mut buf = [0u8; 4];
10384    let n = wcrtomb(buf.as_mut_ptr() as *mut c_char, c as wchar_t, core::ptr::null_mut());
10385    if n == !0usize || n == 0 { return WEOF; }
10386    let mut i = n;
10387    while i > 0 {
10388        i -= 1;
10389        if ungetc(buf[i] as c_int, f) == -1 { return WEOF; }
10390    }
10391    c
10392}
10393
10394#[no_mangle]
10395pub unsafe extern "C" fn getwchar() -> wint_t { fgetwc(stdin) }
10396
10397#[no_mangle]
10398pub unsafe extern "C" fn putwchar(c: wchar_t) -> wint_t { fputwc(c, stdout) }
10399
10400// ============================================================
10401// wchar: swprintf / vswprintf / fwprintf / vfwprintf
10402// ============================================================
10403
10404unsafe fn wfmt_write_str(dst: *mut wchar_t, pos: usize, cap: usize, s: *const u8, len: usize) -> usize {
10405    let mut i = 0;
10406    while i < len {
10407        if pos + i < cap { *dst.add(pos + i) = *s.add(i) as wchar_t; }
10408        i += 1;
10409    }
10410    pos + len
10411}
10412
10413struct HeapGuard(*mut u8);
10414
10415impl Drop for HeapGuard {
10416    fn drop(&mut self) {
10417        if !self.0.is_null() {
10418            unsafe { crate::free(self.0 as *mut c_void); }
10419        }
10420    }
10421}
10422
10423#[no_mangle]
10424unsafe fn vswprintf_impl(
10425    s: *mut *mut wchar_t,
10426    n: usize,
10427    fmt: *const wchar_t,
10428    mut args: VaList,
10429    grow: bool,
10430) -> c_int {
10431    if !grow && n == 0 { return -1; }
10432    let mut buf = *s;
10433    let mut cap = if grow { n } else { n - 1 };
10434    let mut pos = 0usize;
10435    // Format specifiers are ASCII. Keep one byte per wide character so a
10436    // non-ASCII literal can still be emitted from the original string.
10437    let fmt_len = wcslen(fmt);
10438    let fmt_cap = fmt_len.saturating_add(1);
10439    let fmt_guard = HeapGuard(crate::malloc(fmt_cap) as *mut u8);
10440    let fmt_narrow = fmt_guard.0;
10441    if fmt_narrow.is_null() {
10442        ERRNO!() = ENOMEM;
10443        return -1;
10444    }
10445    for k in 0..fmt_len {
10446        let ch = *fmt.add(k) as u32;
10447        *fmt_narrow.add(k) = if ch < 128 { ch as u8 } else { b'?' };
10448    }
10449    *fmt_narrow.add(fmt_len) = 0;
10450    let mut fi = 0usize;
10451    macro_rules! wc {
10452        ($c:expr) => {
10453            if grow && pos + 1 >= cap {
10454                let newcap = cap.saturating_mul(2).max(pos + 2);
10455                let grown = crate::realloc(buf as *mut c_void, newcap * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
10456                if grown.is_null() { return -1; }
10457                buf = grown;
10458                cap = newcap;
10459            }
10460            if pos < cap { *buf.add(pos) = $c as wchar_t; }
10461            pos += 1;
10462        }
10463    }
10464    loop {
10465        let c = *fmt_narrow.add(fi);
10466        if c == 0 { break; }
10467        if c != b'%' {
10468            wc!(*fmt.add(fi) as u32);
10469            fi += 1;
10470            continue;
10471        }
10472        fi += 1;
10473        let mut flags: u8 = 0;
10474        loop {
10475            match *fmt_narrow.add(fi) {
10476                b'-' => { flags |= FLAG_MINUS; fi += 1; }
10477                b'+' => { flags |= FLAG_PLUS; fi += 1; }
10478                b' ' => { flags |= FLAG_SPACE; fi += 1; }
10479                b'0' => { flags |= FLAG_ZERO; fi += 1; }
10480                b'#' => { flags |= FLAG_HASH; fi += 1; }
10481                _ => break,
10482            }
10483        }
10484        let mut width: usize = 0;
10485        if *fmt_narrow.add(fi) == b'*' {
10486            let w = args.next_arg::<c_int>();
10487            width = fmt_star_width(w, &mut flags);
10488            fi += 1;
10489        } else {
10490            while *fmt_narrow.add(fi) >= b'0' && *fmt_narrow.add(fi) <= b'9' {
10491                width = width.saturating_mul(10).saturating_add((*fmt_narrow.add(fi) - b'0') as usize); fi += 1;
10492            }
10493        }
10494        width = fmt_width(width);
10495        let mut precision: i32 = -1;
10496        if *fmt_narrow.add(fi) == b'.' {
10497            fi += 1;
10498            if *fmt_narrow.add(fi) == b'*' {
10499                let p = args.next_arg::<c_int>();
10500                precision = if p < 0 { -1 } else { fmt_precision(p) }; fi += 1;
10501            } else {
10502                precision = 0;
10503                while *fmt_narrow.add(fi) >= b'0' && *fmt_narrow.add(fi) <= b'9' {
10504                    precision = precision.saturating_mul(10).saturating_add((*fmt_narrow.add(fi) - b'0') as i32); fi += 1;
10505                }
10506                precision = fmt_precision(precision);
10507            }
10508        }
10509        let len_mod = *fmt_narrow.add(fi);
10510        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' {
10511            fi += 1;
10512            let spec = *fmt_narrow.add(fi);
10513            if (len_mod == b'h' && spec == b'h') || (len_mod == b'l' && spec == b'l') {
10514                fi += 1;
10515                let spec2 = *fmt_narrow.add(fi);
10516                match (len_mod, spec, spec2) {
10517                    (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; } }
10518                    (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; } }
10519                    (b'h', b'h', b'd') | (b'h', b'h', b'i') => {
10520                        let val = args.next_arg::<c_int>() as i8 as c_int;
10521                        let neg = val < 0;
10522                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
10523                        let b = format_u64(abs);
10524                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10525                        let mut fbuf = [0u8; FMT_INT_BUF];
10526                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10527                    for k in 0..len { wc!(fbuf[k]); }
10528                    }
10529                    (b'h', b'h', b'u') => {
10530                        let val = args.next_arg::<c_uint>() as u8;
10531                        let b = format_u64(val as u64);
10532                        let mut fbuf = [0u8; FMT_INT_BUF];
10533                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10534                    for k in 0..len { wc!(fbuf[k]); }
10535                    }
10536                    (b'h', b'h', b'x') => {
10537                        let val = args.next_arg::<c_uint>() as u8;
10538                        let b = format_hex(val as u64, false);
10539                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10540                        let mut fbuf = [0u8; FMT_INT_BUF];
10541                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10542                    for k in 0..len { wc!(fbuf[k]); }
10543                    }
10544                    (b'h', b'h', b'X') => {
10545                        let val = args.next_arg::<c_uint>() as u8;
10546                        let b = format_hex(val as u64, true);
10547                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10548                        let mut fbuf = [0u8; FMT_INT_BUF];
10549                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10550                    for k in 0..len { wc!(fbuf[k]); }
10551                    }
10552                    (b'h', b'h', b'o') => {
10553                        let val = args.next_arg::<c_uint>() as u8;
10554                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
10555                        let mut fbuf = [0u8; FMT_INT_BUF];
10556                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10557                    for k in 0..len { wc!(fbuf[k]); }
10558                    }
10559                    (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
10560                        let val = args.next_arg::<c_longlong>();
10561                        let neg = val < 0;
10562                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
10563                        let b = format_u64(abs);
10564                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10565                        let mut fbuf = [0u8; FMT_INT_BUF];
10566                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10567                        for k in 0..len { wc!(fbuf[k]); }
10568                    }
10569                    (b'l', b'l', b'u') => {
10570                        let val = args.next_arg::<c_ulonglong>();
10571                        let b = format_u64(val as u64);
10572                        let mut fbuf = [0u8; FMT_INT_BUF];
10573                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10574                        for k in 0..len { wc!(fbuf[k]); }
10575                    }
10576                    (b'l', b'l', b'x') => {
10577                        let val = args.next_arg::<c_ulonglong>();
10578                        let b = format_hex(val as u64, false);
10579                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10580                        let mut fbuf = [0u8; FMT_INT_BUF];
10581                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10582                        for k in 0..len { wc!(fbuf[k]); }
10583                    }
10584                    (b'l', b'l', b'X') => {
10585                        let val = args.next_arg::<c_ulonglong>();
10586                        let b = format_hex(val as u64, true);
10587                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10588                        let mut fbuf = [0u8; FMT_INT_BUF];
10589                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10590                        for k in 0..len { wc!(fbuf[k]); }
10591                    }
10592                    (b'l', b'l', b'o') => {
10593                        let val = args.next_arg::<c_ulonglong>();
10594                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
10595                        let mut fbuf = [0u8; FMT_INT_BUF];
10596                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10597                        for k in 0..len { wc!(fbuf[k]); }
10598                    }
10599                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); wc!(spec2); }
10600                }
10601            } else {
10602                let lm = match len_mod {
10603                        b'z' | b't' if spec != b'n' => b'l',
10604                        // intmax_t is long on every target keel supports.
10605                        b'j' if spec != b'n' => b'l',
10606                        _ => len_mod,
10607                    };
10608                match (lm, spec) {
10609                    (b'h', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut u16) = pos as u16; } }
10610                    (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; } }
10611                    (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; } }
10612                    (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; } }
10613                    (b'h', b'd') | (b'h', b'i') => {
10614                        let val = args.next_arg::<c_int>() as i16 as c_int;
10615                        let neg = val < 0;
10616                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
10617                        let b = format_u64(abs);
10618                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10619                        let mut fbuf = [0u8; FMT_INT_BUF];
10620                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10621                    for k in 0..len { wc!(fbuf[k]); }
10622                    }
10623                    (b'h', b'u') => {
10624                        let val = args.next_arg::<c_uint>() as u16;
10625                        let b = format_u64(val as u64);
10626                        let mut fbuf = [0u8; FMT_INT_BUF];
10627                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10628                    for k in 0..len { wc!(fbuf[k]); }
10629                    }
10630                    (b'h', b'x') => {
10631                        let val = args.next_arg::<c_uint>() as u16;
10632                        let b = format_hex(val as u64, false);
10633                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10634                        let mut fbuf = [0u8; FMT_INT_BUF];
10635                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10636                    for k in 0..len { wc!(fbuf[k]); }
10637                    }
10638                    (b'h', b'X') => {
10639                        let val = args.next_arg::<c_uint>() as u16;
10640                        let b = format_hex(val as u64, true);
10641                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10642                        let mut fbuf = [0u8; FMT_INT_BUF];
10643                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10644                    for k in 0..len { wc!(fbuf[k]); }
10645                    }
10646                    (b'h', b'o') => {
10647                        let val = args.next_arg::<c_uint>() as u16;
10648                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
10649                        let mut fbuf = [0u8; FMT_INT_BUF];
10650                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10651                    for k in 0..len { wc!(fbuf[k]); }
10652                    }
10653                    (b'l', b'd') | (b'l', b'i') => {
10654                        let val = args.next_arg::<c_long>();
10655                        let neg = val < 0;
10656                        let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
10657                        let b = format_u64(abs);
10658                        let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10659                        let mut fbuf = [0u8; FMT_INT_BUF];
10660                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10661                        for k in 0..len { wc!(fbuf[k]); }
10662                    }
10663                    (b'l', b'u') => {
10664                        let val = args.next_arg::<c_ulong>();
10665                        let b = format_u64(val as u64);
10666                        let mut fbuf = [0u8; FMT_INT_BUF];
10667                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10668                        for k in 0..len { wc!(fbuf[k]); }
10669                    }
10670                    (b'l', b'x') => {
10671                        let val = args.next_arg::<c_ulong>();
10672                        let b = format_hex(val as u64, false);
10673                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10674                        let mut fbuf = [0u8; FMT_INT_BUF];
10675                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10676                        for k in 0..len { wc!(fbuf[k]); }
10677                    }
10678                    (b'l', b'X') => {
10679                        let val = args.next_arg::<c_ulong>();
10680                        let b = format_hex(val as u64, true);
10681                        let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10682                        let mut fbuf = [0u8; FMT_INT_BUF];
10683                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10684                        for k in 0..len { wc!(fbuf[k]); }
10685                    }
10686                    (b'l', b'o') => {
10687                        let val = args.next_arg::<c_ulong>();
10688                        let b = format_octal(val as u64, flags & FLAG_HASH != 0);
10689                        let mut fbuf = [0u8; FMT_INT_BUF];
10690                        let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10691                        for k in 0..len { wc!(fbuf[k]); }
10692                    }
10693                    (b'l', b'c') => {
10694                        let ch = args.next_arg::<wint_t>();
10695                        let pad = width.saturating_sub(1);
10696                        if flags & FLAG_MINUS != 0 {
10697                            wc!(ch);
10698                            for _ in 0..pad { wc!(b' '); }
10699                        } else {
10700                            for _ in 0..pad { wc!(b' '); }
10701                            wc!(ch);
10702                        }
10703                    }
10704                    (b'l', b's') => {
10705                        let ws_arg = args.next_arg::<*const wchar_t>();
10706                        if ws_arg.is_null() {
10707                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
10708                            if flags & FLAG_MINUS != 0 {
10709                                for k in 0..slen { wc!(b"(null)"[k]); }
10710                                for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10711                            } else {
10712                                for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10713                                for k in 0..slen { wc!(b"(null)"[k]); }
10714                            }
10715                        } else {
10716                            let mut wlen = 0usize;
10717                            loop {
10718                                let ch = *ws_arg.add(wlen);
10719                                if ch == 0 { break; }
10720                                if precision >= 0 && wlen >= precision as usize { break; }
10721                                wlen += 1;
10722                            }
10723                            if flags & FLAG_MINUS != 0 {
10724                                for k in 0..wlen { wc!(*ws_arg.add(k)); }
10725                                for _ in 0..width.saturating_sub(wlen) { wc!(b' '); }
10726                            } else {
10727                                for _ in 0..width.saturating_sub(wlen) { wc!(b' '); }
10728                                for k in 0..wlen { wc!(*ws_arg.add(k)); }
10729                            }
10730                        }
10731                    }
10732                    (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
10733                    | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
10734                        let val = args.next_arg::<f64>();
10735                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10736                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10737                        let mut fbuf = [0u8; 4224];
10738                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10739                        let mut wbuf = [0u8; 4224];
10740                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10741                        for k in 0..wlen { wc!(wbuf[k]); }
10742                    }
10743                    (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
10744                    | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
10745                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
10746                        let val = {
10747                            let lo: u64 = args.next_arg::<u64>();
10748                            let hi: u64 = args.next_arg::<u64>();
10749                            let combined: u128 = ((hi as u128) << 64) | (lo as u128);
10750                            f128::from_bits(combined) as f64
10751                        };
10752                        #[cfg(target_arch = "x86_64")]
10753                        let val = args.next_arg::<f64>();
10754                        let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10755                        let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10756                        let mut fbuf = [0u8; 4224];
10757                        let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10758                        let mut wbuf = [0u8; 4224];
10759                        let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10760                        for k in 0..wlen { wc!(wbuf[k]); }
10761                    }
10762                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); }
10763                }
10764            }
10765        } else {
10766            let spec = *fmt_narrow.add(fi);
10767            match spec {
10768                b'd' | b'i' => {
10769                    let d = args.next_arg::<c_int>();
10770                    let neg = d < 0;
10771                    let abs = if neg { d.wrapping_neg() as u64 } else { d as u64 };
10772                    let b = format_u64(abs);
10773                    let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
10774                    let mut fbuf = [0u8; FMT_INT_BUF];
10775                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, sign, None, precision, width, flags, false);
10776                    for k in 0..len { wc!(fbuf[k]); }
10777                }
10778                b'u' => {
10779                    let u = args.next_arg::<c_uint>();
10780                    let b = format_u64(u as u64);
10781                    let mut fbuf = [0u8; FMT_INT_BUF];
10782                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, false);
10783                    for k in 0..len { wc!(fbuf[k]); }
10784                }
10785                b'x' => {
10786                    let x = args.next_arg::<c_uint>();
10787                    let b = format_hex(x as u64, false);
10788                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'x') } else { None };
10789                    let mut fbuf = [0u8; FMT_INT_BUF];
10790                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10791                    for k in 0..len { wc!(fbuf[k]); }
10792                }
10793                b'X' => {
10794                    let x = args.next_arg::<c_uint>();
10795                    let b = format_hex(x as u64, true);
10796                    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') { Some(b'X') } else { None };
10797                    let mut fbuf = [0u8; FMT_INT_BUF];
10798                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false);
10799                    for k in 0..len { wc!(fbuf[k]); }
10800                }
10801                b'o' => {
10802                    let o = args.next_arg::<c_uint>();
10803                    let b = format_octal(o as u64, flags & FLAG_HASH != 0);
10804                    let mut fbuf = [0u8; FMT_INT_BUF];
10805                    let len = format_int(fbuf.as_mut_ptr(), b.0.as_ptr(), b.1, None, None, precision, width, flags, flags & FLAG_HASH != 0);
10806                    for k in 0..len { wc!(fbuf[k]); }
10807                }
10808                b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
10809                    let val = args.next_arg::<f64>();
10810                    let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10811                    let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10812                    let mut fbuf = [0u8; 4224];
10813                    let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10814                    let mut wbuf = [0u8; 4224];
10815                    let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10816                    for k in 0..wlen { wc!(wbuf[k]); }
10817                }
10818                b'c' => {
10819                    let ch = args.next_arg::<c_int>();
10820                    wc!(ch as u8);
10821                }
10822                b's' => {
10823                    let p = args.next_arg::<*const c_char>();
10824                    if p.is_null() {
10825                        let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
10826                        if flags & FLAG_MINUS != 0 {
10827                            for k in 0..slen { wc!(b"(null)"[k]); }
10828                            for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10829                        } else {
10830                            for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10831                            for k in 0..slen { wc!(b"(null)"[k]); }
10832                        }
10833                    } else {
10834                        let mut wbuf_local = [0i32; 256];
10835                        let mut wcount = 0usize;
10836                        let mut byte_pos = 0usize;
10837                        let pbytes = p as *const u8;
10838                        loop {
10839                            if precision >= 0 && wcount >= precision as usize { break; }
10840                            if wcount >= 256 { break; }
10841                            let mut wc_val: c_int = 0;
10842                            let consumed = mbrtowc(&mut wc_val as *mut c_int, p.add(byte_pos) as *const c_char, 256, core::ptr::null_mut());
10843                            if consumed == !0usize || consumed == !1usize {
10844                                wbuf_local[wcount] = *pbytes.add(byte_pos) as c_int;
10845                                byte_pos += 1;
10846                                wcount += 1;
10847                            } else if consumed == 0 {
10848                                break;
10849                            } else {
10850                                wbuf_local[wcount] = wc_val;
10851                                byte_pos += consumed;
10852                                wcount += 1;
10853                            }
10854                        }
10855                        if flags & FLAG_MINUS != 0 {
10856                            for k in 0..wcount { wc!(wbuf_local[k]); }
10857                            for _ in 0..width.saturating_sub(wcount) { wc!(b' '); }
10858                        } else {
10859                            for _ in 0..width.saturating_sub(wcount) { wc!(b' '); }
10860                            for k in 0..wcount { wc!(wbuf_local[k]); }
10861                        }
10862                    }
10863                }
10864                b'p' => {
10865                    wc!(b'0'); wc!(b'x');
10866                    let p = args.next_arg::<*const c_void>();
10867                    let b = format_hex(p as u64, false);
10868                    for k in 0..b.1 { wc!(b.0[k]); }
10869                }
10870                b'n' => {
10871                    let p = args.next_arg::<*mut c_void>();
10872                    if !p.is_null() { *(p as *mut c_int) = pos as c_int; }
10873                }
10874                b'%' => { wc!(b'%'); }
10875                _ => { wc!(b'%'); wc!(spec); }
10876            }
10877        }
10878        fi += 1;
10879    }
10880    let null_pos = if pos < cap { pos } else { cap };
10881    *buf.add(null_pos) = 0;
10882    if grow { *s = buf; }
10883    if pos > cap { -1 } else { pos as c_int }
10884}
10885
10886#[no_mangle]
10887pub unsafe extern "C" fn vswprintf(s: *mut wchar_t, n: usize, fmt: *const wchar_t, args: VaList) -> c_int {
10888    let mut buf = s;
10889    vswprintf_impl(&mut buf, n, fmt, args, false)
10890}
10891
10892#[no_mangle]
10893pub unsafe extern "C" fn swprintf(s: *mut wchar_t, n: usize, fmt: *const wchar_t, args: ...) -> c_int {
10894    vswprintf(s, n, fmt, args)
10895}
10896
10897#[no_mangle]
10898pub unsafe extern "C" fn vfwprintf(f: *mut FILE, fmt: *const wchar_t, args: VaList) -> c_int {
10899    // Grow the wide staging buffer instead of failing when the formatted
10900    // output exceeds a fixed size.
10901    let cap = 512usize;
10902    let mut buf = crate::malloc(cap * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
10903    if buf.is_null() {
10904        ERRNO!() = ENOMEM;
10905        return -1;
10906    }
10907    let r = vswprintf_impl(&mut buf, cap, fmt, args, true);
10908    if r < 0 {
10909        crate::free(buf as *mut c_void);
10910        return r;
10911    }
10912    let mut i = 0;
10913    while i < r as usize {
10914        let mut mb = [0u8; 4];
10915        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, *buf.add(i), core::ptr::null_mut());
10916        if n == !0usize {
10917            crate::free(buf as *mut c_void);
10918            return -1;
10919        }
10920        if fwrite(mb.as_ptr() as *const c_void, 1, n, f) != n {
10921            crate::free(buf as *mut c_void);
10922            return -1;
10923        }
10924        i += 1;
10925    }
10926    crate::free(buf as *mut c_void);
10927    r
10928}
10929
10930#[no_mangle]
10931pub unsafe extern "C" fn fwprintf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int {
10932    vfwprintf(f, fmt, args)
10933}
10934
10935// ============================================================
10936// wchar: vswscanf / swscanf / vfwscanf / fwscanf / vwscanf / wscanf
10937// ============================================================
10938
10939// Convert wchar_t format to byte format (ASCII cast, format specifiers are ASCII)
10940unsafe fn wcsfmt_to_mbs(dst: *mut u8, dst_len: usize, src: *const wchar_t) {
10941    let mut i = 0usize;
10942    loop {
10943        let ch = *src.add(i) as u32;
10944        if ch == 0 || i >= dst_len - 1 { break; }
10945        *dst.add(i) = if ch < 128 { ch as u8 } else { b'?' };
10946        i += 1;
10947    }
10948    *dst.add(i) = 0;
10949}
10950
10951#[no_mangle]
10952pub unsafe extern "C" fn vswscanf(s: *const wchar_t, fmt: *const wchar_t, mut args: VaList) -> c_int {
10953    if s.is_null() || fmt.is_null() {
10954        ERRNO!() = EINVAL;
10955        return -1;
10956    }
10957    let wlen = wcslen(s);
10958    let mut cap = wlen.saturating_mul(4).saturating_add(1);
10959    let mut mbs_buf = crate::malloc(cap) as *mut u8;
10960    if mbs_buf.is_null() {
10961        ERRNO!() = ENOMEM;
10962        return -1;
10963    }
10964    let mut i = 0usize;
10965    let mut mb_pos = 0usize;
10966    loop {
10967        let wc = *s.add(i) as c_int;
10968        if wc == 0 { break; }
10969        let mut mb = [0u8; 4];
10970        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, wc, core::ptr::null_mut());
10971        if n == !0usize || n == 0 { break; }
10972        if mb_pos + n >= cap {
10973            let next = match cap.checked_mul(2) {
10974                Some(v) => v,
10975                None => { crate::free(mbs_buf as *mut c_void); ERRNO!() = ENOMEM; return -1; }
10976            };
10977            let grown = crate::realloc(mbs_buf as *mut c_void, next) as *mut u8;
10978            if grown.is_null() { crate::free(mbs_buf as *mut c_void); ERRNO!() = ENOMEM; return -1; }
10979            mbs_buf = grown;
10980            cap = next;
10981        }
10982        core::ptr::copy_nonoverlapping(mb.as_ptr(), mbs_buf.add(mb_pos), n);
10983        mb_pos += n;
10984        i += 1;
10985    }
10986    *mbs_buf.add(mb_pos) = 0;
10987    let flen = wcslen(fmt);
10988    let fcap = flen.saturating_add(1);
10989    let mbs_fmt = crate::malloc(fcap) as *mut u8;
10990    if mbs_fmt.is_null() {
10991        crate::free(mbs_buf as *mut c_void);
10992        ERRNO!() = ENOMEM;
10993        return -1;
10994    }
10995    wcsfmt_to_mbs(mbs_fmt, fcap, fmt);
10996    let r = do_vsscanf(mbs_buf, mb_pos, mbs_fmt as *const c_char, &mut args, core::ptr::null_mut());
10997    crate::free(mbs_fmt as *mut c_void);
10998    crate::free(mbs_buf as *mut c_void);
10999    r
11000}
11001
11002#[no_mangle]
11003pub unsafe extern "C" fn swscanf(s: *const wchar_t, fmt: *const wchar_t, args: ...) -> c_int {
11004    vswscanf(s, fmt, args)
11005}
11006
11007#[no_mangle]
11008pub unsafe extern "C" fn vfwscanf(f: *mut FILE, fmt: *const wchar_t, mut args: VaList) -> c_int {
11009    if f.is_null() || fmt.is_null() {
11010        ERRNO!() = EINVAL;
11011        return -1;
11012    }
11013    let start_pos = ftello(f);
11014    if start_pos < 0 { return -1; }
11015    let mut cap = 4096usize;
11016    let mut buf = crate::malloc(cap) as *mut u8;
11017    if buf.is_null() { ERRNO!() = ENOMEM; return -1; }
11018    let mut n = 0usize;
11019    loop {
11020        if n + 1 >= cap {
11021            let next = match cap.checked_mul(2) {
11022                Some(v) => v,
11023                None => { crate::free(buf as *mut c_void); ERRNO!() = ENOMEM; return -1; }
11024            };
11025            let grown = crate::realloc(buf as *mut c_void, next) as *mut u8;
11026            if grown.is_null() { crate::free(buf as *mut c_void); ERRNO!() = ENOMEM; return -1; }
11027            buf = grown;
11028            cap = next;
11029        }
11030        let c = fgetc(f);
11031        if c == -1 { break; }
11032        *buf.add(n) = c as u8;
11033        n += 1;
11034    }
11035    *buf.add(n) = 0;
11036    let flen = wcslen(fmt);
11037    let fcap = flen.saturating_add(1);
11038    let mbs_fmt = crate::malloc(fcap) as *mut u8;
11039    if mbs_fmt.is_null() {
11040        crate::free(buf as *mut c_void);
11041        ERRNO!() = ENOMEM;
11042        return -1;
11043    }
11044    wcsfmt_to_mbs(mbs_fmt, fcap, fmt);
11045    let mut consumed = 0usize;
11046    let hit_eof = (*f)._eof != 0;
11047    let result = do_vsscanf(buf, n, mbs_fmt as *const c_char, &mut args, &mut consumed);
11048    crate::free(mbs_fmt as *mut c_void);
11049    crate::free(buf as *mut c_void);
11050    let _ = fseeko(f, start_pos + consumed as i64, SEEK_SET);
11051    if hit_eof && consumed == n {
11052        (*f)._eof = 1;
11053    }
11054    result
11055}
11056
11057#[no_mangle]
11058pub unsafe extern "C" fn fwscanf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int {
11059    vfwscanf(f, fmt, args)
11060}
11061
11062#[no_mangle]
11063pub unsafe extern "C" fn vwscanf(fmt: *const wchar_t, args: VaList) -> c_int {
11064    vfwscanf(stdin, fmt, args)
11065}
11066
11067#[no_mangle]
11068pub unsafe extern "C" fn wscanf(fmt: *const wchar_t, args: ...) -> c_int {
11069    vfwscanf(stdin, fmt, args)
11070}
11071
11072// ============================================================
11073// Time: internal helpers
11074// ============================================================
11075
11076const LEAPOCH: i64 = 946684800 + 86400 * (31 + 29);
11077const DAYS_PER_400Y: i64 = 365 * 400 + 97;
11078const DAYS_PER_100Y: i64 = 365 * 100 + 24;
11079const DAYS_PER_4Y: i64 = 365 * 4 + 1;
11080
11081const SECS_THROUGH_MONTH: [i32; 12] = [
11082    0, 31*86400, 59*86400, 90*86400, 120*86400, 151*86400,
11083    181*86400, 212*86400, 243*86400, 273*86400, 304*86400, 334*86400,
11084];
11085
11086const DAYS_IN_MONTH: [i32; 12] = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29];
11087
11088unsafe fn year_to_secs(year: i64, is_leap: &mut bool) -> i64 {
11089    // musl compares (year-2) as unsigned: the small-year fast path is only
11090    // valid for 1902..2038.  A signed comparison miscomputes negative years.
11091    if (year.wrapping_sub(2) as u64) <= 136 {
11092        let y = year as i32;
11093        let mut leaps = (y - 68) >> 2;
11094        if (y - 68) & 3 == 0 { leaps -= 1; *is_leap = true; } else { *is_leap = false; }
11095        return 31536000 * (y as i64 - 70) + 86400 * leaps as i64;
11096    }
11097    let mut cycles = ((year - 100) / 400) as i32;
11098    let mut rem = ((year - 100) % 400) as i32;
11099    if rem < 0 { cycles -= 1; rem += 400; }
11100    let (centuries, leaps);
11101    if rem == 0 { *is_leap = true; centuries = 0; leaps = 0; }
11102    else {
11103        let c;
11104        if rem >= 200 { if rem >= 300 { c = 3; rem -= 300; } else { c = 2; rem -= 200; } }
11105        else { if rem >= 100 { c = 1; rem -= 100; } else { c = 0; } }
11106        centuries = c;
11107        if rem == 0 { *is_leap = false; leaps = 0; }
11108        else { leaps = rem / 4; rem %= 4; *is_leap = rem == 0; }
11109    }
11110    let total_leaps = leaps + 97 * cycles + 24 * centuries - (*is_leap as i32);
11111    (year - 100) * 31536000 + total_leaps as i64 * 86400 + 946684800 + 86400
11112}
11113
11114fn month_to_secs(month: i32, is_leap: bool) -> i32 {
11115    let mut t = SECS_THROUGH_MONTH[month as usize];
11116    if is_leap && month >= 2 { t += 86400; }
11117    t
11118}
11119
11120unsafe fn secs_to_tm(t: i64, tm: &mut tm) -> bool {
11121    if t < (i32::MIN as i64) * 31622400 || t > (i32::MAX as i64) * 31622400 { return false; }
11122    let secs = t - LEAPOCH;
11123    let mut days = secs / 86400;
11124    let mut remsecs = (secs % 86400) as i32;
11125    if remsecs < 0 { remsecs += 86400; days -= 1; }
11126    let mut wday = ((3 + days) % 7) as i32;
11127    if wday < 0 { wday += 7; }
11128    let mut qc_cycles = (days / DAYS_PER_400Y) as i32;
11129    let mut remdays = (days % DAYS_PER_400Y) as i32;
11130    if remdays < 0 { remdays += DAYS_PER_400Y as i32; qc_cycles -= 1; }
11131    let mut c_cycles = remdays / DAYS_PER_100Y as i32;
11132    if c_cycles == 4 { c_cycles -= 1; }
11133    remdays -= c_cycles * DAYS_PER_100Y as i32;
11134    let mut q_cycles = remdays / DAYS_PER_4Y as i32;
11135    if q_cycles == 25 { q_cycles -= 1; }
11136    remdays -= q_cycles * DAYS_PER_4Y as i32;
11137    let mut remyears = remdays / 365;
11138    if remyears == 4 { remyears -= 1; }
11139    remdays -= remyears * 365;
11140    let leap = remyears == 0 && (q_cycles != 0 || c_cycles == 0);
11141    let mut yday = remdays + 31 + 28 + leap as i32;
11142    if yday >= 365 + leap as i32 { yday -= 365 + leap as i32; }
11143    let years = remyears as i64 + 4 * q_cycles as i64 + 100 * c_cycles as i64 + 400 * qc_cycles as i64;
11144    let mut months = 0i32;
11145    let mut rd = remdays;
11146    for m in 0..12 {
11147        if DAYS_IN_MONTH[m] <= rd { rd -= DAYS_IN_MONTH[m]; } else { months = m as i32; break; }
11148    }
11149    let mut adj_years = years;
11150    if months >= 10 { months -= 12; adj_years += 1; }
11151    if adj_years + 100 > i32::MAX as i64 || adj_years + 100 < i32::MIN as i64 { return false; }
11152    tm.tm_year = (adj_years + 100) as c_int;
11153    tm.tm_mon = months + 2;
11154    tm.tm_mday = rd + 1;
11155    tm.tm_wday = wday;
11156    tm.tm_yday = yday;
11157    tm.tm_hour = remsecs / 3600;
11158    tm.tm_min = remsecs / 60 % 60;
11159    tm.tm_sec = remsecs % 60;
11160    true
11161}
11162
11163unsafe fn tm_to_secs(tm: *const tm) -> i64 {
11164    let mut year = (*tm).tm_year as i64;
11165    let mut month = (*tm).tm_mon;
11166    if month >= 12 || month < 0 {
11167        let adj = month / 12;
11168        month %= 12;
11169        if month < 0 { month += 12; }
11170        year += adj as i64;
11171    }
11172    let mut is_leap = false;
11173    let mut t = year_to_secs(year, &mut is_leap);
11174    t += month_to_secs(month, is_leap) as i64;
11175    t += 86400 * ((*tm).tm_mday as i64 - 1);
11176    t += 3600 * (*tm).tm_hour as i64;
11177    t += 60 * (*tm).tm_min as i64;
11178    t += (*tm).tm_sec as i64;
11179    t
11180}
11181
11182static mut TM_BUF: tm = tm {
11183    tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0,
11184    tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0,
11185    tm_gmtoff: 0, tm_zone: core::ptr::null(),
11186};
11187
11188static mut UTC_STR: [c_char; 4] = [b'U' as c_char, b'T' as c_char, b'C' as c_char, 0];
11189
11190const CLOCK_PROCESS_CPUTIME_ID: c_int = 2;
11191
11192// ============================================================
11193// Time: core functions
11194// ============================================================
11195
11196#[no_mangle]
11197pub unsafe extern "C" fn time(t: *mut TimeT) -> TimeT {
11198    let mut ts: timespec = core::mem::zeroed();
11199    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
11200    if !t.is_null() { *t = ts.tv_sec; }
11201    ts.tv_sec
11202}
11203
11204#[no_mangle]
11205pub unsafe extern "C" fn difftime(t1: TimeT, t0: TimeT) -> f64 {
11206    (t1 as i64 - t0 as i64) as f64
11207}
11208
11209#[no_mangle]
11210pub unsafe extern "C" fn clock() -> ClockT {
11211    let mut ts: timespec = core::mem::zeroed();
11212    let _ = sys_clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut ts);
11213    ts.tv_sec * 1000000 + ts.tv_nsec / 1000
11214}
11215
11216#[no_mangle]
11217pub unsafe extern "C" fn gmtime(t: *const TimeT) -> *mut tm {
11218    gmtime_r(t, &raw mut TM_BUF)
11219}
11220
11221#[no_mangle]
11222pub unsafe extern "C" fn gmtime_r(t: *const TimeT, tm: *mut tm) -> *mut tm {
11223    if !secs_to_tm(*t as i64, &mut *tm) { ERRNO!() = EOVERFLOW; return core::ptr::null_mut(); }
11224    (*tm).tm_isdst = 0;
11225    (*tm).tm_gmtoff = 0;
11226    (*tm).tm_zone = core::ptr::addr_of!(UTC_STR).cast::<c_char>();
11227    tm
11228}
11229
11230#[no_mangle]
11231pub unsafe extern "C" fn localtime(t: *const TimeT) -> *mut tm {
11232    tz_localtime_r(t, &raw mut TM_BUF)
11233}
11234
11235#[no_mangle]
11236pub unsafe extern "C" fn localtime_r(t: *const TimeT, tm: *mut tm) -> *mut tm {
11237    tz_localtime_r(t, tm)
11238}
11239
11240#[no_mangle]
11241pub unsafe extern "C" fn mktime(tm: *mut tm) -> TimeT {
11242    tz_mktime(tm)
11243}
11244
11245#[no_mangle]
11246pub unsafe extern "C" fn timegm(tm: *mut tm) -> TimeT {
11247    let t = tm_to_secs(tm as *const tm);
11248    if !secs_to_tm(t, &mut *tm) { ERRNO!() = EOVERFLOW; return -1; }
11249    (*tm).tm_isdst = 0;
11250    (*tm).tm_gmtoff = 0;
11251    (*tm).tm_zone = core::ptr::addr_of!(UTC_STR).cast::<c_char>();
11252    t as TimeT
11253}
11254
11255static mut ASCTIME_BUF: [c_char; 26] = [0; 26];
11256
11257const 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"];
11258const 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"];
11259
11260#[no_mangle]
11261pub unsafe extern "C" fn asctime(tm: *const tm) -> *mut c_char {
11262    asctime_r(tm, core::ptr::addr_of_mut!(ASCTIME_BUF).cast::<c_char>())
11263}
11264
11265#[no_mangle]
11266pub unsafe extern "C" fn asctime_r(tm: *const tm, buf: *mut c_char) -> *mut c_char {
11267    let wday = if (*tm).tm_wday >= 0 && (*tm).tm_wday < 7 { (*tm).tm_wday as usize } else { 0 };
11268    let mon = if (*tm).tm_mon >= 0 && (*tm).tm_mon < 12 { (*tm).tm_mon as usize } else { 0 };
11269    let dn = DAY_NAMES[wday];
11270    let mn = MON_NAMES[mon];
11271    let mut p = 0;
11272    for k in 0..3 { *buf.add(p) = *dn.as_ptr().add(k) as c_char; p += 1; }
11273    *buf.add(p) = b' ' as c_char; p += 1;
11274    for k in 0..3 { *buf.add(p) = *mn.as_ptr().add(k) as c_char; p += 1; }
11275    *buf.add(p) = b' ' as c_char; p += 1;
11276    // %.3s %.3s%3d: the day is right-aligned in a three-column field.
11277    let v = (*tm).tm_mday;
11278    if v < 10 {
11279        *buf.add(p) = b' ' as c_char; p += 1;
11280        *buf.add(p) = b' ' as c_char; p += 1;
11281        *buf.add(p) = (b'0' + v as u8) as c_char; p += 1;
11282    } else if v < 100 {
11283        *buf.add(p) = b' ' as c_char; p += 1;
11284        *buf.add(p) = (b'0' + (v / 10) as u8) as c_char; p += 1;
11285        *buf.add(p) = (b'0' + (v % 10) as u8) as c_char; p += 1;
11286    } else {
11287        *buf.add(p) = (b'0' + (v / 100) as u8) as c_char; p += 1;
11288        *buf.add(p) = (b'0' + ((v / 10) % 10) as u8) as c_char; p += 1;
11289        *buf.add(p) = (b'0' + (v % 10) as u8) as c_char; p += 1;
11290    }
11291    *buf.add(p) = b' ' as c_char; p += 1;
11292    let hh = (*tm).tm_hour;
11293    *buf.add(p) = (b'0' + (hh / 10) as u8) as c_char; p += 1;
11294    *buf.add(p) = (b'0' + (hh % 10) as u8) as c_char; p += 1;
11295    *buf.add(p) = b':' as c_char; p += 1;
11296    let mm = (*tm).tm_min;
11297    *buf.add(p) = (b'0' + (mm / 10) as u8) as c_char; p += 1;
11298    *buf.add(p) = (b'0' + (mm % 10) as u8) as c_char; p += 1;
11299    *buf.add(p) = b':' as c_char; p += 1;
11300    let ss = (*tm).tm_sec;
11301    *buf.add(p) = (b'0' + (ss / 10) as u8) as c_char; p += 1;
11302    *buf.add(p) = (b'0' + (ss % 10) as u8) as c_char; p += 1;
11303    *buf.add(p) = b' ' as c_char; p += 1;
11304    // %d: negative and >4-digit years are valid in musl asctime.
11305    let yr = (*tm).tm_year as i64 + 1900;
11306    let mut tmp = [0u8; 16];
11307    let mut n = 0usize;
11308    let mut v2 = if yr < 0 { -yr } else { yr };
11309    if v2 == 0 {
11310        tmp[n] = b'0';
11311        n += 1;
11312    } else {
11313        while v2 > 0 && n < tmp.len() {
11314            tmp[n] = b'0' + (v2 % 10) as u8;
11315            v2 /= 10;
11316            n += 1;
11317        }
11318    }
11319    if yr < 0 {
11320        *buf.add(p) = b'-' as c_char;
11321        p += 1;
11322    }
11323    for k in (0..n).rev() {
11324        *buf.add(p) = tmp[k] as c_char;
11325        p += 1;
11326    }
11327    *buf.add(p) = b'\n' as c_char; p += 1;
11328    *buf.add(p) = 0;
11329    buf
11330}
11331
11332#[no_mangle]
11333pub unsafe extern "C" fn ctime(t: *const TimeT) -> *mut c_char {
11334    let tm = localtime(t);
11335    if tm.is_null() { core::ptr::null_mut() } else { asctime(tm) }
11336}
11337
11338#[no_mangle]
11339pub unsafe extern "C" fn ctime_r(t: *const TimeT, buf: *mut c_char) -> *mut c_char {
11340    let mut tmp: tm = core::mem::zeroed();
11341    if localtime_r(t, &mut tmp).is_null() { core::ptr::null_mut() } else { asctime_r(&tmp, buf) }
11342}
11343
11344// ============================================================
11345// Time: clock_getres / clock_settime / clock_nanosleep / gettimeofday
11346// ============================================================
11347
11348unsafe fn sys_clock_getres(clockid: c_int, ts: *mut timespec) -> i64 {
11349    <Arch as Syscalls>::syscall2(SYS_CLOCK_GETRES, clockid as i64, ts as i64)
11350}
11351
11352unsafe fn sys_clock_settime(clockid: c_int, ts: *const timespec) -> i64 {
11353    <Arch as Syscalls>::syscall2(SYS_CLOCK_SETTIME, clockid as i64, ts as i64)
11354}
11355
11356unsafe fn sys_clock_nanosleep(clockid: c_int, flags: c_int, req: *const timespec, rem: *mut timespec) -> i64 {
11357    <Arch as Syscalls>::syscall4(SYS_CLOCK_NANOSLEEP, clockid as i64, flags as i64, req as i64, rem as i64)
11358}
11359
11360#[no_mangle]
11361pub unsafe extern "C" fn clock_getres(clockid: c_int, ts: *mut timespec) -> c_int {
11362    let r = sys_clock_getres(clockid, ts);
11363    syscall_ret(r) as c_int
11364}
11365
11366#[no_mangle]
11367pub unsafe extern "C" fn clock_settime(clockid: c_int, ts: *const timespec) -> c_int {
11368    let r = sys_clock_settime(clockid, ts);
11369    syscall_ret(r) as c_int
11370}
11371
11372#[no_mangle]
11373pub unsafe extern "C" fn clock_nanosleep(clockid: c_int, flags: c_int, req: *const timespec, rem: *mut timespec) -> c_int {
11374    let r = sys_clock_nanosleep(clockid, flags, req, rem);
11375    if r < 0 {
11376        let e = (-r) as c_int;
11377        // The kernel returns EOPNOTSUPP for CLOCK_THREAD_CPUTIME_ID;
11378        // POSIX/musl report EINVAL instead.
11379        if clockid == 3 && e == 95 { return 22; }
11380        e
11381    } else {
11382        0
11383    }
11384}
11385
11386#[no_mangle]
11387pub unsafe extern "C" fn gettimeofday(tv: *mut timeval, _tz: *mut c_void) -> c_int {
11388    if tv.is_null() { return 0; }
11389    let mut ts: timespec = core::mem::zeroed();
11390    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
11391    (*tv).tv_sec = ts.tv_sec;
11392    (*tv).tv_usec = ts.tv_nsec / 1000;
11393    0
11394}
11395
11396// ============================================================
11397// Time: strftime
11398// ============================================================
11399
11400fn is_leap_year(y: i32) -> bool {
11401    // Widen before adding 1900 so years near i32::MAX cannot wrap; 2000 is
11402    // not congruent to 1900 modulo 400, so the old shortcut was wrong.
11403    let yr = (y as i64) + 1900;
11404    yr % 4 == 0 && (yr % 100 != 0 || yr % 400 == 0)
11405}
11406
11407fn week_num(tm: &tm) -> i32 {
11408    let mut val = (tm.tm_yday + 7 - ((tm.tm_wday + 6) % 7)) / 7;
11409    if (tm.tm_wday + 371 - tm.tm_yday - 2).rem_euclid(7) <= 2 { val += 1; }
11410    if val == 0 {
11411        val = 52;
11412        let dec31 = (tm.tm_wday + 7 - tm.tm_yday - 1).rem_euclid(7);
11413        if dec31 == 4 || (dec31 == 5 && is_leap_year(tm.tm_year % 400 - 1)) { val += 1; }
11414    } else if val == 53 {
11415        let jan1 = (tm.tm_wday + 371 - tm.tm_yday).rem_euclid(7);
11416        if jan1 != 4 && (jan1 != 3 || !is_leap_year(tm.tm_year)) { val = 1; }
11417    }
11418    val
11419}
11420
11421// Langinfo constants for strftime
11422const ABDAY_1: c_int = 0x20000;
11423const DAY_1: c_int = 0x20007;
11424const ABMON_1: c_int = 0x2000E;
11425const MON_1: c_int = 0x2001A;
11426const AM_STR_LI: c_int = 0x20026;
11427const PM_STR_LI: c_int = 0x20027;
11428const D_T_FMT: c_int = 0x20028;
11429const D_FMT: c_int = 0x20029;
11430const T_FMT: c_int = 0x2002A;
11431const T_FMT_AMPM: c_int = 0x2002B;
11432
11433// Format an i64 into buf as decimal with zero/sign padding. Returns (ptr_to_start, length).
11434// pad: '-' = no pad, '_' = space pad, '0' or 0 = zero pad. width: minimum digits (excluding sign).
11435unsafe fn num_fmt(buf: &mut [u8; 100], val: i64, pad: u8, width: usize) -> (*const u8, usize) {
11436    let negative = val < 0;
11437    let mut v = if negative { -val as u64 } else { val as u64 };
11438    let mut tmp = [0u8; 24];
11439    let mut pos = 24usize;
11440    if v == 0 { pos -= 1; tmp[pos] = b'0'; }
11441    while v > 0 { pos -= 1; tmp[pos] = b'0' + (v % 10) as u8; v /= 10; }
11442    let digits = 24 - pos;
11443    let sign_chars = if negative { 1 } else { 0 };
11444    let needed = sign_chars + digits;
11445    let fill = if width > needed { width - needed } else { 0 };
11446    let total = fill + needed;
11447    let mut p = 0usize;
11448    match pad {
11449        b'-' => { /* no fill */ }
11450        b'_' => {
11451            for _ in 0..fill { buf[p] = b' '; p += 1; }
11452            if negative { buf[p] = b'-'; p += 1; }
11453        }
11454        _ => {
11455            if negative { buf[p] = b'-'; p += 1; }
11456            for _ in 0..fill { buf[p] = b'0'; p += 1; }
11457        }
11458    }
11459    for i in 0..digits { buf[p] = tmp[pos + i]; p += 1; }
11460    (buf.as_ptr(), total)
11461}
11462
11463// Copy a null-terminated C string into buf. Returns (ptr, len).
11464unsafe fn str_to_buf(buf: &mut [u8; 100], s: *const c_char) -> (*const u8, usize) {
11465    let mut k = 0usize;
11466    // tm_zone and nl_langinfo strings are caller/file controlled; never walk
11467    // past the fixed buffer (the format result is truncated instead).
11468    while k + 1 < buf.len() && *s.add(k) != 0 {
11469        buf[k] = *s.add(k) as u8;
11470        k += 1;
11471    }
11472    (buf.as_ptr(), k)
11473}
11474
11475// Core format dispatcher. Returns (ptr, len) where ptr points into buf or a static string.
11476// pad=0 means use default; returns (null, 0) for unknown specifiers.
11477unsafe fn __strftime_fmt_1(buf: &mut [u8; 100], f: u8, tm: *const tm, pad: u8) -> (*const u8, usize) {
11478    let mut val: i64;
11479    let mut width: usize = 2;
11480    let mut def_pad: u8 = b'0';
11481    let fmt: *const c_char;
11482
11483    match f {
11484        b'a' => {
11485            if (*tm).tm_wday as u32 > 6 { return (b"\0".as_ptr(), 0); }
11486            let p = nl_langinfo(ABDAY_1 + (*tm).tm_wday);
11487            return str_to_buf(buf, p);
11488        }
11489        b'A' => {
11490            if (*tm).tm_wday as u32 > 6 { return (b"\0".as_ptr(), 0); }
11491            let p = nl_langinfo(DAY_1 + (*tm).tm_wday);
11492            return str_to_buf(buf, p);
11493        }
11494        b'h' | b'b' => {
11495            if (*tm).tm_mon as u32 > 11 { return (b"\0".as_ptr(), 0); }
11496            let p = nl_langinfo(ABMON_1 + (*tm).tm_mon);
11497            return str_to_buf(buf, p);
11498        }
11499        b'B' => {
11500            if (*tm).tm_mon as u32 > 11 { return (b"\0".as_ptr(), 0); }
11501            let p = nl_langinfo(MON_1 + (*tm).tm_mon);
11502            return str_to_buf(buf, p);
11503        }
11504        b'c' => {
11505            let p = nl_langinfo(D_T_FMT);
11506            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11507            return (buf.as_ptr(), l);
11508        }
11509        b'C' => {
11510            val = (1900i64 + (*tm).tm_year as i64) / 100;
11511            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11512        }
11513        b'e' => { def_pad = b'_'; }
11514        b'd' => {
11515            val = (*tm).tm_mday as i64;
11516            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11517        }
11518        b'D' => {
11519            fmt = b"%m/%d/%y\0".as_ptr() as *const c_char;
11520            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11521            return (buf.as_ptr(), l);
11522        }
11523        b'F' => {
11524            fmt = b"%Y-%m-%d\0".as_ptr() as *const c_char;
11525            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11526            return (buf.as_ptr(), l);
11527        }
11528        b'g' | b'G' => {
11529            val = (*tm).tm_year as i64 + 1900;
11530            if (*tm).tm_yday < 3 && week_num(&*tm) != 1 { val -= 1; }
11531            else if (*tm).tm_yday > 360 && week_num(&*tm) == 1 { val += 1; }
11532            if f == b'g' { val %= 100; }
11533            else { width = 4; }
11534            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11535        }
11536        b'H' => {
11537            val = (*tm).tm_hour as i64;
11538            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11539        }
11540        b'I' => {
11541            val = (*tm).tm_hour as i64;
11542            if val == 0 { val = 12; }
11543            else if val > 12 { val -= 12; }
11544            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11545        }
11546        b'j' => {
11547            val = (*tm).tm_yday as i64 + 1;
11548            width = 3;
11549            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11550        }
11551        b'm' => {
11552            val = (*tm).tm_mon as i64 + 1;
11553            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11554        }
11555        b'M' => {
11556            val = (*tm).tm_min as i64;
11557            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11558        }
11559        b'n' => { buf[0] = b'\n'; return (buf.as_ptr(), 1); }
11560        b'p' => {
11561            let p = if (*tm).tm_hour >= 12 { nl_langinfo(PM_STR_LI) } else { nl_langinfo(AM_STR_LI) };
11562            return str_to_buf(buf, p);
11563        }
11564        b'r' => {
11565            let p = nl_langinfo(T_FMT_AMPM);
11566            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11567            return (buf.as_ptr(), l);
11568        }
11569        b'R' => {
11570            fmt = b"%H:%M\0".as_ptr() as *const c_char;
11571            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11572            return (buf.as_ptr(), l);
11573        }
11574        b's' => {
11575            val = tm_to_secs(tm) - (*tm).tm_gmtoff as i64;
11576            width = 1;
11577            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11578        }
11579        b'S' => {
11580            val = (*tm).tm_sec as i64;
11581            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11582        }
11583        b't' => { buf[0] = b'\t'; return (buf.as_ptr(), 1); }
11584        b'T' => {
11585            fmt = b"%H:%M:%S\0".as_ptr() as *const c_char;
11586            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11587            return (buf.as_ptr(), l);
11588        }
11589        b'u' => {
11590            val = if (*tm).tm_wday != 0 { (*tm).tm_wday as i64 } else { 7 };
11591            width = 1;
11592            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11593        }
11594        b'U' => {
11595            val = ((*tm).tm_yday as u64 + 7 - (*tm).tm_wday as u64) as i64 / 7;
11596            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11597        }
11598        b'W' => {
11599            val = ((*tm).tm_yday as u64 + 7 - ((*tm).tm_wday as u64 + 6) % 7) as i64 / 7;
11600            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11601        }
11602        b'V' => {
11603            val = week_num(&*tm) as i64;
11604            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11605        }
11606        b'w' => {
11607            val = (*tm).tm_wday as i64;
11608            width = 1;
11609            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11610        }
11611        b'x' => {
11612            let p = nl_langinfo(D_FMT);
11613            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11614            return (buf.as_ptr(), l);
11615        }
11616        b'X' => {
11617            let p = nl_langinfo(T_FMT);
11618            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11619            return (buf.as_ptr(), l);
11620        }
11621        b'y' => {
11622            val = (1900i64 + (*tm).tm_year as i64) % 100;
11623            if val < 0 { val = -val; }
11624            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11625        }
11626        b'Y' => {
11627            val = (*tm).tm_year as i64 + 1900;
11628            if val >= 10000 {
11629                let mut tmp = [0u8; 100];
11630                let (_, k) = num_fmt(&mut tmp, val, b'-', 1);
11631                buf[0] = b'+';
11632                for i in 0..k { buf[1 + i] = tmp[i]; }
11633                return (buf.as_ptr(), 1 + k);
11634            }
11635            width = 4;
11636            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11637        }
11638        b'z' => {
11639            if (*tm).tm_isdst < 0 { return (b"\0".as_ptr(), 0); }
11640            let gmtoff = (*tm).tm_gmtoff as i64;
11641            let sign = if gmtoff >= 0 { b'+' } else { b'-' };
11642            let off = if gmtoff < 0 { -gmtoff } else { gmtoff };
11643            let hh = (off / 3600) as i32;
11644            let mm = ((off % 3600) / 60) as i32;
11645            buf[0] = sign;
11646            buf[1] = b'0' + (hh / 10) as u8;
11647            buf[2] = b'0' + (hh % 10) as u8;
11648            buf[3] = b'0' + (mm / 10) as u8;
11649            buf[4] = b'0' + (mm % 10) as u8;
11650            return (buf.as_ptr(), 5);
11651        }
11652        b'Z' => {
11653            if (*tm).tm_isdst < 0 || (*tm).tm_zone.is_null() { return (b"\0".as_ptr(), 0); }
11654            return str_to_buf(buf, (*tm).tm_zone);
11655        }
11656        b'%' => { buf[0] = b'%'; return (buf.as_ptr(), 1); }
11657        _ => { return (core::ptr::null(), 0); }
11658    }
11659    // fallthrough for 'e' (def_pad='_', same logic as 'd')
11660    val = (*tm).tm_mday as i64;
11661    num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width)
11662}
11663
11664unsafe fn __strftime_l(s: *mut c_char, n: usize, f: *const c_char, tm: *const tm) -> usize {
11665    let mut l: usize = 0;
11666    let mut fi: usize = 0;
11667    while l < n {
11668        let ch = *f.add(fi) as u8;
11669        if ch == 0 {
11670            *s.add(l) = 0;
11671            return l;
11672        }
11673        if ch != b'%' {
11674            *s.add(l) = ch as c_char;
11675            l += 1;
11676            fi += 1;
11677            continue;
11678        }
11679        fi += 1;
11680        // Parse flags
11681        let mut pad: u8 = 0;
11682        let fc = *f.add(fi) as u8;
11683        if fc == b'-' || fc == b'_' || fc == b'0' { pad = fc; fi += 1; }
11684        let plus = *f.add(fi) as u8 == b'+';
11685        if plus { fi += 1; }
11686        // Parse width
11687        let mut width: usize = 0;
11688        let mut p_idx = fi;
11689        {
11690            let fc2 = *f.add(fi) as u8;
11691            if fc2 >= b'0' && fc2 <= b'9' {
11692                let mut w: usize = 0;
11693                while { let c = *f.add(p_idx) as u8; c >= b'0' && c <= b'9' } {
11694                    w = w * 10 + (*f.add(p_idx) as usize - b'0' as usize);
11695                    p_idx += 1;
11696                }
11697                width = w;
11698            }
11699        }
11700        let spec_ch = *f.add(p_idx) as u8;
11701        if spec_ch == b'C' || spec_ch == b'F' || spec_ch == b'G' || spec_ch == b'Y' {
11702            if width == 0 && p_idx != fi { width = 1; }
11703        } else {
11704            width = 0;
11705        }
11706        fi = p_idx;
11707        // Skip E/O modifier
11708        let fc3 = *f.add(fi) as u8;
11709        if fc3 == b'E' || fc3 == b'O' { fi += 1; }
11710        let fch = *f.add(fi) as u8;
11711        // Call formatter
11712        let mut buf = [0u8; 100];
11713        let (t, k) = __strftime_fmt_1(&mut buf, fch, tm, pad);
11714        if t.is_null() { break; }
11715        let mut k = k;
11716        let mut t = t;
11717        if width != 0 {
11718            // Strip sign and leading zeros, count remaining digits
11719            if *t == b'+' || *t == b'-' { t = t.add(1); k -= 1; }
11720            while k > 0 && *t == b'0' && k > 1 && *t.add(1) >= b'0' && *t.add(1) <= b'9' {
11721                t = t.add(1); k -= 1;
11722            }
11723            if width < k { width = k; }
11724            let mut d: usize = 0;
11725            while d < k && *t.add(d) >= b'0' && *t.add(d) <= b'9' { d += 1; }
11726            if (*tm).tm_year < -1900 {
11727                if l < n { *s.add(l) = b'-' as c_char; }
11728                l += 1;
11729                width -= 1;
11730            } else if plus && d + (width - k) >= (if spec_ch == b'C' { 3 } else { 5 }) {
11731                if l < n { *s.add(l) = b'+' as c_char; }
11732                l += 1;
11733                width -= 1;
11734            }
11735            while width > k && l < n {
11736                *s.add(l) = b'0' as c_char;
11737                l += 1;
11738                width -= 1;
11739            }
11740        }
11741        let copy = if k > n - l { n - l } else { k };
11742        core::ptr::copy_nonoverlapping(t, s.add(l) as *mut u8, copy);
11743        l += copy;
11744        fi += 1;
11745    }
11746    if n > 0 {
11747        if l == n { l = n - 1; }
11748        *s.add(l) = 0;
11749    }
11750    0
11751}
11752
11753#[no_mangle]
11754pub unsafe extern "C" fn strftime(s: *mut c_char, maxsize: usize, fmt: *const c_char, tm: *const tm) -> usize {
11755    __strftime_l(s, maxsize, fmt, tm)
11756}
11757
11758// ============================================================
11759// Time: strptime
11760// ============================================================
11761
11762unsafe fn match_prefix(s: *const u8, prefix: &[u8]) -> bool {
11763    for i in 0..prefix.len() {
11764        if *s.add(i) == 0 || *s.add(i) != prefix[i] { return false; }
11765    }
11766    true
11767}
11768
11769unsafe fn match_ci_prefix(s: *const u8, prefix: &[u8]) -> bool {
11770    for i in 0..prefix.len() {
11771        let c = *s.add(i);
11772        if c == 0 { return false; }
11773        if c.to_ascii_lowercase() != prefix[i].to_ascii_lowercase() { return false; }
11774    }
11775    true
11776}
11777
11778unsafe fn parse_int(p: *const u8, max_digits: usize) -> (i32, *const u8) {
11779    let mut val = 0i32;
11780    let mut np = p;
11781    let mut count = 0;
11782    while *np >= b'0' && *np <= b'9' && count < max_digits {
11783        val = val * 10 + (*np - b'0') as i32;
11784        np = np.add(1);
11785        count += 1;
11786    }
11787    if count == 0 { (0, p) } else { (val, np) }
11788}
11789
11790unsafe fn parse_range(p: *const u8, min: i32, max: i32) -> (i32, *const u8) {
11791    let (val, np) = parse_int(p, 4);
11792    if np == p || val < min || val > max { (0, p) } else { (val, np) }
11793}
11794
11795fn is_ascii_space(c: u8) -> bool {
11796    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == 0x0c || c == 0x0b
11797}
11798
11799#[no_mangle]
11800pub unsafe extern "C" fn strptime(s: *const c_char, fmt: *const c_char, tm: *mut tm) -> *mut c_char {
11801    let mut p = s as *const u8;
11802    let mut f = fmt as *const u8;
11803    let mut want_century = 0i32;
11804    let mut century = 0i32;
11805    let mut relyear = 0i32;
11806    while *f != 0 {
11807        if *f != b'%' {
11808            if is_ascii_space(*f) {
11809                while *p != 0 && is_ascii_space(*p) { p = p.add(1); }
11810            } else {
11811                if *p != *f { return core::ptr::null_mut(); }
11812                p = p.add(1);
11813            }
11814            f = f.add(1);
11815            continue;
11816        }
11817        f = f.add(1);
11818        if *f == b'+' { f = f.add(1); }
11819        while *f >= b'0' && *f <= b'9' { f = f.add(1); }
11820        if *f == b'E' || *f == b'O' { f = f.add(1); }
11821        match *f {
11822            b'a' | b'A' => {
11823                let mut found = false;
11824                for i in 0..7 {
11825                    let names: [&[u8]; 7] = [b"Sunday", b"Monday", b"Tuesday", b"Wednesday", b"Thursday", b"Friday", b"Saturday"];
11826                    let snames: [&[u8]; 7] = [b"Sun", b"Mon", b"Tue", b"Wed", b"Thu", b"Fri", b"Sat"];
11827                    if match_prefix(p, names[i]) { (*tm).tm_wday = i as c_int; p = p.add(names[i].len()); found = true; break; }
11828                    if match_prefix(p, snames[i]) { (*tm).tm_wday = i as c_int; p = p.add(snames[i].len()); found = true; break; }
11829                }
11830                if !found { return core::ptr::null_mut(); }
11831            }
11832            b'b' | b'B' | b'h' => {
11833                let mut found = false;
11834                for i in 0..12 {
11835                    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"];
11836                    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"];
11837                    if match_prefix(p, names[i]) { (*tm).tm_mon = i as c_int; p = p.add(names[i].len()); found = true; break; }
11838                    if match_prefix(p, snames[i]) { (*tm).tm_mon = i as c_int; p = p.add(snames[i].len()); found = true; break; }
11839                }
11840                if !found { return core::ptr::null_mut(); }
11841            }
11842            b'C' => {
11843                let (v, np) = parse_int(p, 2);
11844                if np == p { return core::ptr::null_mut(); }
11845                century = v;
11846                want_century |= 2;
11847                p = np;
11848            }
11849            b'd' | b'e' => {
11850                let (v, np) = parse_range(p, 1, 31);
11851                if np == p { return core::ptr::null_mut(); }
11852                (*tm).tm_mday = v;
11853                p = np;
11854            }
11855            b'D' => {
11856                let r = strptime(p as *const c_char, b"%m/%d/%y\0".as_ptr() as *const c_char, tm);
11857                if r.is_null() { return core::ptr::null_mut(); }
11858                p = r as *const u8;
11859            }
11860            b'F' => {
11861                let (yv, ynp) = parse_int(p, 4);
11862                if ynp == p { return core::ptr::null_mut(); }
11863                (*tm).tm_year = yv - 1900;
11864                p = ynp;
11865                if *p != b'-' { return core::ptr::null_mut(); }
11866                p = p.add(1);
11867                let (mv, mnp) = parse_range(p, 1, 12);
11868                if mnp == p { return core::ptr::null_mut(); }
11869                (*tm).tm_mon = mv - 1;
11870                p = mnp;
11871                if *p != b'-' { return core::ptr::null_mut(); }
11872                p = p.add(1);
11873                let (dv, dnp) = parse_range(p, 1, 31);
11874                if dnp == p { return core::ptr::null_mut(); }
11875                (*tm).tm_mday = dv;
11876                p = dnp;
11877            }
11878            b'H' | b'I' => {
11879                let (v, np) = parse_range(p, 0, 23);
11880                if np == p { return core::ptr::null_mut(); }
11881                (*tm).tm_hour = v;
11882                p = np;
11883            }
11884            b'j' => {
11885                let (v, np) = parse_range(p, 1, 366);
11886                if np == p { return core::ptr::null_mut(); }
11887                (*tm).tm_yday = v - 1;
11888                p = np;
11889            }
11890            b'm' => {
11891                let (v, np) = parse_range(p, 1, 12);
11892                if np == p { return core::ptr::null_mut(); }
11893                (*tm).tm_mon = v - 1;
11894                p = np;
11895            }
11896            b'M' => {
11897                let (v, np) = parse_range(p, 0, 59);
11898                if np == p { return core::ptr::null_mut(); }
11899                (*tm).tm_min = v;
11900                p = np;
11901            }
11902            b'n' | b't' => {
11903                while *p != 0 && is_ascii_space(*p) { p = p.add(1); }
11904            }
11905            b'p' => {
11906                if match_ci_prefix(p, b"AM") {
11907                    if (*tm).tm_hour == 12 { (*tm).tm_hour = 0; }
11908                    p = p.add(2);
11909                } else if match_ci_prefix(p, b"PM") {
11910                    if (*tm).tm_hour < 12 { (*tm).tm_hour += 12; }
11911                    p = p.add(2);
11912                } else { return core::ptr::null_mut(); }
11913            }
11914            b'r' => {
11915                let r = strptime(p as *const c_char, b"%I:%M:%S %p\0".as_ptr() as *const c_char, tm);
11916                if r.is_null() { return core::ptr::null_mut(); }
11917                p = r as *const u8;
11918            }
11919            b'R' => {
11920                let r = strptime(p as *const c_char, b"%H:%M\0".as_ptr() as *const c_char, tm);
11921                if r.is_null() { return core::ptr::null_mut(); }
11922                p = r as *const u8;
11923            }
11924            b's' => {
11925                let neg = if *p == b'-' { p = p.add(1); true } else { false };
11926                if *p < b'0' || *p > b'9' { return core::ptr::null_mut(); }
11927                let mut val = 0i64;
11928                while *p >= b'0' && *p <= b'9' {
11929                    val = val * 10 + (*p - b'0') as i64;
11930                    p = p.add(1);
11931                }
11932                if neg { val = -val; }
11933                secs_to_tm(val, &mut *tm);
11934            }
11935            b'S' => {
11936                let (v, np) = parse_range(p, 0, 60);
11937                if np == p { return core::ptr::null_mut(); }
11938                (*tm).tm_sec = v;
11939                p = np;
11940            }
11941            b'T' => {
11942                let r = strptime(p as *const c_char, b"%H:%M:%S\0".as_ptr() as *const c_char, tm);
11943                if r.is_null() { return core::ptr::null_mut(); }
11944                p = r as *const u8;
11945            }
11946            b'U' | b'W' => {
11947                let (_, np) = parse_range(p, 0, 53);
11948                if np == p { return core::ptr::null_mut(); }
11949                p = np;
11950            }
11951            b'V' => {
11952                let (_, np) = parse_range(p, 1, 53);
11953                if np == p { return core::ptr::null_mut(); }
11954                p = np;
11955            }
11956            b'w' => {
11957                let (v, np) = parse_range(p, 0, 6);
11958                if np == p { return core::ptr::null_mut(); }
11959                (*tm).tm_wday = v;
11960                p = np;
11961            }
11962            b'y' => {
11963                let (v, np) = parse_int(p, 2);
11964                if np == p { return core::ptr::null_mut(); }
11965                relyear = v;
11966                want_century |= 1;
11967                p = np;
11968            }
11969            b'Y' => {
11970                let neg = if *p == b'-' { p = p.add(1); true } else { false };
11971                let (v, np) = parse_int(p, 4);
11972                if np == p { return core::ptr::null_mut(); }
11973                (*tm).tm_year = if neg { -(v + 1900) } else { v - 1900 };
11974                want_century = 0;
11975                p = np;
11976            }
11977            b'z' => {
11978                if *p != b'+' && *p != b'-' { return core::ptr::null_mut(); }
11979                let neg = *p == b'-';
11980                p = p.add(1);
11981                let mut off = 0i64;
11982                let mut digits = 0;
11983                while digits < 4 && *p >= b'0' && *p <= b'9' {
11984                    off = off * 10 + (*p - b'0') as i64;
11985                    p = p.add(1);
11986                    digits += 1;
11987                }
11988                if digits == 0 { return core::ptr::null_mut(); }
11989                let (hh, mm) = if digits <= 2 { (off, 0i64) } else { (off / 100, off % 100) };
11990                (*tm).tm_gmtoff = (hh * 3600 + mm * 60) * if neg { -1 } else { 1 };
11991            }
11992            b'Z' => {
11993                let mut matched = false;
11994                for i in 0..2 {
11995                    let name = crate::tzname[i];
11996                    if name.is_null() { continue; }
11997                    let len = strlen(name);
11998                    if strncmp(p, name as *const u8, len) == 0 {
11999                        (*tm).tm_isdst = i as c_int;
12000                        p = p.add(len);
12001                        matched = true;
12002                        break;
12003                    }
12004                }
12005                if !matched {
12006                    // No match: skip an alphabetic zone abbreviation.
12007                    while *p != 0 && (*p | 32).wrapping_sub(b'a') <= 25 { p = p.add(1); }
12008                }
12009            }
12010            b'%' => {
12011                if *p != b'%' { return core::ptr::null_mut(); }
12012                p = p.add(1);
12013            }
12014            _ => { return core::ptr::null_mut(); }
12015        }
12016        f = f.add(1);
12017    }
12018    if want_century != 0 {
12019        (*tm).tm_year = relyear;
12020        if want_century & 2 != 0 { (*tm).tm_year += century * 100 - 1900; }
12021        else if (*tm).tm_year <= 68 { (*tm).tm_year += 100; }
12022    }
12023    p as *mut c_char
12024}
12025
12026// ============================================================
12027// Time: tzset / daylight / timezone / tzname
12028// ============================================================
12029
12030#[no_mangle]
12031pub static mut daylight: c_int = 0;
12032#[no_mangle]
12033pub static mut timezone: c_long = 0;
12034#[no_mangle]
12035pub 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];
12036
12037#[no_mangle]
12038pub unsafe extern "C" fn tzset() {
12039    tz_set();
12040}
12041
12042// ============================================================
12043// system()
12044// ============================================================
12045
12046#[no_mangle]
12047pub unsafe extern "C" fn system(cmd: *const c_char) -> c_int {
12048    if cmd.is_null() {
12049        // test shell availability via fork+exec
12050        let pid = sys_fork();
12051        if pid == 0 {
12052            let sh = b"/bin/sh\0".as_ptr() as *const c_char;
12053            let dash_c = b"-c\0".as_ptr() as *const c_char;
12054            let exit0 = b"exit 0\0".as_ptr() as *const c_char;
12055            let argv = [b"sh\0".as_ptr() as *const c_char, dash_c, exit0, core::ptr::null()];
12056            sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
12057            _exit(127);
12058        }
12059        if pid < 0 { return -1; }
12060        let mut status: c_int = 0;
12061        loop {
12062            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
12063            if r >= 0 { return status; }
12064            if r != -4 { return -1; } // not EINTR
12065        }
12066    }
12067
12068    let sa_ignore = KSigAction {
12069        sa_handler: SIG_IGN,
12070        sa_flags: SA_RESTORER,
12071        sa_restorer: sig_restorer as *const () as usize,
12072        sa_mask: [0],
12073    };
12074    let mut oldint: KSigAction = core::mem::zeroed();
12075    let mut oldquit: KSigAction = core::mem::zeroed();
12076
12077    sys_rt_sigaction(SIGINT, &sa_ignore, &mut oldint, 8);
12078    sys_rt_sigaction(SIGQUIT, &sa_ignore, &mut oldquit, 8);
12079
12080    let mut block_set: SigSetT = 0;
12081    block_set |= 1u64 << (SIGCHLD - 1);
12082    let mut oldmask: SigSetT = 0;
12083    sys_rt_sigprocmask(SIG_BLOCK, &block_set, &mut oldmask, 8);
12084
12085    let pid = sys_fork();
12086
12087    if pid == 0 {
12088        sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
12089        sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
12090        sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
12091
12092        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
12093        let argv = [
12094            b"sh\0".as_ptr() as *const c_char,
12095            b"-c\0".as_ptr() as *const c_char,
12096            cmd,
12097            core::ptr::null(),
12098        ];
12099        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
12100        _exit(127);
12101    }
12102
12103    let mut status: c_int = -1;
12104    if pid > 0 {
12105        loop {
12106            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
12107            if r >= 0 { break; }
12108            if r != -4 { break; } // not EINTR
12109        }
12110    }
12111
12112    sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
12113    sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
12114    sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
12115
12116    status
12117}
12118
12119// ============================================================
12120// errno: strerror / strerror_r / environ alias
12121// ============================================================
12122
12123// static error string table indexed by errno
12124static ERR_STRS: [&[u8]; 134] = [
12125    b"Success\0",                     // 0
12126    b"Operation not permitted\0",     // 1
12127    b"No such file or directory\0",   // 2
12128    b"No such process\0",             // 3
12129    b"Interrupted system call\0",     // 4
12130    b"Input/output error\0",          // 5
12131    b"No such device or address\0",   // 6
12132    b"Argument list too long\0",      // 7
12133    b"Exec format error\0",           // 8
12134    b"Bad file descriptor\0",         // 9
12135    b"No child processes\0",          // 10
12136    b"Resource temporarily unavailable\0", // 11
12137    b"Cannot allocate memory\0",      // 12
12138    b"Permission denied\0",           // 13
12139    b"Bad address\0",                 // 14
12140    b"Block device required\0",       // 15
12141    b"Device or resource busy\0",     // 16
12142    b"File exists\0",                 // 17
12143    b"Invalid cross-device link\0",   // 18
12144    b"No such device\0",              // 19
12145    b"Not a directory\0",             // 20
12146    b"Is a directory\0",              // 21
12147    b"Invalid argument\0",            // 22
12148    b"Too many open files in system\0", // 23
12149    b"Too many open files\0",         // 24
12150    b"Inappropriate ioctl for device\0", // 25
12151    b"Text file busy\0",              // 26
12152    b"File too large\0",              // 27
12153    b"No space left on device\0",     // 28
12154    b"Illegal seek\0",                // 29
12155    b"Read-only file system\0",       // 30
12156    b"Too many links\0",              // 31
12157    b"Broken pipe\0",                 // 32
12158    b"Numerical argument out of domain\0", // 33
12159    b"Numerical result out of range\0", // 34
12160    b"Resource deadlock avoided\0",   // 35
12161    b"File name too long\0",          // 36
12162    b"No locks available\0",          // 37
12163    b"Function not implemented\0",    // 38
12164    b"Directory not empty\0",         // 39
12165    b"Too many levels of symbolic links\0", // 40
12166    b"Unknown error 41\0",            // 41
12167    b"No message of desired type\0",  // 42
12168    b"Identifier removed\0",          // 43
12169    b"Channel number out of range\0", // 44
12170    b"Level 2 not synchronized\0",    // 45
12171    b"Level 3 halted\0",              // 46
12172    b"Level 3 reset\0",               // 47
12173    b"Link number out of range\0",    // 48
12174    b"Protocol driver not attached\0", // 49
12175    b"No CSI structure available\0",  // 50
12176    b"Level 2 halted\0",              // 51
12177    b"Invalid exchange\0",            // 52
12178    b"Invalid request descriptor\0",  // 53
12179    b"Exchange full\0",               // 54
12180    b"No anode\0",                    // 55
12181    b"Invalid request code\0",        // 56
12182    b"Invalid slot\0",                // 57
12183    b"Unknown error 58\0",            // 58
12184    b"Bad font file format\0",        // 59
12185    b"Device not a stream\0",         // 60
12186    b"No data available\0",           // 61
12187    b"Timer expired\0",               // 62
12188    b"Out of streams resources\0",    // 63
12189    b"Machine is not on the network\0", // 64
12190    b"Package not installed\0",       // 65
12191    b"Object is remote\0",            // 66
12192    b"Link has been severed\0",       // 67
12193    b"Advertise error\0",             // 68
12194    b"Srmount error\0",               // 69
12195    b"Communication error on send\0", // 70
12196    b"Protocol error\0",              // 71
12197    b"Multihop attempted\0",          // 72
12198    b"RFS specific error\0",          // 73
12199    b"Bad message\0",                 // 74
12200    b"Value too large for defined data type\0", // 75
12201    b"Name not unique on network\0",  // 76
12202    b"File descriptor in bad state\0", // 77
12203    b"Remote address changed\0",      // 78
12204    b"Can not access a needed shared library\0", // 79
12205    b"Accessing a corrupted shared library\0", // 80
12206    b".lib section in a.out corrupted\0", // 81
12207    b"Attempting to link in too many shared libraries\0", // 82
12208    b"Cannot exec a shared library directly\0", // 83
12209    b"Invalid or incomplete multibyte or wide character\0", // 84
12210    b"Interrupted system call should be restarted\0", // 85
12211    b"Streams pipe error\0",          // 86
12212    b"Too many users\0",              // 87
12213    b"Socket operation on non-socket\0", // 88
12214    b"Destination address required\0", // 89
12215    b"Message too long\0",            // 90
12216    b"Protocol wrong type for socket\0", // 91
12217    b"Protocol not available\0",      // 92
12218    b"Protocol not supported\0",      // 93
12219    b"Socket type not supported\0",   // 94
12220    b"Operation not supported\0",     // 95
12221    b"Protocol family not supported\0", // 96
12222    b"Address family not supported by protocol\0", // 97
12223    b"Address already in use\0",      // 98
12224    b"Cannot assign requested address\0", // 99
12225    b"Network is down\0",             // 100
12226    b"Network is unreachable\0",      // 101
12227    b"Network dropped connection on reset\0", // 102
12228    b"Software caused connection abort\0", // 103
12229    b"Connection reset by peer\0",    // 104
12230    b"No buffer space available\0",   // 105
12231    b"Transport endpoint is already connected\0", // 106
12232    b"Transport endpoint is not connected\0", // 107
12233    b"Cannot send after transport endpoint shutdown\0", // 108
12234    b"Too many references: cannot splice\0", // 109
12235    b"Connection timed out\0",        // 110
12236    b"Connection refused\0",          // 111
12237    b"Host is down\0",                // 112
12238    b"No route to host\0",            // 113
12239    b"Operation already in progress\0", // 114
12240    b"Operation now in progress\0",   // 115
12241    b"Stale file handle\0",           // 116
12242    b"Structure needs cleaning\0",    // 117
12243    b"Not a XENIX named type file\0", // 118
12244    b"No XENIX semaphores available\0", // 119
12245    b"Is a named type file\0",        // 120
12246    b"Remote I/O error\0",            // 121
12247    b"Quota exceeded\0",              // 122
12248    b"No medium found\0",             // 123
12249    b"Wrong medium type\0",           // 124
12250    b"Operation canceled\0",          // 125
12251    b"Required key not available\0",  // 126
12252    b"Key has expired\0",             // 127
12253    b"Key has been revoked\0",        // 128
12254    b"Key was rejected by service\0", // 129
12255    b"Owner died\0",                  // 130
12256    b"State not recoverable\0",       // 131
12257    b"Operation not possible due to RF-kill\0", // 132
12258    b"Memory page has hardware error\0", // 133
12259];
12260
12261#[no_mangle]
12262pub unsafe extern "C" fn strerror(errnum: c_int) -> *mut c_char {
12263    if errnum < 0 || errnum as usize >= ERR_STRS.len() {
12264        // static buf for unknown errors
12265        static mut UNKNOWN_BUF: [c_char; 64] = [0; 64];
12266        let prefix = b"Unknown error \0";
12267        let mut i = 0;
12268        while prefix[i] != 0 {
12269            UNKNOWN_BUF[i] = prefix[i] as c_char;
12270            i += 1;
12271        }
12272        let (buf, len) = format_u64(errnum.unsigned_abs() as u64);
12273        for j in 0..len {
12274            UNKNOWN_BUF[i] = buf[20 - len + j] as c_char;
12275            i += 1;
12276        }
12277        UNKNOWN_BUF[i] = 0;
12278        return core::ptr::addr_of_mut!(UNKNOWN_BUF).cast::<c_char>();
12279    }
12280    ERR_STRS[errnum as usize].as_ptr() as *mut c_char
12281}
12282
12283#[no_mangle]
12284pub unsafe extern "C" fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: usize) -> c_int {
12285    let s = strerror(errnum);
12286    let slen = strlen(s as *const c_char);
12287    if slen >= buflen {
12288        if buflen > 0 {
12289            core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, buflen - 1);
12290            *buf.add(buflen - 1) = 0;
12291        }
12292        return 34; // ERANGE
12293    }
12294    core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, slen + 1);
12295    0
12296}
12297
12298// Alias for programs that declare `extern char **environ`.
12299#[no_mangle]
12300pub static mut environ: *mut *mut c_char = core::ptr::null_mut();
12301
12302// keep environ in sync with __environ
12303unsafe fn sync_environ() {
12304    environ = __environ;
12305}
12306
12307// ============================================================
12308// unistd extensions: pipe, dup, dup2, fcntl, access, unlink, etc.
12309// ============================================================
12310
12311#[inline]
12312unsafe fn sys_dup(oldfd: i32) -> i64 {
12313    <Arch as Syscalls>::syscall1(SYS_DUP, oldfd as i64)
12314}
12315
12316#[inline]unsafe fn sys_dup2(oldfd: i32, newfd: i32) -> i64 {
12317    // dup3 with flags=0 is equivalent to dup2
12318    sys_dup3(oldfd, newfd, 0)
12319}
12320
12321#[inline]
12322unsafe fn sys_access(path: *const u8, mode: i32) -> i64 {
12323    <Arch as Syscalls>::syscall4(SYS_FACCESSAT, AT_FDCWD as i64, path as i64, mode as i64, 0)
12324}
12325
12326#[inline]unsafe fn sys_unlink(path: *const u8) -> i64 {
12327    sys_unlinkat(AT_FDCWD, path, 0)
12328}
12329
12330#[inline]unsafe fn sys_rmdir(path: *const u8) -> i64 {
12331    sys_unlinkat(AT_FDCWD, path, 512) // AT_REMOVEDIR
12332}
12333
12334#[inline]
12335unsafe fn sys_chdir(path: *const u8) -> i64 {
12336    <Arch as Syscalls>::syscall1(SYS_CHDIR, path as i64)
12337}
12338
12339#[inline]
12340unsafe fn sys_getcwd(buf: *mut u8, size: usize) -> i64 {
12341    <Arch as Syscalls>::syscall2(SYS_GETCWD, buf as i64, size as i64)
12342}
12343
12344#[inline]
12345unsafe fn sys_sethostname(name: *const u8, len: usize) -> i64 {
12346    <Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)
12347}
12348
12349#[inline]
12350unsafe fn sys_gethostname(buf: *mut u8, len: usize) -> i64 {
12351    #[repr(C)]
12352    struct UtsName {
12353        sysname: [u8; 65],
12354        nodename: [u8; 65],
12355        release: [u8; 65],
12356        version: [u8; 65],
12357        machine: [u8; 65],
12358        domainname: [u8; 65],
12359    }
12360    let mut uts: UtsName = core::mem::zeroed();
12361    let result = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
12362    if result < 0 {
12363        return result;
12364    }
12365    let nlen = strlen(uts.nodename.as_ptr() as *const c_char);
12366    let copylen = if nlen < len { nlen } else { if len > 0 { len - 1 } else { 0 } };
12367    core::ptr::copy_nonoverlapping(uts.nodename.as_ptr(), buf, copylen);
12368    if len > 0 { *buf.add(copylen) = 0; }
12369    0
12370}
12371
12372unsafe fn sys_truncate(path: *const u8, length: i64) -> i64 {
12373    <Arch as Syscalls>::syscall2(SYS_TRUNCATE, path as i64, length as i64)
12374}
12375
12376unsafe fn sys_ftruncate(fd: i32, length: i64) -> i64 {
12377    <Arch as Syscalls>::syscall2(SYS_FTRUNCATE, fd as i64, length as i64)
12378}
12379
12380unsafe fn sys_nanosleep(req: *const timespec, rem: *mut timespec) -> i64 {
12381    <Arch as Syscalls>::syscall2(SYS_NANOSLEEP, req as i64, rem as i64)
12382}
12383
12384const ITIMER_REAL: i32 = 0;
12385
12386#[repr(C)]
12387struct itimerval {
12388    it_interval: timeval,
12389    it_value: timeval,
12390}
12391
12392unsafe fn sys_alarm(seconds: c_uint) -> i64 {
12393    let mut new: itimerval = core::mem::zeroed();
12394    new.it_value.tv_sec = seconds as c_long;
12395    let mut old: itimerval = core::mem::zeroed();
12396    let r = <Arch as Syscalls>::syscall3(
12397        SYS_SETITIMER,
12398        ITIMER_REAL as i64,
12399        &new as *const _ as i64,
12400        &mut old as *mut _ as i64,
12401    );
12402    if r < 0 {
12403        return r;
12404    }
12405    old.it_value.tv_sec as i64 + (old.it_value.tv_usec != 0) as i64
12406}
12407
12408unsafe fn sys_pause() -> i64 {
12409    #[cfg(target_arch = "x86_64")]
12410    { <Arch as Syscalls>::syscall0(SYS_PAUSE) }
12411    #[cfg(target_arch = "aarch64")]
12412    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
12413    #[cfg(target_arch = "riscv64")]
12414    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
12415}
12416
12417unsafe fn sys_fsync(fd: i32) -> i64 {
12418    <Arch as Syscalls>::syscall1(SYS_FSYNC, fd as i64)
12419}
12420
12421unsafe fn sys_fdatasync(fd: i32) -> i64 {
12422    <Arch as Syscalls>::syscall1(SYS_FDATASYNC, fd as i64)
12423}
12424
12425unsafe fn sys_sync() {
12426    let _ = <Arch as Syscalls>::syscall0(SYS_SYNC);
12427}
12428
12429unsafe fn sys_symlink(target: *const u8, linkpath: *const u8) -> i64 {
12430    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, AT_FDCWD as i64, linkpath as i64)
12431}
12432
12433unsafe fn sys_symlinkat(target: *const u8, newdirfd: i32, linkpath: *const u8) -> i64 {
12434    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)
12435}
12436
12437unsafe fn sys_readlinkat(dirfd: i32, path: *const u8, buf: *mut u8, bufsiz: usize) -> i64 {
12438    <Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, path as i64, buf as i64, bufsiz as i64)
12439}
12440
12441unsafe fn sys_linkat(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: i32) -> i64 {
12442    <Arch as Syscalls>::syscall5(SYS_LINKAT, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
12443}
12444
12445unsafe fn sys_fchmod(fd: i32, mode: u32) -> i64 {
12446    <Arch as Syscalls>::syscall2(SYS_FCHMOD, fd as i64, mode as i64)
12447}
12448
12449unsafe fn sys_fchmodat(dirfd: i32, path: *const u8, mode: u32, flags: i32) -> i64 {
12450    <Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, path as i64, mode as i64, flags as i64)
12451}
12452
12453unsafe fn sys_umask(mask: u32) -> u32 {
12454    <Arch as Syscalls>::syscall1(SYS_UMASK, mask as i64) as u32
12455}
12456
12457unsafe fn sys_getgroups(size: i32, list: *mut c_uint) -> i64 {
12458    <Arch as Syscalls>::syscall2(SYS_GETGROUPS, size as i64, list as i64)
12459}
12460
12461unsafe fn sys_setuid(uid: c_uint) -> i64 {
12462    <Arch as Syscalls>::syscall1(SYS_SETUID, uid as i64)
12463}
12464
12465unsafe fn sys_setgid(gid: c_uint) -> i64 {
12466    <Arch as Syscalls>::syscall1(SYS_SETGID, gid as i64)
12467}
12468
12469unsafe fn sys_setsid() -> i64 {
12470    <Arch as Syscalls>::syscall0(SYS_SETSID)
12471}
12472
12473unsafe fn sys_setpgid(pid: c_int, pgid: c_int) -> i64 {
12474    <Arch as Syscalls>::syscall2(SYS_SETPGID, pid as i64, pgid as i64)
12475}
12476
12477unsafe fn sys_getpgid(pid: c_int) -> i64 {
12478    <Arch as Syscalls>::syscall1(SYS_GETPGID, pid as i64)
12479}
12480
12481unsafe fn sys_getsid(pid: c_int) -> i64 {
12482    <Arch as Syscalls>::syscall1(SYS_GETSID, pid as i64)
12483}
12484
12485unsafe fn sys_mkdirat(dirfd: i32, path: *const u8, mode: u32) -> i64 {
12486    <Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, path as i64, mode as i64)
12487}
12488
12489// Public C ABI wrappers for unistd
12490
12491#[no_mangle]
12492pub unsafe extern "C" fn pipe(fds: *mut c_int) -> c_int {
12493    let r = sys_pipe2(fds, 0);
12494    syscall_ret(r) as c_int
12495}
12496
12497#[no_mangle]
12498pub unsafe extern "C" fn pipe2(fds: *mut c_int, flags: c_int) -> c_int {
12499    let r = sys_pipe2(fds, flags);
12500    syscall_ret(r) as c_int
12501}
12502
12503#[no_mangle]
12504pub unsafe extern "C" fn dup(oldfd: c_int) -> c_int {
12505    let r = sys_dup(oldfd);
12506    syscall_ret(r) as c_int
12507}
12508
12509#[no_mangle]
12510pub unsafe extern "C" fn dup2(oldfd: c_int, newfd: c_int) -> c_int {
12511    if oldfd == newfd {
12512        // dup3 rejects equal descriptors with EINVAL; dup2 must validate the
12513        // descriptor and return newfd unchanged.
12514        let r = sys_fcntl(oldfd, 1 /* F_GETFD */, 0);
12515        if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12516        return newfd;
12517    }
12518    let r = sys_dup2(oldfd, newfd);
12519    syscall_ret(r) as c_int
12520}
12521
12522#[no_mangle]
12523pub unsafe extern "C" fn dup3(oldfd: c_int, newfd: c_int, flags: c_int) -> c_int {
12524    let r = sys_dup3(oldfd, newfd, flags);
12525    syscall_ret(r) as c_int
12526}
12527
12528#[no_mangle]
12529pub unsafe extern "C" fn fcntl(fd: c_int, cmd: c_int, mut args: ...) -> c_int {
12530    // Commands without an argument. Everything else (including seals,
12531    // pipe sizes, ownership and locks) takes the third argument.
12532    let no_arg = matches!(cmd, 1 /* F_GETFD */ | 3 /* F_GETFL */ | 9 /* F_GETOWN */
12533        | 11 /* F_GETSIG */ | 1025 /* F_GETLEASE */ | 1032 /* F_GETPIPE_SZ */
12534        | 1034 /* F_GET_SEALS */);
12535    let r = if no_arg {
12536        sys_fcntl(fd, cmd, 0)
12537    } else {
12538        let arg = args.next_arg::<c_long>();
12539        sys_fcntl(fd, cmd, arg)
12540    };
12541    syscall_ret(r) as c_int
12542}
12543
12544#[no_mangle]
12545pub unsafe extern "C" fn access(path: *const c_char, mode: c_int) -> c_int {
12546    let r = sys_access(path as *const u8, mode);
12547    syscall_ret(r) as c_int
12548}
12549
12550#[no_mangle]
12551pub unsafe extern "C" fn unlink(path: *const c_char) -> c_int {
12552    let r = sys_unlink(path as *const u8);
12553    syscall_ret(r) as c_int
12554}
12555
12556#[no_mangle]
12557pub unsafe extern "C" fn rmdir(path: *const c_char) -> c_int {
12558    let r = sys_rmdir(path as *const u8);
12559    syscall_ret(r) as c_int
12560}
12561
12562#[no_mangle]
12563pub unsafe extern "C" fn chdir(path: *const c_char) -> c_int {
12564    let r = sys_chdir(path as *const u8);
12565    syscall_ret(r) as c_int
12566}
12567
12568#[no_mangle]
12569pub unsafe extern "C" fn getcwd(buf: *mut c_char, size: usize) -> *mut c_char {
12570    if buf.is_null() {
12571        // allocate
12572        let alloc_size = if size == 0 { 256 } else { size };
12573        let p = malloc(alloc_size) as *mut c_char;
12574        if p.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
12575        let r = sys_getcwd(p as *mut u8, alloc_size);
12576        if r < 0 { free(p as *mut c_void); ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
12577        // The kernel returns "(unreachable)..." when cwd is outside the
12578        // current root; POSIX getcwd must fail with ENOENT in that case.
12579        if *p as u8 != b'/' {
12580            free(p as *mut c_void);
12581            ERRNO!() = 2;
12582            return core::ptr::null_mut();
12583        }
12584        return p;
12585    }
12586    if size == 0 { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
12587    let r = sys_getcwd(buf as *mut u8, size);
12588    if r < 0 { ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
12589    if *buf as u8 != b'/' {
12590        ERRNO!() = 2;
12591        return core::ptr::null_mut();
12592    }
12593    buf
12594}
12595
12596#[no_mangle]
12597pub unsafe extern "C" fn gethostname(name: *mut c_char, len: usize) -> c_int {
12598    let r = sys_gethostname(name as *mut u8, len);
12599    syscall_ret(r) as c_int
12600}
12601
12602// Linux page size.  This is hardcoded to 4096 on every architecture; that
12603// is correct for the CI hosts but not for aarch64/riscv64 kernels with a
12604// larger base page size.  See sysconf(_SC_PAGE_SIZE) for the same value.
12605#[no_mangle]
12606pub extern "C" fn getpagesize() -> c_int {
12607    4096
12608}
12609
12610#[no_mangle]
12611pub unsafe extern "C" fn truncate(path: *const c_char, length: i64) -> c_int {
12612    let r = sys_truncate(path as *const u8, length);
12613    syscall_ret(r) as c_int
12614}
12615
12616#[no_mangle]
12617pub unsafe extern "C" fn ftruncate(fd: c_int, length: i64) -> c_int {
12618    let r = sys_ftruncate(fd, length);
12619    syscall_ret(r) as c_int
12620}
12621
12622#[no_mangle]
12623pub unsafe extern "C" fn nanosleep(req: *const timespec, rem: *mut timespec) -> c_int {
12624    pthread_testcancel();
12625    let r = sys_nanosleep(req, rem);
12626    pthread_testcancel();
12627    syscall_ret(r) as c_int
12628}
12629
12630#[no_mangle]
12631pub unsafe extern "C" fn sleep(seconds: c_uint) -> c_uint {
12632    let req = timespec { tv_sec: seconds as c_long, tv_nsec: 0 };
12633    let mut rem: timespec = core::mem::zeroed();
12634    pthread_testcancel();
12635    let r = sys_nanosleep(&req, &mut rem);
12636    pthread_testcancel();
12637    if r < 0 {
12638        let e = (-r) as c_int;
12639        if e == EINTR { return rem.tv_sec as c_uint; }
12640    }
12641    0
12642}
12643
12644#[no_mangle]
12645pub unsafe extern "C" fn usleep(usec: c_uint) -> c_int {
12646    let req = timespec { tv_sec: (usec / 1000000) as c_long, tv_nsec: ((usec % 1000000) * 1000) as c_long };
12647    pthread_testcancel();
12648    let r = sys_nanosleep(&req, core::ptr::null_mut());
12649    pthread_testcancel();
12650    syscall_ret(r) as c_int
12651}
12652
12653#[no_mangle]
12654pub unsafe extern "C" fn alarm(seconds: c_uint) -> c_uint {
12655    // POSIX rounds a nonzero fractional remainder up to one second;
12656    // sys_alarm() already performs that rounding.
12657    let r = sys_alarm(seconds);
12658    if r < 0 { 0 } else { r as c_uint }
12659}
12660
12661#[no_mangle]
12662pub unsafe extern "C" fn pause() -> c_int {
12663    pthread_testcancel();
12664    sys_pause();
12665    pthread_testcancel();
12666    ERRNO!() = EINTR;
12667    -1
12668}
12669
12670#[no_mangle]
12671pub unsafe extern "C" fn fsync(fd: c_int) -> c_int {
12672    let r = sys_fsync(fd);
12673    syscall_ret(r) as c_int
12674}
12675
12676#[no_mangle]
12677pub unsafe extern "C" fn fdatasync(fd: c_int) -> c_int {
12678    let r = sys_fdatasync(fd);
12679    syscall_ret(r) as c_int
12680}
12681
12682#[no_mangle]
12683pub unsafe extern "C" fn sync() {
12684    sys_sync();
12685}
12686
12687#[no_mangle]
12688pub unsafe extern "C" fn symlink(target: *const c_char, linkpath: *const c_char) -> c_int {
12689    let r = sys_symlinkat(target as *const u8, AT_FDCWD, linkpath as *const u8);
12690    syscall_ret(r) as c_int
12691}
12692
12693#[no_mangle]
12694pub unsafe extern "C" fn readlink(path: *const c_char, buf: *mut c_char, bufsiz: usize) -> isize {
12695    let r = sys_readlinkat(AT_FDCWD, path as *const u8, buf as *mut u8, bufsiz);
12696    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12697    r as isize
12698}
12699
12700#[no_mangle]
12701pub unsafe extern "C" fn link(oldpath: *const c_char, newpath: *const c_char) -> c_int {
12702    let r = sys_linkat(AT_FDCWD, oldpath as *const u8, AT_FDCWD, newpath as *const u8, 0);
12703    syscall_ret(r) as c_int
12704}
12705
12706#[no_mangle]
12707pub unsafe extern "C" fn chmod(path: *const c_char, mode: c_uint) -> c_int {
12708    let r = sys_fchmodat(AT_FDCWD, path as *const u8, mode, 0);
12709    syscall_ret(r) as c_int
12710}
12711
12712#[no_mangle]
12713pub unsafe extern "C" fn fchmod(fd: c_int, mode: c_uint) -> c_int {
12714    let r = sys_fchmod(fd, mode);
12715    syscall_ret(r) as c_int
12716}
12717
12718#[no_mangle]
12719pub unsafe extern "C" fn umask(mask: c_uint) -> c_uint {
12720    sys_umask(mask) as c_uint
12721}
12722
12723#[no_mangle]
12724pub unsafe extern "C" fn isatty(fd: c_int) -> c_int {
12725    let mut ws: winsize = core::mem::zeroed();
12726    if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 { 1 } else { 0 }
12727}
12728
12729#[no_mangle]
12730pub unsafe extern "C" fn getlogin() -> *mut c_char {
12731    crate::getenv(b"LOGNAME\0".as_ptr() as *const c_char)
12732}
12733
12734#[no_mangle]
12735pub unsafe extern "C" fn getgroups(size: c_int, list: *mut c_uint) -> c_int {
12736    let r = sys_getgroups(size, list);
12737    syscall_ret(r) as c_int
12738}
12739
12740#[no_mangle]
12741pub unsafe extern "C" fn setuid(uid: c_uint) -> c_int {
12742    let r = sys_setuid(uid);
12743    syscall_ret(r) as c_int
12744}
12745
12746#[no_mangle]
12747pub unsafe extern "C" fn setgid(gid: c_uint) -> c_int {
12748    let r = sys_setgid(gid);
12749    syscall_ret(r) as c_int
12750}
12751
12752#[no_mangle]
12753pub unsafe extern "C" fn seteuid(euid: c_uint) -> c_int {
12754    // Setting only the effective uid must keep the real and saved uids, so a
12755    // process can drop privileges and later restore them (setuid would clear
12756    // the saved uid for root).
12757    setresuid(u32::MAX, euid, u32::MAX)
12758}
12759
12760#[no_mangle]
12761pub unsafe extern "C" fn setegid(egid: c_uint) -> c_int {
12762    setresgid(u32::MAX, egid, u32::MAX)
12763}
12764
12765#[no_mangle]
12766pub unsafe extern "C" fn setreuid(ruid: c_uint, euid: c_uint) -> c_int {
12767    let r = <Arch as Syscalls>::syscall2(sysno(113, 145), ruid as i64, euid as i64);
12768    syscall_ret(r) as c_int
12769}
12770
12771
12772
12773#[no_mangle]
12774pub unsafe extern "C" fn setsid() -> c_int {
12775    let r = sys_setsid();
12776    syscall_ret(r) as c_int
12777}
12778
12779#[no_mangle]
12780pub unsafe extern "C" fn setpgid(pid: c_int, pgid: c_int) -> c_int {
12781    let r = sys_setpgid(pid, pgid);
12782    syscall_ret(r) as c_int
12783}
12784
12785#[no_mangle]
12786pub unsafe extern "C" fn getpgid(pid: c_int) -> c_int {
12787    let r = sys_getpgid(pid);
12788    syscall_ret(r) as c_int
12789}
12790
12791#[no_mangle]
12792pub unsafe extern "C" fn getsid(pid: c_int) -> c_int {
12793    let r = sys_getsid(pid);
12794    syscall_ret(r) as c_int
12795}
12796
12797#[no_mangle]
12798pub unsafe extern "C" fn getpgrp() -> c_int {
12799    sys_getpgid(0) as c_int
12800}
12801
12802#[no_mangle]
12803pub unsafe extern "C" fn setpgrp() -> c_int {
12804    setpgid(0, 0)
12805}
12806
12807#[no_mangle]
12808unsafe fn mkstemps_impl(template: *mut c_char, suffixlen: i32) -> c_int {
12809    mkstemps_flags(template, suffixlen, 0)
12810}
12811
12812unsafe fn mkstemps_flags(template: *mut c_char, suffixlen: i32, flags: i32) -> c_int {
12813    if template.is_null() || suffixlen < 0 {
12814        ERRNO!() = EINVAL;
12815        return -1;
12816    }
12817    let len = strlen(template as *const c_char);
12818    let suffix = suffixlen as usize;
12819    if len < 6 + suffix {
12820        ERRNO!() = EINVAL;
12821        return -1;
12822    }
12823    let x_start = len - suffix - 6;
12824    for i in x_start..x_start + 6 {
12825        if *template.add(i) != b'X' as c_char {
12826            ERRNO!() = EINVAL;
12827            return -1;
12828        }
12829    }
12830    let mut ts: timespec = core::mem::zeroed();
12831    let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
12832    let mut ctr: u32 = ts.tv_nsec as u32;
12833    for _ in 0..100 {
12834        ctr = ctr.wrapping_mul(1103515245).wrapping_add(12345);
12835        let mut seed = ctr;
12836        let hex = b"0123456789abcdef";
12837        for i in x_start..x_start + 6 {
12838            *template.add(i) = hex[(seed & 0xf) as usize] as c_char;
12839            seed >>= 4;
12840        }
12841        let fd = sys_open(template as *const u8, (O_RDWR | O_CREAT | O_EXCL | flags) as i64, 0o600);
12842        if fd >= 0 {
12843            return fd as c_int;
12844        }
12845        let e = (-fd) as c_int;
12846        if e != EEXIST {
12847            ERRNO!() = e;
12848            return -1;
12849        }
12850    }
12851    ERRNO!() = EEXIST;
12852    -1
12853}
12854
12855#[no_mangle]
12856pub unsafe extern "C" fn mkstemp(template: *mut c_char) -> c_int {
12857    mkstemps_impl(template, 0)
12858}
12859
12860#[no_mangle]
12861pub unsafe extern "C" fn mkdir(path: *const c_char, mode: c_uint) -> c_int {
12862    let r = sys_mkdirat(AT_FDCWD, path as *const u8, mode);
12863    syscall_ret(r) as c_int
12864}
12865
12866// ============================================================
12867// libgen: basename / dirname
12868// ============================================================
12869
12870#[no_mangle]
12871pub unsafe extern "C" fn dirname(s: *mut c_char) -> *mut c_char {
12872    if s.is_null() || *s == 0 {
12873        return b".\0".as_ptr() as *mut c_char;
12874    }
12875    let mut i = strlen(s as *const c_char);
12876    i = i.wrapping_sub(1);
12877    // skip trailing slashes
12878    while i > 0 && *s.add(i) == b'/' as c_char {
12879        i = i.wrapping_sub(1);
12880    }
12881    if i == 0 && *s.add(0) == b'/' as c_char {
12882        return b"/\0".as_ptr() as *mut c_char;
12883    }
12884    // skip non-slashes
12885    while i > 0 && *s.add(i) != b'/' as c_char {
12886        i = i.wrapping_sub(1);
12887    }
12888    if i == 0 {
12889        if *s.add(0) == b'/' as c_char {
12890            return b"/\0".as_ptr() as *mut c_char;
12891        }
12892        return b".\0".as_ptr() as *mut c_char;
12893    }
12894    // skip slashes
12895    while i > 0 && *s.add(i - 1) == b'/' as c_char {
12896        i = i.wrapping_sub(1);
12897    }
12898    if i == 0 {
12899        return b"/\0".as_ptr() as *mut c_char;
12900    }
12901    *s.add(i) = 0;
12902    s
12903}
12904
12905#[no_mangle]
12906pub unsafe extern "C" fn basename(s: *mut c_char) -> *mut c_char {
12907    if s.is_null() || *s == 0 {
12908        return b".\0".as_ptr() as *mut c_char;
12909    }
12910    let mut i = strlen(s as *const c_char);
12911    i = i.wrapping_sub(1);
12912    // strip trailing slashes
12913    while i > 0 && *s.add(i) == b'/' as c_char {
12914        *s.add(i) = 0;
12915        i = i.wrapping_sub(1);
12916    }
12917    // find last slash
12918    while i > 0 && *s.add(i - 1) != b'/' as c_char {
12919        i = i.wrapping_sub(1);
12920    }
12921    s.add(i)
12922}
12923
12924// ============================================================
12925// arpa/inet: inet_pton / inet_ntop / inet_addr / inet_ntoa / inet_aton
12926// ============================================================
12927
12928const AF_INET_VAL: c_int = 2;
12929const AF_INET6_VAL: c_int = 10;
12930
12931unsafe fn inet_pton_v4(s: *const u8, a: *mut u8) -> c_int {
12932    let mut p = s;
12933    let mut i = 0;
12934    while i < 4 {
12935        let oct_start = p;
12936        let mut v: u32 = 0;
12937        let mut j: u32 = 0;
12938        while j < 3 && *p >= b'0' && *p <= b'9' {
12939            v = v * 10 + (*p - b'0') as u32;
12940            p = p.add(1);
12941            j += 1;
12942        }
12943        if j == 0 || (j > 1 && *oct_start == b'0') || v > 255 { return 0; }
12944        *a.add(i) = v as u8;
12945        if *p == 0 && i == 3 { return 1; }
12946        if *p != b'.' { return 0; }
12947        p = p.add(1);
12948        i += 1;
12949    }
12950    0
12951}
12952
12953unsafe fn inet_pton_v6(s: *const u8, a: *mut u8) -> c_int {
12954    let mut ip = [0u16; 8];
12955    let mut p = s;
12956    let mut i: usize = 0;
12957    let mut brk: isize = -1;
12958    let mut need_v4 = false;
12959    let mut v4_start: *const u8 = core::ptr::null();
12960
12961    if *p == b':' {
12962        p = p.add(1);
12963        if *p != b':' { return 0; }
12964    }
12965
12966    loop {
12967        if *p == b':' && brk < 0 {
12968            brk = i as isize;
12969            ip[i & 7] = 0;
12970            p = p.add(1);
12971            if *p == 0 { break; }
12972            if i == 7 { return 0; }
12973            i += 1;
12974            continue;
12975        }
12976        v4_start = p;
12977        let mut v: u16 = 0;
12978        let mut j = 0;
12979        while j < 4 {
12980            let d = hex_digit(*p);
12981            if d < 0 { break; }
12982            v = v * 16 + d as u16;
12983            p = p.add(1);
12984            j += 1;
12985        }
12986        if j == 0 { return 0; }
12987        ip[i & 7] = v;
12988        if *p == 0 && (brk >= 0 || i == 7) { break; }
12989        if i == 7 { return 0; }
12990        if *p != b':' {
12991            if *p != b'.' || (i < 6 && brk < 0) { return 0; }
12992            need_v4 = true;
12993            i += 1;
12994            ip[i & 7] = 0;
12995            break;
12996        }
12997        p = p.add(1);
12998        i += 1;
12999    }
13000
13001    if brk >= 0 {
13002        // expand :: : move trailing fields to the end and zero the gap
13003        let trail_count = i + 1 - brk as usize;
13004        let dest_start = brk as usize + 7 - i;
13005        // move backwards to avoid overwrite in the overlapping case
13006        for j in (0..trail_count).rev() {
13007            ip[dest_start + j] = ip[brk as usize + j];
13008        }
13009        for j in 0..(7 - i) {
13010            ip[brk as usize + j] = 0;
13011        }
13012    }
13013
13014    for k in 0..8 {
13015        *a.add(k * 2) = (ip[k] >> 8) as u8;
13016        *a.add(k * 2 + 1) = (ip[k] & 0xff) as u8;
13017    }
13018
13019    if need_v4 {
13020        if inet_pton_v4(v4_start, a.add(12)) <= 0 { return 0; }
13021    }
13022    1
13023}
13024
13025unsafe fn hex_digit(c: u8) -> i32 {
13026    if c >= b'0' && c <= b'9' { (c - b'0') as i32 }
13027    else if c >= b'a' && c <= b'f' { (c - b'a' + 10) as i32 }
13028    else if c >= b'A' && c <= b'F' { (c - b'A' + 10) as i32 }
13029    else { -1 }
13030}
13031
13032#[no_mangle]
13033pub unsafe extern "C" fn inet_pton(af: c_int, s: *const c_char, a: *mut c_void) -> c_int {
13034    if af == AF_INET_VAL {
13035        inet_pton_v4(s as *const u8, a as *mut u8)
13036    } else if af == AF_INET6_VAL {
13037        inet_pton_v6(s as *const u8, a as *mut u8)
13038    } else {
13039        ERRNO!() = EAFNOSUPPORT;
13040        -1
13041    }
13042}
13043
13044#[no_mangle]
13045pub unsafe extern "C" fn inet_ntop(af: c_int, a: *const c_void, s: *mut c_char, size: u32) -> *mut c_char {
13046    if af == AF_INET_VAL {
13047        let b = a as *const u8;
13048        let needed = 16; // "255.255.255.255\0"
13049        if size < needed as u32 { ERRNO!() = ENOSPC; return core::ptr::null_mut(); }
13050        let mut pos = 0;
13051        for i in 0..4 {
13052            if i > 0 { *s.add(pos) = b'.' as c_char; pos += 1; }
13053            let (buf, len) = format_u64(*b.add(i) as u64);
13054            for j in 0..len { *s.add(pos) = buf[j] as c_char; pos += 1; }
13055        }
13056        *s.add(pos) = 0;
13057        s
13058    } else if af == AF_INET6_VAL {
13059        let b = a as *const u8;
13060        let needed = 46; // max IPv6
13061        if size < needed as u32 { ERRNO!() = ENOSPC; return core::ptr::null_mut(); }
13062        let mut words = [0u16; 8];
13063        for i in 0..8 {
13064            words[i] = ((*b.add(i * 2) as u16) << 8) | (*b.add(i * 2 + 1) as u16);
13065        }
13066        // IPv4-mapped: ::ffff:a.b.c.d
13067        let mut pos = 0usize;
13068        if words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0
13069            && words[4] == 0 && words[5] == 0xffff
13070        {
13071            let prefix = b"::ffff:";
13072            for k in 0..prefix.len() { *s.add(pos) = prefix[k] as c_char; pos += 1; }
13073            for idx in 0..4 {
13074                if idx > 0 { *s.add(pos) = b'.' as c_char; pos += 1; }
13075                let octet = *b.add(12 + idx);
13076                if octet >= 100 {
13077                    *s.add(pos) = (b'0' + octet / 100) as c_char; pos += 1;
13078                    *s.add(pos) = (b'0' + (octet / 10) % 10) as c_char; pos += 1;
13079                } else if octet >= 10 {
13080                    *s.add(pos) = (b'0' + octet / 10) as c_char; pos += 1;
13081                }
13082                *s.add(pos) = (b'0' + octet % 10) as c_char; pos += 1;
13083            }
13084            *s.add(pos) = 0;
13085            return s;
13086        }
13087        // find longest run of zeros
13088        let mut best_start: isize = -1;
13089        let mut best_len: usize = 0;
13090        let mut j: usize = 0;
13091        while j < 8 {
13092            if words[j] == 0 {
13093                let mut k = j;
13094                while k < 8 && words[k] == 0 { k += 1; }
13095                let run = k - j;
13096                if run > best_len { best_start = j as isize; best_len = run; }
13097                j = k;
13098            } else {
13099                j += 1;
13100            }
13101        }
13102        let mut i: usize = 0;
13103        let mut prev_in_run = false;
13104        while i < 8 {
13105            let in_run = best_len >= 2 && i >= best_start as usize && i < best_start as usize + best_len;
13106            if in_run {
13107                if i == best_start as usize {
13108                    *s.add(pos) = b':' as c_char; pos += 1;
13109                    *s.add(pos) = b':' as c_char; pos += 1;
13110                }
13111                i += 1;
13112                prev_in_run = true;
13113                continue;
13114            }
13115            if i > 0 && !prev_in_run {
13116                *s.add(pos) = b':' as c_char; pos += 1;
13117            }
13118            let (buf, len) = format_hex(words[i] as u64, false);
13119            for k in 0..len { *s.add(pos) = buf[k] as c_char; pos += 1; }
13120            i += 1;
13121            prev_in_run = false;
13122        }
13123        *s.add(pos) = 0;
13124        s
13125    } else {
13126        ERRNO!() = EAFNOSUPPORT;
13127        core::ptr::null_mut()
13128    }
13129}
13130
13131#[no_mangle]
13132pub unsafe extern "C" fn inet_aton(s: *const c_char, dest: *mut c_void) -> c_int {
13133    let a = dest as *mut u8;
13134    let mut p = s as *const u8;
13135    let mut vals = [0u64; 4];
13136    let mut i = 0usize;
13137    while i < 4 {
13138        if *p < b'0' || *p > b'9' { return 0; }
13139        let mut base = 10u32;
13140        if *p == b'0' {
13141            let c = *p.add(1);
13142            if c == b'x' || c == b'X' {
13143                base = 16;
13144                p = p.add(2);
13145                if !((*p >= b'0' && *p <= b'9')
13146                    || (*p >= b'a' && *p <= b'f')
13147                    || (*p >= b'A' && *p <= b'F')) {
13148                    return 0;
13149                }
13150            } else {
13151                base = 8;
13152            }
13153        }
13154        let mut v: u64 = 0;
13155        let start = p;
13156        loop {
13157            let c = *p;
13158            let d = if c >= b'0' && c <= b'9' {
13159                (c - b'0') as u64
13160            } else if base == 16 && c >= b'a' && c <= b'f' {
13161                (c - b'a' + 10) as u64
13162            } else if base == 16 && c >= b'A' && c <= b'F' {
13163                (c - b'A' + 10) as u64
13164            } else {
13165                break;
13166            };
13167            v = v * (base as u64) + d;
13168            p = p.add(1);
13169        }
13170        if p == start { return 0; }
13171        vals[i] = v;
13172        if *p == 0 {
13173            break;
13174        }
13175        if *p != b'.' || i == 3 { return 0; }
13176        p = p.add(1);
13177        i += 1;
13178    }
13179    if i == 4 { return 0; }
13180    if i < 1 { vals[1] = vals[0] & 0xffffff; vals[0] >>= 24; }
13181    if i < 2 { vals[2] = vals[1] & 0xffff; vals[1] >>= 16; }
13182    if i < 3 { vals[3] = vals[2] & 0xff; vals[2] >>= 8; }
13183    for j in 0..4 {
13184        if vals[j] > 255 { return 0; }
13185        *a.add(j) = vals[j] as u8;
13186    }
13187    1
13188}
13189
13190#[no_mangle]
13191pub unsafe extern "C" fn inet_addr(s: *const c_char) -> u32 {
13192    let mut a = [0u8; 4];
13193    if inet_aton(s, a.as_mut_ptr() as *mut c_void) == 1 {
13194        u32::from_ne_bytes(a)
13195    } else {
13196        !0u32 // INADDR_NONE
13197    }
13198}
13199
13200#[no_mangle]
13201pub unsafe extern "C" fn inet_ntoa(addr: u32) -> *mut c_char {
13202    static mut NTOA_BUF: [c_char; 16] = [0; 16];
13203    let b = addr.to_ne_bytes();
13204    let mut pos = 0;
13205    for i in 0..4 {
13206        if i > 0 { NTOA_BUF[pos] = b'.' as c_char; pos += 1; }
13207        let (buf, len) = format_u64(b[i] as u64);
13208        for j in 0..len { NTOA_BUF[pos] = buf[j] as c_char; pos += 1; }
13209    }
13210    NTOA_BUF[pos] = 0;
13211    core::ptr::addr_of_mut!(NTOA_BUF).cast::<c_char>()
13212}
13213
13214// inet_network/inet_makeaddr/inet_lnaof/inet_netof - simple implementations
13215#[no_mangle]
13216pub unsafe extern "C" fn inet_network(s: *const c_char) -> u32 {
13217    inet_addr(s).to_be()
13218}
13219
13220#[no_mangle]
13221pub extern "C" fn inet_makeaddr(net: c_int, host: c_int) -> u32 {
13222    // musl's inet_legacy: class A when the network number fits in 8 bits,
13223    // class B when it fits in 16, otherwise the top 24 bits.
13224    let n = net as u32;
13225    let mut h = host as u32;
13226    if n < 256 {
13227        h |= n << 24;
13228    } else if n < 65536 {
13229        h |= n << 16;
13230    } else {
13231        h |= n << 8;
13232    }
13233    h
13234}
13235
13236#[no_mangle]
13237pub extern "C" fn inet_lnaof(addr: u32) -> c_int {
13238    // s_addr already carries the network-order numeric value, exactly like
13239    // musl's inet_legacy.c; do not byte-swap it again.
13240    let h = addr;
13241    if h < 0x80000000 { (h & 0x00ffffff) as c_int }
13242    else if h < 0xc0000000 { (h & 0x0000ffff) as c_int }
13243    else { (h & 0x000000ff) as c_int }
13244}
13245
13246#[no_mangle]
13247pub extern "C" fn inet_netof(addr: u32) -> c_int {
13248    let h = addr;
13249    if h < 0x80000000 { (h >> 24) as c_int }
13250    else if h < 0xc0000000 { (h >> 16) as c_int }
13251    else { (h >> 8) as c_int }
13252}
13253
13254// ============================================================
13255// stdlib: strtod / strtof / strtold
13256// ============================================================
13257
13258// Correctly-rounded float parser.
13259// Decimal: collects digits into buffer, uses core::str::FromStr.
13260// Hex: u128 integer arithmetic with round-to-nearest-even.
13261// is_f32: true for strtof (f32::from_str), false for strtod/strtold (f64::from_str).
13262unsafe fn parse_float(s: *const u8, endptr: *mut *mut u8, is_f32: bool) -> f64 {
13263    let mut p = s;
13264    // skip whitespace
13265    while *p == b' ' || *p == b'\t' || *p == b'\n' || *p == b'\r' { p = p.add(1); }
13266    let mut neg = false;
13267    if *p == b'-' { neg = true; p = p.add(1); }
13268    else if *p == b'+' { p = p.add(1); }
13269
13270    // inf
13271    if (*p | 0x20) == b'i'
13272        && (*p.add(1) | 0x20) == b'n'
13273        && (*p.add(2) | 0x20) == b'f'
13274    {
13275        p = p.add(3);
13276        // optionally consume "inity"
13277        if (*p | 0x20) == b'i'
13278            && (*p.add(1) | 0x20) == b't'
13279            && (*p.add(2) | 0x20) == b'y'
13280        {
13281            p = p.add(3);
13282        }
13283        if !endptr.is_null() { *endptr = p as *mut u8; }
13284        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13285    }
13286    // nan
13287    if (*p | 0x20) == b'n'
13288        && (*p.add(1) | 0x20) == b'a'
13289        && (*p.add(2) | 0x20) == b'n'
13290    {
13291        p = p.add(3);
13292        // optionally consume (n-char-sequence)
13293        if *p == b'(' {
13294            p = p.add(1);
13295            while *p != 0 && *p != b')' { p = p.add(1); }
13296            if *p == b')' { p = p.add(1); }
13297        }
13298        if !endptr.is_null() { *endptr = p as *mut u8; }
13299        return if neg { -f64::NAN } else { f64::NAN };
13300    }
13301
13302    // hex float
13303    if *p == b'0' && (*p.add(1) == b'x' || *p.add(1) == b'X') {
13304        p = p.add(2);
13305        let mut mant: u128 = 0;
13306        let mut frac_hex: i64 = 0;
13307        let mut dropped: i64 = 0;
13308        let mut tail_nonzero = false;
13309        let mut found = false;
13310        let mut in_frac = false;
13311
13312        loop {
13313            if let Some(d) = hex_val(*p) {
13314                if mant <= u128::MAX / 16 {
13315                    mant = mant * 16 + d as u128;
13316                } else {
13317                    // Too many significant digits for u128: keep the leading
13318                    // ones and remember that the dropped tail is nonzero.
13319                    dropped += 1;
13320                    if d != 0 { tail_nonzero = true; }
13321                }
13322                if in_frac { frac_hex += 1; }
13323                p = p.add(1);
13324                found = true;
13325            } else if *p == b'.' && !in_frac {
13326                in_frac = true;
13327                p = p.add(1);
13328            } else {
13329                break;
13330            }
13331        }
13332
13333        if !found {
13334            if !endptr.is_null() { *endptr = s as *mut u8; }
13335            return 0.0;
13336        }
13337
13338        // binary exponent p[+-]N
13339        let mut bin_exp: i32 = 0;
13340        if *p == b'p' || *p == b'P' {
13341            p = p.add(1);
13342            let mut exp_neg = false;
13343            if *p == b'-' { exp_neg = true; p = p.add(1); }
13344            else if *p == b'+' { p = p.add(1); }
13345            while *p >= b'0' && *p <= b'9' {
13346                if bin_exp < 100000 {
13347                    bin_exp = bin_exp * 10 + (*p - b'0') as i32;
13348                }
13349                p = p.add(1);
13350            }
13351            if exp_neg { bin_exp = -bin_exp; }
13352        }
13353
13354        if !endptr.is_null() { *endptr = p as *mut u8; }
13355        if mant == 0 { return if neg { -0.0 } else { 0.0 }; }
13356
13357        // The exponent must account for every fractional digit, including
13358        // the ones dropped from `mant`.
13359        let total_exp = bin_exp as i64 - 4 * (frac_hex - dropped);
13360        let r = hex_mant_to_f64(mant, total_exp, neg, tail_nonzero);
13361        note_float_range(r, true, is_f32);
13362        return r;
13363    }
13364
13365    // decimal: collect the significant digits into a bounded buffer and let
13366    // Rust's parser do the correctly-rounded conversion. Keeping only the
13367    // leading digits (and folding the rest into the exponent) keeps the stack
13368    // footprint small without changing the result.
13369    const MAX_SIG_DIGITS: usize = 768;
13370    let mut buf = [0u8; MAX_SIG_DIGITS + 32];
13371    let mut n = 0usize;
13372    let mut found_digit = false;
13373    let mut nonzero = false;
13374    let mut frac_kept: i64 = 0;
13375    let mut frac_lead_zeros: i64 = 0;
13376    let mut int_dropped: i64 = 0;
13377
13378    while *p >= b'0' && *p <= b'9' {
13379        if *p != b'0' { nonzero = true; }
13380        if nonzero {
13381            if n < MAX_SIG_DIGITS {
13382                buf[n] = *p;
13383                n += 1;
13384            } else {
13385                int_dropped += 1;
13386            }
13387        }
13388        p = p.add(1);
13389        found_digit = true;
13390    }
13391    if *p == b'.' {
13392        p = p.add(1);
13393        while *p >= b'0' && *p <= b'9' {
13394            if *p != b'0' { nonzero = true; }
13395            if !nonzero {
13396                // Leading fractional zeros still shift the exponent.
13397                frac_lead_zeros += 1;
13398            } else if n < MAX_SIG_DIGITS {
13399                buf[n] = *p;
13400                n += 1;
13401                frac_kept += 1;
13402            }
13403            p = p.add(1);
13404            found_digit = true;
13405        }
13406    }
13407    if !found_digit {
13408        ERRNO!() = EINVAL;
13409        if !endptr.is_null() { *endptr = s as *mut u8; }
13410        return 0.0;
13411    }
13412    let mut exp10: i64 = int_dropped - frac_kept - frac_lead_zeros;
13413    if *p == b'e' || *p == b'E' {
13414        let mut q = p.add(1);
13415        let mut exp_neg = false;
13416        if *q == b'-' { exp_neg = true; q = q.add(1); }
13417        else if *q == b'+' { q = q.add(1); }
13418        // Without at least one exponent digit the 'e' is not part of the
13419        // number; leave the end pointer on it.
13420        if *q >= b'0' && *q <= b'9' {
13421            let mut e: i64 = 0;
13422            while *q >= b'0' && *q <= b'9' {
13423                e = e.saturating_mul(10).saturating_add((*q - b'0') as i64);
13424                if e > 1_000_000 { e = 1_000_000; }
13425                q = q.add(1);
13426            }
13427            exp10 += if exp_neg { -e } else { e };
13428            p = q;
13429        }
13430    }
13431    if !endptr.is_null() { *endptr = p as *mut u8; }
13432    if n == 0 {
13433        // Every digit was zero.
13434        return if neg { -0.0 } else { 0.0 };
13435    }
13436
13437    // Represent the kept digits as an integer times a power of ten.
13438    buf[n] = b'e';
13439    n += 1;
13440    let mut tmp = [0u8; 24];
13441    let mut tn = 0usize;
13442    let e_abs = exp10.unsigned_abs();
13443    if e_abs == 0 {
13444        tmp[0] = b'0';
13445        tn = 1;
13446    } else {
13447        let mut v = e_abs;
13448        while v > 0 && tn < tmp.len() {
13449            tmp[tn] = b'0' + (v % 10) as u8;
13450            v /= 10;
13451            tn += 1;
13452        }
13453    }
13454    if exp10 < 0 { buf[n] = b'-'; n += 1; }
13455    for k in (0..tn).rev() {
13456        buf[n] = tmp[k];
13457        n += 1;
13458    }
13459
13460    let s_str = core::str::from_utf8_unchecked(
13461        core::slice::from_raw_parts(buf.as_ptr(), n),
13462    );
13463    if is_f32 {
13464        match <f32 as core::str::FromStr>::from_str(s_str) {
13465            Ok(v) => {
13466                let r = if neg { -(v as f64) } else { v as f64 };
13467                note_float_range(r, nonzero, true);
13468                r
13469            }
13470            Err(_) => { if !endptr.is_null() { *endptr = s as *mut u8; } 0.0 }
13471        }
13472    } else {
13473        match <f64 as core::str::FromStr>::from_str(s_str) {
13474            Ok(v) => {
13475                let r = if neg { -v } else { v };
13476                note_float_range(r, nonzero, false);
13477                r
13478            }
13479            Err(_) => { if !endptr.is_null() { *endptr = s as *mut u8; } 0.0 }
13480        }
13481    }
13482}
13483
13484/// Set ERANGE for overflow and underflow, like musl's floatscan.
13485unsafe fn note_float_range(r: f64, nonzero: bool, is_f32: bool) {
13486    let (infinite, zero, subnormal) = if is_f32 {
13487        let v = r as f32;
13488        (v.is_infinite(), v == 0.0, v != 0.0 && v.abs() < f32::MIN_POSITIVE)
13489    } else {
13490        (r.is_infinite(), r == 0.0, r != 0.0 && r.abs() < f64::MIN_POSITIVE)
13491    };
13492    if infinite || subnormal || (zero && nonzero) {
13493        ERRNO!() = ERANGE;
13494    }
13495}
13496
13497// Convert hex mantissa integer to f64 with correct rounding.
13498// mant: integer from parsed hex digits. total_exp: bin_exp - 4 * frac_hex_digits.
13499// tail_nonzero records dropped digits below `mant` for the sticky bit.
13500// Value = mant * 2^total_exp.
13501fn hex_mant_to_f64(mant: u128, total_exp: i64, neg: bool, tail_nonzero: bool) -> f64 {
13502    if mant == 0 { return if neg { -0.0 } else { 0.0 }; }
13503
13504    let msb = (127 - mant.leading_zeros()) as i64;
13505    let unbiased_exp = msb + total_exp;
13506    let biased_exp = unbiased_exp + 1023;
13507
13508    // Overflow → infinity
13509    if biased_exp >= 2047 {
13510        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13511    }
13512
13513    // Subnormal or underflow
13514    if biased_exp <= 0 {
13515        // subnormal: biased_exp=0, effective exponent=-1022
13516        // mantissa = round(mant * 2^(total_exp + 1074))
13517        let shift = total_exp + 1074;
13518        if shift < 0 {
13519            return if neg { -0.0 } else { 0.0 };
13520        }
13521        if shift > 128 {
13522            return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13523        }
13524        let shifted = mant << (shift as u32);
13525        let mantissa52 = (shifted as u64) & 0x000FFFFFFFFFFFFF;
13526        let guard = ((shifted >> 52) & 1) != 0;
13527        let sticky = (shifted >> 53) != 0 || tail_nonzero;
13528        let mut result = mantissa52;
13529        if guard && (sticky || (result & 1) != 0) {
13530            result += 1;
13531            if result > 0x000FFFFFFFFFFFFF {
13532                // carry → smallest normal
13533                return if neg { -f64::from_bits(1u64 << 52) } else { f64::from_bits(1u64 << 52) };
13534            }
13535        }
13536        return if neg { -f64::from_bits(result) } else { f64::from_bits(result) };
13537    }
13538
13539    // Normal: biased_exp in [1, 2046]
13540    let shift = msb - 52;
13541
13542    if shift <= 0 {
13543        // fewer than 53 bits, no rounding needed
13544        let mantissa = ((mant as u64) & ((1u64 << msb as u32) - 1)) << ((-shift) as u32);
13545        let bits = ((biased_exp as u64) << 52) | mantissa;
13546        return if neg { -f64::from_bits(bits) } else { f64::from_bits(bits) };
13547    }
13548
13549    // shift > 0: round to nearest even
13550    let mantissa = ((mant >> shift as u32) as u64) & 0x000FFFFFFFFFFFFF;
13551    let guard = ((mant >> (shift as u32 - 1)) & 1) != 0;
13552    let sticky = (if shift > 1 {
13553        (mant & ((1u128 << (shift as u32 - 1)) - 1)) != 0
13554    } else { false }) || tail_nonzero;
13555
13556    let mut result_mant = mantissa;
13557    let mut result_exp = biased_exp;
13558    if guard && (sticky || (result_mant & 1) != 0) {
13559        result_mant += 1;
13560        if result_mant > 0x000FFFFFFFFFFFFF {
13561            result_mant = 0;
13562            result_exp += 1;
13563            if result_exp >= 2047 {
13564                return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13565            }
13566        }
13567    }
13568
13569    let bits = ((result_exp as u64) << 52) | result_mant;
13570    if neg { -f64::from_bits(bits) } else { f64::from_bits(bits) }
13571}
13572
13573unsafe fn hex_val(c: u8) -> Option<u8> {
13574    if c >= b'0' && c <= b'9' { Some(c - b'0') }
13575    else if c >= b'a' && c <= b'f' { Some(c - b'a' + 10) }
13576    else if c >= b'A' && c <= b'F' { Some(c - b'A' + 10) }
13577    else { None }
13578}
13579
13580#[no_mangle]
13581pub unsafe extern "C" fn strtod(s: *const c_char, endptr: *mut *mut c_char) -> f64 {
13582    let mut end: *mut u8 = s as *mut u8;
13583    let r = parse_float(s as *const u8, &mut end, false);
13584    if !endptr.is_null() { *endptr = end as *mut c_char; }
13585    r
13586}
13587
13588#[no_mangle]
13589pub unsafe extern "C" fn strtof(s: *const c_char, endptr: *mut *mut c_char) -> f32 {
13590    let mut end: *mut u8 = s as *mut u8;
13591    let r = parse_float(s as *const u8, &mut end, true);
13592    if !endptr.is_null() { *endptr = end as *mut c_char; }
13593    r as f32
13594}
13595
13596#[no_mangle]
13597#[cfg(target_arch = "x86_64")]
13598pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f64 {
13599    strtod(s, endptr)
13600}
13601
13602#[no_mangle]
13603#[cfg(target_arch = "aarch64")]
13604pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f128 {
13605    strtod(s, endptr) as f128
13606}
13607
13608#[no_mangle]
13609#[cfg(target_arch = "riscv64")]
13610pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f128 {
13611    strtod(s, endptr) as f128
13612}
13613
13614#[no_mangle]
13615pub unsafe extern "C" fn atof(s: *const c_char) -> f64 {
13616    strtod(s, core::ptr::null_mut())
13617}
13618
13619// ============================================================
13620// stdio: open_memstream / fmemopen
13621// ============================================================
13622
13623#[repr(C)]
13624struct MsCookie {
13625    bufp: *mut *mut c_char,
13626    sizep: *mut usize,
13627    pos: usize,
13628    len: usize,
13629    buf: *mut u8,
13630    space: usize,
13631}
13632
13633#[repr(C)]
13634struct MfCookie {
13635    pos: usize,
13636    len: usize,
13637    size: usize,
13638    buf: *mut u8,
13639    mode: c_char,
13640}
13641
13642unsafe extern "C" fn ms_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
13643    let c = (*f).cookie as *mut MsCookie;
13644    if whence < 0 || whence > 2 { ERRNO!() = EINVAL; return -1; }
13645    let base: i64 = match whence {
13646        0 => 0,
13647        1 => (*c).pos as i64,
13648        2 => (*c).len as i64,
13649        _ => { ERRNO!() = EINVAL; return -1; }
13650    };
13651    if off < -base || off > isize::MAX as i64 - base { ERRNO!() = EINVAL; return -1; }
13652    (*c).pos = (base + off) as usize;
13653    (*c).pos as i64
13654}
13655
13656unsafe extern "C" fn ms_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
13657    let c = (*f).cookie as *mut MsCookie;
13658    let buffered = (*f).wpos as usize - (*f).wbase as usize;
13659    if buffered > 0 {
13660        (*f).wpos = (*f).wbase;
13661        if ms_write(f, (*f).wbase, buffered) < buffered { return 0; }
13662    }
13663    if len == 0 { return 0; }
13664    if (*c).pos + len >= (*c).space {
13665        let new_space = 2 * (*c).space + 1 | (*c).pos + len + 1;
13666        let newbuf = realloc((*c).buf as *mut c_void, new_space) as *mut u8;
13667        if newbuf.is_null() { return 0; }
13668        *(*c).bufp = newbuf as *mut c_char;
13669        core::ptr::write_bytes(newbuf.add((*c).space), 0, new_space - (*c).space);
13670        (*c).buf = newbuf;
13671        (*c).space = new_space;
13672    }
13673    core::ptr::copy_nonoverlapping(buf, (*c).buf.add((*c).pos), len);
13674    (*c).pos += len;
13675    if (*c).pos >= (*c).len { (*c).len = (*c).pos; }
13676    *(*c).sizep = (*c).pos;
13677    len
13678}
13679
13680unsafe extern "C" fn ms_close(f: *mut FILE) -> c_int {
13681    // The byte buffer belongs to the caller; free only the cookie.
13682    if !f.is_null() && !(*f).cookie.is_null() {
13683        free((*f).cookie);
13684        (*f).cookie = core::ptr::null_mut();
13685    }
13686    0
13687}
13688
13689#[no_mangle]
13690pub unsafe extern "C" fn open_memstream(bufp: *mut *mut c_char, sizep: *mut usize) -> *mut FILE {
13691    if bufp.is_null() || sizep.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
13692    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
13693    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13694    let buf_area = buf_ptr(f);
13695    init_file(f, -1, b"w\0".as_ptr() as *const c_char, Some(ms_close), buf_area, BUFSIZ);
13696    (*f).flags = F_NORD | F_SVB;
13697    (*f).lbf = -1;
13698    let c = calloc(1, core::mem::size_of::<MsCookie>()) as *mut MsCookie;
13699    if c.is_null() { free(f as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13700    (*c).bufp = bufp;
13701    (*c).sizep = sizep;
13702    (*c).pos = 0;
13703    (*c).len = 0;
13704    let initial = crate::malloc(1) as *mut u8;
13705    if initial.is_null() {
13706        crate::free(c as *mut c_void);
13707        crate::free(f as *mut c_void);
13708        ERRNO!() = ENOMEM;
13709        return core::ptr::null_mut();
13710    }
13711    *initial = 0;
13712    (*c).buf = initial;
13713    (*c).space = 1;
13714    (*f).cookie = c as *mut c_void;
13715    (*f).write_fn = Some(ms_write);
13716    (*f).seek_fn = Some(ms_seek);
13717    *bufp = initial as *mut c_char;
13718    *sizep = 0;
13719    f
13720}
13721
13722unsafe extern "C" fn mseek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
13723    let c = (*f).cookie as *mut MfCookie;
13724    if whence < 0 || whence > 2 { ERRNO!() = EINVAL; return -1; }
13725    let base: i64 = match whence {
13726        0 => 0,
13727        1 => (*c).pos as i64,
13728        2 => (*c).len as i64,
13729        _ => { ERRNO!() = EINVAL; return -1; }
13730    };
13731    if off < -base || off > (*c).size as i64 - base { ERRNO!() = EINVAL; return -1; }
13732    (*c).pos = (base + off) as usize;
13733    (*c).pos as i64
13734}
13735
13736unsafe extern "C" fn mread(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
13737    let c = (*f).cookie as *mut MfCookie;
13738    let mut rem = if (*c).pos <= (*c).len { (*c).len - (*c).pos } else { 0 };
13739    let mut l = len;
13740    if l > rem {
13741        l = rem;
13742        (*f).flags |= F_EOF;
13743    }
13744    core::ptr::copy_nonoverlapping((*c).buf.add((*c).pos), buf, l);
13745    (*c).pos += l;
13746    rem -= l;
13747    if rem > (*f).buf_size { rem = (*f).buf_size; }
13748    (*f).rpos = (*f).buf;
13749    (*f).rend = (*f).buf.add(rem);
13750    core::ptr::copy_nonoverlapping((*c).buf.add((*c).pos), (*f).rpos, rem);
13751    (*c).pos += rem;
13752    l
13753}
13754
13755unsafe extern "C" fn mwrite(f: *mut FILE, buf: *const u8, len: usize) -> usize {
13756    let c = (*f).cookie as *mut MfCookie;
13757    let buffered = (*f).wpos as usize - (*f).wbase as usize;
13758    if buffered > 0 {
13759        (*f).wpos = (*f).wbase;
13760        if mwrite(f, (*f).wbase, buffered) < buffered { return 0; }
13761    }
13762    if len == 0 { return 0; }
13763    if (*c).mode == b'a' as c_char { (*c).pos = (*c).len; }
13764    let rem = (*c).size - (*c).pos;
13765    let mut l = len;
13766    if l > rem { l = rem; }
13767    core::ptr::copy_nonoverlapping(buf, (*c).buf.add((*c).pos), l);
13768    (*c).pos += l;
13769    if (*c).pos > (*c).len {
13770        (*c).len = (*c).pos;
13771        if (*c).len < (*c).size {
13772            *(*c).buf.add((*c).len) = 0;
13773        } else if ((*f).flags & F_NORD) != 0 && (*c).size > 0 {
13774            *(*c).buf.add((*c).size - 1) = 0;
13775        }
13776    }
13777    l
13778}
13779
13780unsafe extern "C" fn mclose(_f: *mut FILE) -> c_int {
13781    0
13782}
13783
13784#[no_mangle]
13785pub unsafe extern "C" fn fmemopen(buf: *mut c_void, size: usize, mode: *const c_char) -> *mut FILE {
13786    if mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
13787    let m = *mode;
13788    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
13789        ERRNO!() = EINVAL; return core::ptr::null_mut();
13790    }
13791    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
13792    let need_alloc = buf.is_null();
13793    let alloc_size = core::mem::size_of::<FILE>() + UNGET + BUFSIZ + if need_alloc { size } else { 0 };
13794    let f = calloc(1, alloc_size) as *mut FILE;
13795    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13796    let buf_area = buf_ptr(f);
13797    init_file(f, -1, mode, Some(mclose), buf_area, BUFSIZ);
13798    (*f).flags |= F_SVB;
13799    let actual_buf: *mut u8 = if need_alloc {
13800        (f as *mut u8).add(alloc_size - size)
13801    } else {
13802        buf as *mut u8
13803    };
13804    if need_alloc { core::ptr::write_bytes(actual_buf, 0, size); }
13805    let c = calloc(1, core::mem::size_of::<MfCookie>()) as *mut MfCookie;
13806    if c.is_null() { free(f as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13807    (*c).buf = actual_buf;
13808    (*c).size = size;
13809    (*c).mode = m;
13810    (*f).cookie = c as *mut c_void;
13811    (*f).read_fn = Some(mread);
13812    (*f).write_fn = Some(mwrite);
13813    (*f).seek_fn = Some(mseek);
13814    if !has_plus { (*f).flags = if m == b'r' as c_char { F_NOWR } else { F_NORD }; }
13815    if m == b'r' as c_char {
13816        (*c).len = size;
13817    } else if m == b'a' as c_char {
13818        (*c).len = strnlen(actual_buf, size);
13819        (*c).pos = (*c).len;
13820    } else if has_plus {
13821        *actual_buf = 0;
13822    }
13823    f
13824}
13825
13826// ============================================================
13827// Stat (for ftok)
13828// ============================================================
13829
13830#[repr(C)]
13831struct kernel_stat64 {
13832    st_dev: u64,
13833    st_ino: u64,
13834    st_nlink: u64,
13835    st_mode: u32,
13836    st_uid: u32,
13837    st_gid: u32,
13838    __pad0: c_int,
13839    st_rdev: u64,
13840    st_size: i64,
13841    st_blksize: i64,
13842    st_blocks: i64,
13843    st_atime: i64,
13844    st_atime_nsec: i64,
13845    st_mtime: i64,
13846    st_mtime_nsec: i64,
13847    st_ctime: i64,
13848    st_ctime_nsec: i64,
13849    __unused: [i64; 3],
13850}
13851
13852// sys_stat = 4 on x86_64
13853#[inline]
13854unsafe fn sys_stat(path: *const u8, statbuf: *mut kernel_stat64) -> i64 {
13855    <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, statbuf as i64, 0)
13856}
13857
13858// ============================================================
13859// Search: hcreate/hdestroy/hsearch (hash table)
13860// ============================================================
13861
13862const HSEARCH_MINSIZE: usize = 8;
13863
13864#[repr(C)]
13865#[derive(Copy, Clone)]
13866pub struct HSearchEntry {
13867    key: *mut c_char,
13868    data: *mut c_void,
13869}
13870
13871#[repr(C)]
13872struct HTab {
13873    entries: *mut HSearchEntry,
13874    mask: usize,
13875    used: usize,
13876}
13877
13878#[repr(C)]
13879pub struct HSearchData {
13880    tab: *mut HTab,
13881    __unused1: c_uint,
13882    __unused2: c_uint,
13883}
13884
13885// Single static hash table for the non-_r variants.
13886static mut HTAB_DATA: HSearchData = HSearchData {
13887    tab: core::ptr::null_mut(),
13888    __unused1: 0,
13889    __unused2: 0,
13890};
13891
13892unsafe fn keyhash(k: *const c_char) -> usize {
13893    let mut h: usize = 0;
13894    let mut p = k;
13895    while *p != 0 {
13896        h = h.wrapping_mul(31).wrapping_add(*p as usize);
13897        p = p.add(1);
13898    }
13899    h
13900}
13901
13902unsafe fn htab_lookup(key: *const c_char, hash: usize, htab: *mut HSearchData) -> *mut HSearchEntry {
13903    let tab = (*htab).tab;
13904    let mask = (*tab).mask;
13905    let entries = (*tab).entries;
13906    let mut i = hash;
13907    let mut j: usize = 1;
13908    loop {
13909        let e = entries.add(i & mask);
13910        if (*e).key.is_null() || strcmp((*e).key as *const u8, key as *const u8) == 0 {
13911            return e;
13912        }
13913        i = i.wrapping_add(j);
13914        j += 1;
13915    }
13916}
13917
13918unsafe fn htab_resize(nel: usize, htab: *mut HSearchData) -> c_int {
13919    let tab = (*htab).tab;
13920    let old_entries = (*tab).entries;
13921    let old_size = (*tab).mask + 1;
13922
13923    let mut newsize: usize = HSEARCH_MINSIZE;
13924    while newsize < nel {
13925        let Some(next) = newsize.checked_mul(2) else {
13926            ERRNO!() = ENOMEM;
13927            return 0;
13928        };
13929        newsize = next;
13930    }
13931
13932    let new_entries = calloc(newsize, core::mem::size_of::<HSearchEntry>()) as *mut HSearchEntry;
13933    if new_entries.is_null() {
13934        ERRNO!() = ENOMEM;
13935        return 0;
13936    }
13937    (*tab).entries = new_entries;
13938    (*tab).mask = newsize - 1;
13939
13940    if !old_entries.is_null() {
13941        for idx in 0..old_size {
13942            let old_e = old_entries.add(idx);
13943            if !(*old_e).key.is_null() {
13944                let h = keyhash((*old_e).key);
13945                let mut i = h;
13946                let mut j: usize = 1;
13947                loop {
13948                    let e = new_entries.add(i & (*tab).mask);
13949                    if (*e).key.is_null() {
13950                        *e = *old_e;
13951                        break;
13952                    }
13953                    i = i.wrapping_add(j);
13954                    j += 1;
13955                }
13956            }
13957        }
13958        free(old_entries as *mut c_void);
13959    }
13960    1
13961}
13962
13963unsafe fn hcreate_r_impl(nel: usize, htab: *mut HSearchData) -> c_int {
13964    if nel == 0 || nel > (1usize << 30) {
13965        ERRNO!() = ENOMEM;
13966        return 0;
13967    }
13968    (*htab).tab = calloc(1, core::mem::size_of::<HTab>()) as *mut HTab;
13969    if (*htab).tab.is_null() {
13970        ERRNO!() = ENOMEM;
13971        return 0;
13972    }
13973    if htab_resize(nel, htab) == 0 {
13974        free((*htab).tab as *mut c_void);
13975        (*htab).tab = core::ptr::null_mut();
13976        return 0;
13977    }
13978    1
13979}
13980
13981unsafe fn hdestroy_r_impl(htab: *mut HSearchData) {
13982    if !(*htab).tab.is_null() {
13983        if !(*(*htab).tab).entries.is_null() {
13984            free((*(*htab).tab).entries as *mut c_void);
13985        }
13986        free((*htab).tab as *mut c_void);
13987        (*htab).tab = core::ptr::null_mut();
13988    }
13989}
13990
13991unsafe fn hsearch_r_impl(item: HSearchEntry, action: c_int, retval: *mut *mut HSearchEntry, htab: *mut HSearchData) -> c_int {
13992    let hash = keyhash(item.key);
13993    let e = htab_lookup(item.key, hash, htab);
13994
13995    if !(*e).key.is_null() {
13996        *retval = e;
13997        return 1;
13998    }
13999    if action == 0 { // FIND
14000        *retval = core::ptr::null_mut();
14001        return 0;
14002    }
14003    // ENTER
14004    let item_key = item.key;
14005    *e = item;
14006    (*(*htab).tab).used += 1;
14007    if (*(*htab).tab).used > (*(*htab).tab).mask - (*(*htab).tab).mask / 4 {
14008        if htab_resize(2 * (*(*htab).tab).used, htab) == 0 {
14009            (*(*htab).tab).used -= 1;
14010            (*e).key = core::ptr::null_mut();
14011            *retval = core::ptr::null_mut();
14012            return 0;
14013        }
14014        let e2 = htab_lookup(item_key, hash, htab);
14015        *retval = e2;
14016        return 1;
14017    }
14018    *retval = e;
14019    1
14020}
14021
14022#[no_mangle]
14023pub unsafe extern "C" fn hcreate(nel: usize) -> c_int {
14024    hcreate_r_impl(nel, core::ptr::addr_of_mut!(HTAB_DATA))
14025}
14026
14027#[no_mangle]
14028pub unsafe extern "C" fn hdestroy() {
14029    hdestroy_r_impl(core::ptr::addr_of_mut!(HTAB_DATA));
14030}
14031
14032#[no_mangle]
14033pub unsafe extern "C" fn hsearch(item: HSearchEntry, action: c_int) -> *mut HSearchEntry {
14034    let mut e: *mut HSearchEntry = core::ptr::null_mut();
14035    hsearch_r_impl(item, action, &mut e, core::ptr::addr_of_mut!(HTAB_DATA));
14036    e
14037}
14038
14039#[no_mangle]
14040pub unsafe extern "C" fn hcreate_r(nel: usize, htab: *mut HSearchData) -> c_int {
14041    hcreate_r_impl(nel, htab)
14042}
14043
14044#[no_mangle]
14045pub unsafe extern "C" fn hdestroy_r(htab: *mut HSearchData) {
14046    hdestroy_r_impl(htab);
14047}
14048
14049#[no_mangle]
14050pub unsafe extern "C" fn hsearch_r(item: HSearchEntry, action: c_int, retval: *mut *mut HSearchEntry, htab: *mut HSearchData) -> c_int {
14051    hsearch_r_impl(item, action, retval, htab)
14052}
14053
14054// ============================================================
14055// Search: insque / remque
14056// ============================================================
14057
14058#[repr(C)]
14059struct QueNode {
14060    next: *mut QueNode,
14061    prev: *mut QueNode,
14062}
14063
14064#[no_mangle]
14065pub unsafe extern "C" fn insque(element: *mut c_void, pred: *mut c_void) {
14066    let e = element as *mut QueNode;
14067    let p = pred as *mut QueNode;
14068    if p.is_null() {
14069        (*e).next = core::ptr::null_mut();
14070        (*e).prev = core::ptr::null_mut();
14071        return;
14072    }
14073    (*e).next = (*p).next;
14074    (*e).prev = p;
14075    (*p).next = e;
14076    if !(*e).next.is_null() {
14077        (*(*e).next).prev = e;
14078    }
14079}
14080
14081#[no_mangle]
14082pub unsafe extern "C" fn remque(element: *mut c_void) {
14083    let e = element as *mut QueNode;
14084    if !(*e).next.is_null() {
14085        (*(*e).next).prev = (*e).prev;
14086    }
14087    if !(*e).prev.is_null() {
14088        (*(*e).prev).next = (*e).next;
14089    }
14090}
14091
14092// ============================================================
14093// Search: lsearch / lfind
14094// ============================================================
14095
14096#[no_mangle]
14097pub unsafe extern "C" fn lsearch(
14098    key: *const c_void,
14099    base: *mut c_void,
14100    nelp: *mut usize,
14101    width: usize,
14102    compar: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
14103) -> *mut c_void {
14104    let n = *nelp;
14105    let p = base as *mut u8;
14106    for i in 0..n {
14107        let elem = p.add(i * width);
14108        if compar.unwrap()(key, elem as *const c_void) == 0 {
14109            return elem as *mut c_void;
14110        }
14111    }
14112    let dest = p.add(n * width);
14113    memcpy(dest as *mut c_void, key as *const c_void, width);
14114    *nelp = n + 1;
14115    dest as *mut c_void
14116}
14117
14118#[no_mangle]
14119pub unsafe extern "C" fn lfind(
14120    key: *const c_void,
14121    base: *const c_void,
14122    nelp: *mut usize,
14123    width: usize,
14124    compar: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
14125) -> *mut c_void {
14126    let n = *nelp;
14127    let p = base as *const u8;
14128    for i in 0..n {
14129        let elem = p.add(i * width);
14130        if compar.unwrap()(key, elem as *const c_void) == 0 {
14131            return elem as *mut c_void;
14132        }
14133    }
14134    core::ptr::null_mut()
14135}
14136
14137// ============================================================
14138// Search: tsearch / tfind / tdelete / twalk / tdestroy (BST, no balancing)
14139// ============================================================
14140
14141// Unbalanced binary tree, unlike musl's AVL tree: O(n) worst case.
14142#[repr(C)]
14143pub struct TreeNode {
14144    key: *const c_void,
14145    left: *mut TreeNode,
14146    right: *mut TreeNode,
14147}
14148
14149type ComparFn = Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>;
14150
14151unsafe fn bst_new(key: *const c_void) -> *mut TreeNode {
14152    let n = calloc(1, core::mem::size_of::<TreeNode>()) as *mut TreeNode;
14153    if !n.is_null() {
14154        (*n).key = key;
14155        (*n).left = core::ptr::null_mut();
14156        (*n).right = core::ptr::null_mut();
14157    }
14158    n
14159}
14160
14161#[no_mangle]
14162pub unsafe extern "C" fn tsearch(
14163    key: *const c_void,
14164    rootp: *mut *mut TreeNode,
14165    compar: ComparFn,
14166) -> *mut c_void {
14167    if rootp.is_null() {
14168        return core::ptr::null_mut();
14169    }
14170    let mut pp = rootp;
14171    loop {
14172        let n = *pp;
14173        if n.is_null() {
14174            let r = bst_new(key);
14175            if r.is_null() {
14176                return core::ptr::null_mut();
14177            }
14178            *pp = r;
14179            return r as *mut c_void;
14180        }
14181        let c = compar.unwrap()(key, (*n).key);
14182        if c == 0 {
14183            return n as *mut c_void;
14184        }
14185        if c < 0 {
14186            pp = &mut (*n).left;
14187        } else {
14188            pp = &mut (*n).right;
14189        }
14190    }
14191}
14192
14193#[no_mangle]
14194pub unsafe extern "C" fn tfind(
14195    key: *const c_void,
14196    rootp: *const *mut TreeNode,
14197    compar: ComparFn,
14198) -> *mut c_void {
14199    if rootp.is_null() {
14200        return core::ptr::null_mut();
14201    }
14202    let mut n = *rootp;
14203    loop {
14204        if n.is_null() {
14205            return core::ptr::null_mut();
14206        }
14207        let c = compar.unwrap()(key, (*n).key);
14208        if c == 0 {
14209            return n as *mut c_void;
14210        }
14211        if c < 0 {
14212            n = (*n).left;
14213        } else {
14214            n = (*n).right;
14215        }
14216    }
14217}
14218
14219#[no_mangle]
14220pub unsafe extern "C" fn tdelete(
14221    key: *const c_void,
14222    rootp: *mut *mut TreeNode,
14223    compar: ComparFn,
14224) -> *mut c_void {
14225    if rootp.is_null() {
14226        return core::ptr::null_mut();
14227    }
14228    let mut pp = rootp;
14229    let mut parent: *mut c_void = core::ptr::null_mut();
14230    loop {
14231        let n = *pp;
14232        if n.is_null() {
14233            return core::ptr::null_mut();
14234        }
14235        let c = compar.unwrap()(key, (*n).key);
14236        if c == 0 {
14237            break;
14238        }
14239        parent = n as *mut c_void;
14240        if c < 0 {
14241            pp = &mut (*n).left;
14242        } else {
14243            pp = &mut (*n).right;
14244        }
14245    }
14246    let n = *pp;
14247    // musl returns the node above the deleted one; deleting the root has no
14248    // parent, so it returns the (now-freed) root pointer as a non-null token.
14249    let result = if parent.is_null() { n as *mut c_void } else { parent };
14250    if !(*n).left.is_null() {
14251        // replace with in-order predecessor
14252        let mut q = &mut (*n).left;
14253        while !(*(*q)).right.is_null() {
14254            q = &mut (*(*q)).right;
14255        }
14256        let pred = *q;
14257        // swap keys
14258        (*n).key = (*pred).key;
14259        // remove predecessor
14260        *q = (*pred).left;
14261        free(pred as *mut c_void);
14262    } else {
14263        // replace with right child (may be null)
14264        *pp = (*n).right;
14265        free(n as *mut c_void);
14266    }
14267    result
14268}
14269
14270#[no_mangle]
14271pub unsafe extern "C" fn twalk(
14272    root: *const TreeNode,
14273    action: Option<unsafe extern "C" fn(*const c_void, c_int, c_int)>,
14274) {
14275    unsafe fn walk(
14276        node: *const TreeNode,
14277        action: Option<unsafe extern "C" fn(*const c_void, c_int, c_int)>,
14278        depth: c_int,
14279    ) {
14280        if node.is_null() {
14281            return;
14282        }
14283        let is_leaf = (*node).left.is_null() && (*node).right.is_null();
14284        if is_leaf {
14285            action.unwrap()(node as *const c_void, 3, depth); // leaf
14286        } else {
14287            action.unwrap()(node as *const c_void, 0, depth); // preorder
14288            walk((*node).left, action, depth + 1);
14289            action.unwrap()(node as *const c_void, 1, depth); // postorder (left done)
14290            walk((*node).right, action, depth + 1);
14291            action.unwrap()(node as *const c_void, 2, depth); // endorder
14292        }
14293    }
14294    walk(root, action, 0);
14295}
14296
14297#[no_mangle]
14298pub unsafe extern "C" fn tdestroy(root: *mut TreeNode, freekey: Option<unsafe extern "C" fn(*mut c_void)>) {
14299    if root.is_null() {
14300        return;
14301    }
14302    tdestroy((*root).left, freekey);
14303    tdestroy((*root).right, freekey);
14304    if let Some(f) = freekey {
14305        f((*root).key as *mut c_void);
14306    }
14307    free(root as *mut c_void);
14308}
14309
14310// ============================================================
14311// fnmatch: full POSIX pattern matching
14312// ============================================================
14313
14314const FNM_PATHNAME: c_int = 0x1;
14315const FNM_NOESCAPE: c_int = 0x2;
14316const FNM_PERIOD: c_int = 0x4;
14317const FNM_LEADING_DIR: c_int = 0x8;
14318const FNM_CASEFOLD: c_int = 0x10;
14319const FNM_NOMATCH: c_int = 1;
14320
14321const FNM_END: c_int = 0;
14322const FNM_STAR: c_int = -5;
14323const FNM_QUESTION: c_int = -4;
14324const FNM_BRACKET: c_int = -3;
14325const FNM_UNMATCHABLE: c_int = -2;
14326
14327fn ascii_tolower(c: u8) -> u8 {
14328    if c >= b'A' && c <= b'Z' { c + 32 } else { c }
14329}
14330
14331fn ascii_toupper(c: u8) -> u8 {
14332    if c >= b'a' && c <= b'z' { c - 32 } else { c }
14333}
14334
14335fn ascii_casefold(k: u8) -> u8 {
14336    let upper = ascii_toupper(k);
14337    if upper != k { upper } else { ascii_tolower(k) }
14338}
14339
14340/// Get next byte from pattern, classifying it.
14341/// Returns (token_type, bytes_consumed).
14342unsafe fn pat_next(pat: *const u8, m: usize, flags: c_int) -> (c_int, usize) {
14343    if m == 0 || *pat == 0 {
14344        return (FNM_END, 0);
14345    }
14346    let mut p = pat;
14347    let mut step = 1usize;
14348    let mut esc = false;
14349    if *p == b'\\' && !(flags & FNM_NOESCAPE != 0) && *p.add(1) != 0 {
14350        p = p.add(1);
14351        step = 2;
14352        esc = true;
14353    }
14354    if *p == b'[' && !esc {
14355        // scan for matching ]
14356        let mut k = 1usize;
14357        if k < m && (*pat.add(k) == b'^' || *pat.add(k) == b'!') { k += 1; }
14358        if k < m && *pat.add(k) == b']' { k += 1; }
14359        while k < m && *pat.add(k) != 0 && *pat.add(k) != b']' {
14360            if k + 1 < m && *pat.add(k) == b'[' &&
14361               (*pat.add(k+1) == b':' || *pat.add(k+1) == b'.' || *pat.add(k+1) == b'=') {
14362                let z = *pat.add(k+1);
14363                k += 2;
14364                if k < m { k += 1; }
14365                while k < m && *pat.add(k) != 0 && (*pat.add(k-1) != z || *pat.add(k) != b']') { k += 1; }
14366                if k == m || *pat.add(k) == 0 { break; }
14367            }
14368            k += 1;
14369        }
14370        if k == m || *pat.add(k) == 0 {
14371            // unmatched [ is literal
14372            return (b'[' as c_int, 1);
14373        }
14374        return (FNM_BRACKET, k + 1);
14375    }
14376    if *p == b'*' && !esc {
14377        return (FNM_STAR, 1);
14378    }
14379    if *p == b'?' && !esc {
14380        return (FNM_QUESTION, 1);
14381    }
14382    (*p as c_int, step)
14383}
14384
14385unsafe fn match_class(name: &[u8], k: u8, kfold: u8) -> bool {
14386    let eq = |c: u8| k == c || kfold == c;
14387    let in_range = |lo: u8, hi: u8| (k >= lo && k <= hi) || (kfold >= lo && kfold <= hi);
14388    match name {
14389        b"alnum" => in_range(b'0', b'9') || in_range(b'A', b'Z') || in_range(b'a', b'z'),
14390        b"alpha" => in_range(b'A', b'Z') || in_range(b'a', b'z'),
14391        b"blank" => eq(b' ') || eq(b'\t'),
14392        b"cntrl" => k < 0x20 || k == 0x7f,
14393        b"digit" => in_range(b'0', b'9'),
14394        b"graph" => k >= 0x21 && k <= 0x7e,
14395        b"lower" => in_range(b'a', b'z'),
14396        b"print" => k >= 0x20 && k <= 0x7e,
14397        b"punct" =>
14398            (k >= 0x21 && k <= 0x2f) ||
14399            (k >= 0x3a && k <= 0x40) ||
14400            (k >= 0x5b && k <= 0x60) ||
14401            (k >= 0x7b && k <= 0x7e),
14402        b"space" => eq(b' ') || eq(b'\t') || eq(b'\n') || eq(b'\r') || eq(0x0c) || eq(0x0b),
14403        b"upper" => in_range(b'A', b'Z'),
14404        b"xdigit" => in_range(b'0', b'9') || in_range(b'A', b'F') || in_range(b'a', b'f'),
14405        _ => false,
14406    }
14407}
14408
14409/// Match a bracket expression [class] against char k.
14410unsafe fn match_bracket(mut p: *const u8, k: u8, kfold: u8) -> bool {
14411    let mut inv = false;
14412    p = p.add(1); // skip [
14413    if *p == b'^' || *p == b'!' {
14414        inv = true;
14415        p = p.add(1);
14416    }
14417    // handle ] as first char
14418    if *p == b']' {
14419        if k == b']' { return !inv; }
14420        p = p.add(1);
14421    } else if *p == b'-' {
14422        if k == b'-' { return !inv; }
14423        p = p.add(1);
14424    }
14425    while *p != b']' && *p != 0 {
14426        if *p == b'-' && *p.add(1) != b']' && *p.add(1) != 0 {
14427            // range: previous char to next char
14428            let lo = *p.sub(1);
14429            let hi = *p.add(1);
14430            if lo <= hi && (k >= lo && k <= hi || kfold >= lo && kfold <= hi) {
14431                return !inv;
14432            }
14433            p = p.add(2);
14434        } else if *p == b'[' && (*p.add(1) == b':' || *p.add(1) == b'.' || *p.add(1) == b'=') {
14435            let z = *p.add(1);
14436            let start = p.add(2);
14437            let mut q = start;
14438            while *q != 0 && (*q != z || *q.add(1) != b']') { q = q.add(1); }
14439            if *q != 0 {
14440                let len = (q as usize) - (start as usize);
14441                if len > 0 {
14442                    let inner = core::slice::from_raw_parts(start, len);
14443                    let matched =
14444                        if z == b':' { match_class(inner, k, kfold) }
14445                        else { len == 1 && (inner[0] == k || inner[0] == kfold) };
14446                    if matched { return !inv; }
14447                }
14448                p = q.add(2);
14449                continue;
14450            }
14451        } else {
14452            if *p == k || *p == kfold {
14453                return !inv;
14454            }
14455            p = p.add(1);
14456        }
14457    }
14458    inv
14459}
14460
14461/// Core fnmatch for a single path component (no FNM_PATHNAME splitting).
14462/// Match one non-star, non-end pattern token against one input byte.
14463unsafe fn fnmatch_token(
14464    tok: c_int,
14465    pat: *const u8,
14466    s: *const u8,
14467    flags: c_int,
14468) -> bool {
14469    if *s == 0 {
14470        return false;
14471    }
14472    let k = *s;
14473    let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14474    match tok {
14475        FNM_QUESTION => true,
14476        FNM_BRACKET => match_bracket(pat, k, kfold),
14477        c => k as c_int == c || kfold as c_int == c,
14478    }
14479}
14480
14481unsafe fn fnmatch_internal(pat: *const u8, str: *const u8, flags: c_int) -> c_int {
14482    // Handle leading .
14483    if flags & FNM_PERIOD != 0 && *str == b'.' && *pat != b'.' {
14484        return FNM_NOMATCH;
14485    }
14486
14487    let mut p = pat;
14488    let mut s = str;
14489
14490    // Consume pattern up to first *
14491    loop {
14492        let (tok, step) = pat_next(p, usize::MAX, flags);
14493        match tok {
14494            FNM_END => {
14495                return if *s == 0 { 0 } else { FNM_NOMATCH };
14496            }
14497            FNM_STAR => {
14498                p = p.add(1);
14499                break;
14500            }
14501            _ => {
14502                if !fnmatch_token(tok, p, s, flags) { return FNM_NOMATCH; }
14503                p = p.add(step);
14504                s = s.add(1);
14505            }
14506        }
14507    }
14508
14509    // Now p points after first *, rest of pattern is variable
14510    // Factor: find tail after last * and count fixed chars needed
14511    let mut ptail = p;
14512    let mut tailcnt: usize = 0;
14513    let mut pp = p;
14514    loop {
14515        let (tok, step) = pat_next(pp, usize::MAX, flags);
14516        if tok == FNM_END { break; }
14517        if tok == FNM_STAR {
14518            tailcnt = 0;
14519            ptail = pp.add(1);
14520        } else {
14521            tailcnt += 1;
14522        }
14523        pp = pp.add(step);
14524    }
14525
14526    // str must have at least tailcnt chars
14527    let slen = strlen(s as *const c_char);
14528    if slen < tailcnt { return FNM_NOMATCH; }
14529
14530    // Match tail: ptail..end against str[tailcnt from end]
14531    let stail = s.add(slen - tailcnt);
14532    let mut tp = ptail;
14533    let mut ts = stail;
14534    loop {
14535        let (tok, step) = pat_next(tp, usize::MAX, flags);
14536        if tok == FNM_END {
14537            break;
14538        }
14539        if !fnmatch_token(tok, tp, ts, flags) { return FNM_NOMATCH; }
14540        tp = tp.add(step);
14541        ts = ts.add(1);
14542    }
14543
14544    let endstr = stail;
14545    let endpat = ptail;
14546
14547    let mut cp = p;
14548    let mut cs = s;
14549    while cp < endpat {
14550        let (tok, step) = pat_next(cp, usize::MAX, flags);
14551        if tok == FNM_STAR {
14552            cp = cp.add(step);
14553            cs = s;
14554            continue;
14555        }
14556        let comp_start = cp;
14557        let mut ok = false;
14558        let mut try_s = cs;
14559        while try_s < endstr {
14560            let mut tmp_p = comp_start;
14561            let mut tmp_s = try_s;
14562            let mut matched = true;
14563            loop {
14564                let (t, st) = pat_next(tmp_p, usize::MAX, flags);
14565                if t == FNM_STAR || t == FNM_END {
14566                    cp = tmp_p;
14567                    cs = tmp_s;
14568                    ok = true;
14569                    break;
14570                }
14571                if !fnmatch_token(t, tmp_p, tmp_s, flags) {
14572                    matched = false;
14573                    break;
14574                }
14575                tmp_s = tmp_s.add(1);
14576                tmp_p = tmp_p.add(st);
14577            }
14578            if ok { break; }
14579            if !matched {
14580                try_s = try_s.add(1);
14581            }
14582        }
14583        if !ok {
14584            return FNM_NOMATCH;
14585        }
14586    }
14587    0
14588}
14589
14590#[no_mangle]
14591pub unsafe extern "C" fn fnmatch(pat: *const c_char, str: *const c_char, flags: c_int) -> c_int {
14592    let pat = pat as *const u8;
14593    let str = str as *const u8;
14594
14595    if flags & FNM_PATHNAME != 0 {
14596        // Split on /
14597        let mut s = str;
14598        let mut p = pat;
14599        loop {
14600            // find next / in str
14601            let mut send = s;
14602            while *send != 0 && *send != b'/' { send = send.add(1); }
14603            // find next / in pat
14604            let mut pend = p;
14605            loop {
14606                let (tok, step) = pat_next(pend, usize::MAX, flags);
14607                if tok == FNM_END || (tok >= 0 && tok as u8 == b'/') {
14608                    break;
14609                }
14610                pend = pend.add(step);
14611            }
14612            let (ptok, pstep) = pat_next(pend, usize::MAX, flags);
14613            let pat_is_slash = ptok >= 0 && ptok as u8 == b'/';
14614            let str_is_slash = *send == b'/';
14615            if pat_is_slash != str_is_slash && (*send != 0 || !(flags & FNM_LEADING_DIR != 0)) {
14616                return FNM_NOMATCH;
14617            }
14618            // match component
14619            // We need a null-terminated copy of the component
14620            let plen = (pend as usize) - (p as usize);
14621            let slen = (send as usize) - (s as usize);
14622            // Components longer than 1024 bytes are rejected rather than
14623            // matched with a heap buffer.
14624            if plen > 1024 || slen > 1024 { return FNM_NOMATCH; }
14625            let mut pbuf = [0u8; 1025];
14626            let mut sbuf = [0u8; 1025];
14627            core::ptr::copy_nonoverlapping(p, pbuf.as_mut_ptr(), plen);
14628            pbuf[plen] = 0;
14629            core::ptr::copy_nonoverlapping(s, sbuf.as_mut_ptr(), slen);
14630            sbuf[slen] = 0;
14631            if fnmatch_internal(pbuf.as_ptr(), sbuf.as_ptr(), flags & !FNM_LEADING_DIR) != 0 {
14632                return FNM_NOMATCH;
14633            }
14634            if !pat_is_slash {
14635                return 0;
14636            }
14637            s = send.add(1);
14638            p = pend.add(pstep);
14639        }
14640    }
14641
14642    if flags & FNM_LEADING_DIR != 0 {
14643        // Try matching at each /
14644        let mut s = str;
14645        while *s != 0 {
14646            if *s == b'/' {
14647                // temporarily null-terminate
14648                // The prefix must be NUL-terminated for fnmatch_internal().
14649                let len = (s as usize) - (str as usize);
14650                // Just call fnmatch_internal with a temp buffer
14651                if len < 4096 {
14652                    let mut buf = [0u8; 4096];
14653                    core::ptr::copy_nonoverlapping(str, buf.as_mut_ptr(), len);
14654                    buf[len] = 0;
14655                    if fnmatch_internal(pat, buf.as_ptr(), flags) == 0 {
14656                        return 0;
14657                    }
14658                }
14659            }
14660            s = s.add(1);
14661        }
14662    }
14663
14664    fnmatch_internal(pat, str, flags)
14665}
14666
14667// ============================================================
14668// mntent: setmntent/endmntent/getmntent/getmntent_r/addmntent/hasmntopt
14669// ============================================================
14670
14671#[no_mangle]
14672pub unsafe extern "C" fn setmntent(name: *const c_char, mode: *const c_char) -> *mut FILE {
14673    fopen(name, mode)
14674}
14675
14676#[no_mangle]
14677pub unsafe extern "C" fn endmntent(f: *mut FILE) -> c_int {
14678    if !f.is_null() {
14679        fclose(f);
14680    }
14681    1
14682}
14683
14684// static buffers for getmntent (non-_r variant)
14685static mut MNTENT_MNT: MntEnt = MntEnt {
14686    mnt_fsname: core::ptr::null_mut(),
14687    mnt_dir: core::ptr::null_mut(),
14688    mnt_type: core::ptr::null_mut(),
14689    mnt_opts: core::ptr::null_mut(),
14690    mnt_freq: 0,
14691    mnt_passno: 0,
14692};
14693
14694#[repr(C)]
14695pub struct MntEnt {
14696    mnt_fsname: *mut c_char,
14697    mnt_dir: *mut c_char,
14698    mnt_type: *mut c_char,
14699    mnt_opts: *mut c_char,
14700    mnt_freq: c_int,
14701    mnt_passno: c_int,
14702}
14703
14704unsafe fn unescape_ent(beg: *mut c_char) -> *mut c_char {
14705    let mut dest = beg;
14706    let mut src = beg;
14707    while *src != 0 {
14708        if *src != b'\\' as c_char {
14709            *dest = *src;
14710            dest = dest.add(1);
14711            src = src.add(1);
14712            continue;
14713        }
14714        // backslash
14715        if *src.add(1) == b'\\' as c_char {
14716            src = src.add(1);
14717            *dest = *src;
14718            dest = dest.add(1);
14719            src = src.add(1);
14720            continue;
14721        }
14722        // octal escape
14723        let mut val: u8 = 0;
14724        let mut cnt = 0;
14725        let mut sp = src.add(1);
14726        while cnt < 3 && *sp >= b'0' as c_char && *sp <= b'7' as c_char {
14727            val = val * 8 + (*sp as u8 - b'0');
14728            sp = sp.add(1);
14729            cnt += 1;
14730        }
14731        if cnt > 0 {
14732            *dest = val as c_char;
14733            dest = dest.add(1);
14734            src = sp;
14735        } else {
14736            *dest = *src;
14737            dest = dest.add(1);
14738            src = src.add(1);
14739        }
14740    }
14741    *dest = 0;
14742    beg
14743}
14744
14745unsafe fn parse_mntent_line(
14746    linebuf: *mut c_char,
14747    mnt: *mut MntEnt,
14748) -> *mut MntEnt {
14749    let _len = strlen(linebuf as *const c_char);
14750    // skip comments and empty lines
14751    // parse: fsname dir type opts freq passno
14752    let mut p = linebuf;
14753    // skip leading whitespace
14754    while *p == b' ' as c_char || *p == b'\t' as c_char || *p == b'\n' as c_char || *p == b'\r' as c_char {
14755        p = p.add(1);
14756    }
14757    if *p == 0 || *p == b'#' as c_char {
14758        return core::ptr::null_mut();
14759    }
14760
14761    // fsname
14762    (*mnt).mnt_fsname = p;
14763    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14764        p = p.add(1);
14765    }
14766    if *p == 0 { return core::ptr::null_mut(); }
14767    *p = 0;
14768    p = p.add(1);
14769    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14770
14771    // dir
14772    (*mnt).mnt_dir = p;
14773    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14774        p = p.add(1);
14775    }
14776    if *p == 0 { return core::ptr::null_mut(); }
14777    *p = 0;
14778    p = p.add(1);
14779    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14780
14781    // type
14782    (*mnt).mnt_type = p;
14783    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14784        p = p.add(1);
14785    }
14786    if *p == 0 { return core::ptr::null_mut(); }
14787    *p = 0;
14788    p = p.add(1);
14789    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14790
14791    // opts
14792    (*mnt).mnt_opts = p;
14793    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14794        p = p.add(1);
14795    }
14796    if *p != 0 {
14797        *p = 0;
14798        p = p.add(1);
14799    }
14800    if *(*mnt).mnt_opts == 0 {
14801        (*mnt).mnt_opts = b"defaults\0".as_ptr() as *mut c_char;
14802    }
14803
14804    // freq and passno
14805    (*mnt).mnt_freq = 0;
14806    (*mnt).mnt_passno = 0;
14807    // skip whitespace
14808    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14809    if *p >= b'0' as c_char && *p <= b'9' as c_char {
14810        (*mnt).mnt_freq = (*p - b'0' as c_char) as c_int;
14811        p = p.add(1);
14812        while *p >= b'0' as c_char && *p <= b'9' as c_char {
14813            (*mnt).mnt_freq = (*mnt).mnt_freq * 10 + (*p - b'0' as c_char) as c_int;
14814            p = p.add(1);
14815        }
14816    }
14817    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14818    if *p >= b'0' as c_char && *p <= b'9' as c_char {
14819        (*mnt).mnt_passno = (*p - b'0' as c_char) as c_int;
14820        p = p.add(1);
14821        while *p >= b'0' as c_char && *p <= b'9' as c_char {
14822            (*mnt).mnt_passno = (*mnt).mnt_passno * 10 + (*p - b'0' as c_char) as c_int;
14823            p = p.add(1);
14824        }
14825    }
14826
14827    // unescape
14828    unescape_ent((*mnt).mnt_fsname);
14829    unescape_ent((*mnt).mnt_dir);
14830    unescape_ent((*mnt).mnt_type);
14831    unescape_ent((*mnt).mnt_opts);
14832
14833    mnt
14834}
14835
14836// Use a sentinel pointer to detect internal buffer usage
14837// cast integer to pointer for sentinel
14838static SENTINEL_PTR: usize = 1;
14839
14840// Read one char from FILE buffer directly (avoids musl's static fgets ABI mismatch)
14841unsafe fn mntent_fgetc(f: *mut FILE) -> c_int {
14842    fgetc(f)
14843}
14844
14845unsafe fn mntent_fgets(buf: *mut c_char, n: usize, f: *mut FILE) -> *mut c_char {
14846    if n == 0 { return core::ptr::null_mut(); }
14847    let max = n - 1;
14848    let mut i = 0usize;
14849    while i < max {
14850        let c = mntent_fgetc(f);
14851        if c == -1 { if i == 0 { return core::ptr::null_mut(); } break; }
14852        *buf.add(i) = c as c_char;
14853        i += 1;
14854        if c == b'\n' as c_int { break; }
14855    }
14856    *buf.add(i) = 0;
14857    buf
14858}
14859
14860#[no_mangle]
14861pub unsafe extern "C" fn getmntent_r(
14862    f: *mut FILE,
14863    mnt: *mut MntEnt,
14864    mut linebuf: *mut c_char,
14865    buflen: c_int,
14866) -> *mut MntEnt {
14867    let use_internal = linebuf as usize == SENTINEL_PTR;
14868
14869    (*mnt).mnt_freq = 0;
14870    (*mnt).mnt_passno = 0;
14871
14872    static mut MNT_LINE: *mut c_char = core::ptr::null_mut();
14873    static mut MNT_LINE_CAP: usize = 0;
14874
14875    loop {
14876        let res = if use_internal {
14877            let n = getline(&raw mut MNT_LINE, &raw mut MNT_LINE_CAP, f);
14878            if n < 0 {
14879                return core::ptr::null_mut();
14880            }
14881            linebuf = MNT_LINE;
14882            MNT_LINE
14883        } else {
14884            if buflen <= 0 {
14885                ERRNO!() = EINVAL;
14886                return core::ptr::null_mut();
14887            }
14888            mntent_fgets(linebuf, buflen as usize, f)
14889        };
14890        if res.is_null() {
14891            return core::ptr::null_mut();
14892        }
14893        let mut has_newline = false;
14894        let mut p = linebuf;
14895        while *p != 0 { if *p == b'\n' as c_char { has_newline = true; break; } p = p.add(1); }
14896        if !has_newline {
14897            ERRNO!() = 34;
14898            return core::ptr::null_mut();
14899        }
14900        let result = parse_mntent_line(linebuf, mnt);
14901        if !result.is_null() {
14902            return result;
14903        }
14904    }
14905}
14906
14907#[no_mangle]
14908pub unsafe extern "C" fn getmntent(f: *mut FILE) -> *mut MntEnt {
14909    getmntent_r(f, core::ptr::addr_of_mut!(MNTENT_MNT), SENTINEL_PTR as *mut c_char, 0)
14910}
14911
14912#[no_mangle]
14913pub unsafe extern "C" fn addmntent(f: *mut FILE, mnt: *const MntEnt) -> c_int {
14914    fseek(f, 0, 2); // SEEK_END
14915    let written = fprintf(
14916        f,
14917        b"%s\t%s\t%s\t%s\t%d\t%d\n\0".as_ptr() as *const c_char,
14918        (*mnt).mnt_fsname,
14919        (*mnt).mnt_dir,
14920        (*mnt).mnt_type,
14921        (*mnt).mnt_opts,
14922        (*mnt).mnt_freq,
14923        (*mnt).mnt_passno,
14924    );
14925    if written < 0 { 1 } else { 0 }
14926}
14927
14928#[no_mangle]
14929pub unsafe extern "C" fn hasmntopt(mnt: *const MntEnt, opt: *const c_char) -> *mut c_char {
14930    let l = strlen(opt as *const c_char);
14931    let mut p = (*mnt).mnt_opts;
14932    loop {
14933        if strncmp(p as *const u8, opt as *const u8, l) == 0 {
14934            let after = *p.add(l);
14935            if after == 0 || after == b',' as c_char || after == b'=' as c_char {
14936                return p;
14937            }
14938        }
14939        let comma = strchr(p as *const u8, b',' as c_int);
14940        if comma.is_null() {
14941            return core::ptr::null_mut();
14942        }
14943        p = comma.add(1) as *mut c_char;
14944    }
14945}
14946
14947// ============================================================
14948// SysV IPC: ftok, msg*, sem*, shm*
14949// x86_64 direct syscalls: msgget=68, msgsnd=69, msgrcv=70, msgctl=71
14950//   semget=64, semop=65, semctl=66, semtimedop=220
14951//   shmget=29, shmat=30, shmctl=31, shmdt=67
14952// ============================================================
14953
14954
14955#[inline]
14956unsafe fn sys_msgget(key: c_int, msgflg: c_int) -> i64 {
14957    <Arch as Syscalls>::syscall2(SYS_MSGGET, key as i64, msgflg as i64)
14958}
14959
14960#[inline]
14961unsafe fn sys_msgsnd(msqid: c_int, msgp: *const c_void, msgsz: usize, msgflg: c_int) -> i64 {
14962    <Arch as Syscalls>::syscall4(SYS_MSGSND, msqid as i64, msgp as i64, msgsz as i64, msgflg as i64)
14963}
14964
14965#[inline]
14966unsafe fn sys_msgrcv(msqid: c_int, msgp: *mut c_void, msgsz: usize, msgtyp: c_long, msgflg: c_int) -> i64 {
14967    <Arch as Syscalls>::syscall5(SYS_MSGRCV, msqid as i64, msgp as i64, msgsz as i64, msgtyp as i64, msgflg as i64)
14968}
14969
14970#[inline]
14971unsafe fn sys_msgctl(msqid: c_int, cmd: c_int, buf: *mut c_void) -> i64 {
14972    <Arch as Syscalls>::syscall3(SYS_MSGCTL, msqid as i64, cmd as i64, buf as i64)
14973}
14974
14975#[inline]
14976unsafe fn sys_semget(key: c_int, nsems: c_int, semflg: c_int) -> i64 {
14977    <Arch as Syscalls>::syscall3(SYS_SEMGET, key as i64, nsems as i64, semflg as i64)
14978}
14979
14980#[inline]
14981unsafe fn sys_semop(semid: c_int, sops: *const c_void, nsops: usize) -> i64 {
14982    <Arch as Syscalls>::syscall3(SYS_SEMOP, semid as i64, sops as i64, nsops as i64)
14983}
14984
14985#[inline]
14986unsafe fn sys_semctl(semid: c_int, semnum: c_int, cmd: c_int, arg: *mut c_void) -> i64 {
14987    <Arch as Syscalls>::syscall4(SYS_SEMCTL, semid as i64, semnum as i64, cmd as i64, arg as i64)
14988}
14989
14990#[inline]
14991unsafe fn sys_shmget(key: c_int, size: usize, shmflg: c_int) -> i64 {
14992    <Arch as Syscalls>::syscall3(SYS_SHMGET, key as i64, size as i64, shmflg as i64)
14993}
14994
14995#[inline]
14996unsafe fn sys_shmat(shmid: c_int, shmaddr: *const c_void, shmflg: c_int) -> i64 {
14997    <Arch as Syscalls>::syscall3(SYS_SHMAT, shmid as i64, shmaddr as i64, shmflg as i64)
14998}
14999
15000#[inline]
15001unsafe fn sys_shmdt(shmaddr: *const c_void) -> i64 {
15002    <Arch as Syscalls>::syscall1(SYS_SHMDT, shmaddr as i64)
15003}
15004
15005#[inline]
15006unsafe fn sys_shmctl(shmid: c_int, cmd: c_int, buf: *mut c_void) -> i64 {
15007    <Arch as Syscalls>::syscall3(SYS_SHMCTL, shmid as i64, cmd as i64, buf as i64)
15008}
15009
15010// ftok
15011#[no_mangle]
15012pub unsafe extern "C" fn ftok(path: *const c_char, id: c_int) -> c_int {
15013    let mut st: kernel_stat64 = core::mem::zeroed();
15014    let r = sys_stat(path as *const u8, &mut st);
15015    if r < 0 {
15016        ERRNO!() = (-r) as c_int;
15017        return -1;
15018    }
15019    ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16) | (((id as u32 & 0xff) << 24)) as u64) as c_int
15020}
15021
15022// msgget
15023#[no_mangle]
15024pub unsafe extern "C" fn msgget(key: c_int, msgflg: c_int) -> c_int {
15025    let r = sys_msgget(key, msgflg);
15026    syscall_ret(r) as c_int
15027}
15028
15029// msgsnd
15030#[no_mangle]
15031pub unsafe extern "C" fn msgsnd(msqid: c_int, msgp: *const c_void, msgsz: usize, msgflg: c_int) -> c_int {
15032    let r = sys_msgsnd(msqid, msgp, msgsz, msgflg);
15033    syscall_ret(r) as c_int
15034}
15035
15036// msgrcv
15037#[no_mangle]
15038pub unsafe extern "C" fn msgrcv(msqid: c_int, msgp: *mut c_void, msgsz: usize, msgtyp: c_long, msgflg: c_int) -> isize {
15039    let r = sys_msgrcv(msqid, msgp, msgsz, msgtyp, msgflg);
15040    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
15041}
15042
15043// msgctl
15044#[no_mangle]
15045pub unsafe extern "C" fn msgctl(msqid: c_int, cmd: c_int, buf: *mut c_void) -> c_int {
15046    let r = sys_msgctl(msqid, cmd, buf);
15047    syscall_ret(r) as c_int
15048}
15049
15050// semget
15051#[no_mangle]
15052pub unsafe extern "C" fn semget(key: c_int, nsems: c_int, semflg: c_int) -> c_int {
15053    if nsems > 65535 { ERRNO!() = 22; return -1; }
15054    let r = sys_semget(key, nsems, semflg);
15055    syscall_ret(r) as c_int
15056}
15057
15058// semop
15059#[no_mangle]
15060pub unsafe extern "C" fn semop(semid: c_int, sops: *const c_void, nsops: usize) -> c_int {
15061    let r = sys_semop(semid, sops, nsops);
15062    syscall_ret(r) as c_int
15063}
15064
15065// semctl - C variadic
15066#[no_mangle]
15067pub unsafe extern "C" fn semctl(semid: c_int, semnum: c_int, cmd: c_int, mut args: ...) -> c_int {
15068    let mut arg: *mut c_void = core::ptr::null_mut();
15069    // Commands that take the union semun argument
15070    match cmd {
15071        // SETVAL/SETALL/GETALL, IPC_SET/IPC_STAT/IPC_INFO, SEM_STAT,
15072        // SEM_INFO, SEM_STAT_ANY and the 32-bit compat variants all carry
15073        // the `union semun` argument.
15074        16 | 13 | 17 | 1 | 2 | 3 | 18 | 19 | 20 | 0x102 | 0x104 | 0x106 => {
15075            arg = args.next_arg::<*mut c_void>();
15076        }
15077        _ => {}
15078    }
15079    let r = sys_semctl(semid, semnum, cmd, arg);
15080    syscall_ret(r) as c_int
15081}
15082
15083// shmget
15084#[no_mangle]
15085pub unsafe extern "C" fn shmget(key: c_int, size: usize, shmflg: c_int) -> c_int {
15086    let r = sys_shmget(key, size, shmflg);
15087    syscall_ret(r) as c_int
15088}
15089
15090// shmat
15091#[no_mangle]
15092pub unsafe extern "C" fn shmat(shmid: c_int, shmaddr: *const c_void, shmflg: c_int) -> *mut c_void {
15093    let r = sys_shmat(shmid, shmaddr, shmflg);
15094    if (r as usize) > (-(4096isize as isize)) as usize {
15095        ERRNO!() = (-r) as c_int;
15096        return -1isize as *mut c_void;
15097    }
15098    r as *mut c_void
15099}
15100
15101// shmdt
15102#[no_mangle]
15103pub unsafe extern "C" fn shmdt(shmaddr: *const c_void) -> c_int {
15104    let r = sys_shmdt(shmaddr);
15105    syscall_ret(r) as c_int
15106}
15107
15108// shmctl
15109#[no_mangle]
15110pub unsafe extern "C" fn shmctl(shmid: c_int, cmd: c_int, buf: *mut c_void) -> c_int {
15111    let r = sys_shmctl(shmid, cmd, buf);
15112    syscall_ret(r) as c_int
15113}
15114
15115// ============================================================
15116// Startup: __libc_start_main
15117//
15118// musl crt1.o _start_c calls:
15119//   __libc_start_main(main, argc, argv, _init, _fini, rtld_fini, stack_end)
15120// ============================================================
15121
15122// Auxiliary vector pointer, populated by the dynamic linker before
15123// constructors run so getauxval() works during early startup.
15124#[no_mangle]
15125pub static mut __auxv: *const usize = core::ptr::null();
15126#[no_mangle]
15127pub static mut __keel_static_base: usize = 0;
15128static mut RC_STATIC_EXEC: bool = false;
15129
15130#[no_mangle]
15131pub static mut __progname: *mut c_char = core::ptr::null_mut();
15132#[no_mangle]
15133pub static mut __progname_full: *mut c_char = core::ptr::null_mut();
15134#[no_mangle]
15135pub static mut program_invocation_name: *mut c_char = core::ptr::null_mut();
15136#[no_mangle]
15137pub static mut program_invocation_short_name: *mut c_char = core::ptr::null_mut();
15138
15139#[no_mangle]
15140pub static in6addr_any: [u32; 4] = [0; 4];
15141#[no_mangle]
15142pub static in6addr_loopback: [u32; 4] = [0, 0, 0, 0x0100_0000];
15143
15144#[no_mangle]
15145pub static mut __daylight: c_int = 0;
15146#[no_mangle]
15147pub static mut __timezone: c_long = 0;
15148#[no_mangle]
15149pub static mut __tzname: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
15150
15151#[no_mangle]
15152pub unsafe extern "C" fn getauxval(type_: c_ulong) -> c_ulong {
15153    let mut p = __auxv;
15154    if p.is_null() {
15155        return 0;
15156    }
15157    loop {
15158        let tag = *p;
15159        if tag == 0 {
15160            return 0;
15161        }
15162        if tag == type_ as usize {
15163            return *p.add(1) as c_ulong;
15164        }
15165        p = p.add(2);
15166    }
15167}
15168
15169
15170unsafe fn run_static_init() {
15171    if !RC_STATIC_EXEC {
15172        return;
15173    }
15174    extern "C" {
15175        static __preinit_array_start: usize;
15176        static __preinit_array_end: usize;
15177        static __init_array_start: usize;
15178        static __init_array_end: usize;
15179    }
15180    let mut p = core::ptr::addr_of!(__preinit_array_start) as usize;
15181    let end = core::ptr::addr_of!(__preinit_array_end) as usize;
15182    while p < end {
15183        let f = core::ptr::read_unaligned(p as *const usize);
15184        if f != 0 {
15185            let f: unsafe extern "C" fn() = core::mem::transmute(f);
15186            f();
15187        }
15188        p += core::mem::size_of::<usize>();
15189    }
15190    p = core::ptr::addr_of!(__init_array_start) as usize;
15191    let end = core::ptr::addr_of!(__init_array_end) as usize;
15192    while p < end {
15193        let f = core::ptr::read_unaligned(p as *const usize);
15194        if f != 0 {
15195            let f: unsafe extern "C" fn() = core::mem::transmute(f);
15196            f();
15197        }
15198        p += core::mem::size_of::<usize>();
15199    }
15200}
15201
15202type MainFn = unsafe extern "C" fn(c_int, *const *const c_char, *const *const c_char) -> c_int;
15203type InitFn = unsafe extern "C" fn();
15204
15205#[cfg(target_arch = "x86_64")]
15206unsafe fn static_tls_tp() -> usize {
15207    let mut fs: u64 = 0;
15208    if arch_prctl(0x1003, &mut fs as *mut u64 as u64) != 0 {
15209        0
15210    } else {
15211        fs as usize
15212    }
15213}
15214
15215#[cfg(target_arch = "x86_64")]
15216unsafe fn set_static_tls_tp(tp: usize) {
15217    let _ = arch_prctl(0x1002, tp as u64);
15218}
15219
15220#[cfg(target_arch = "aarch64")]
15221unsafe fn static_tls_tp() -> usize {
15222    let tp: usize;
15223    core::arch::asm!("mrs {}, tpidr_el0", out(reg) tp, options(nostack));
15224    tp
15225}
15226
15227#[cfg(target_arch = "aarch64")]
15228unsafe fn set_static_tls_tp(tp: usize) {
15229    core::arch::asm!("msr tpidr_el0, {}", in(reg) tp, options(nostack));
15230}
15231
15232#[cfg(target_arch = "riscv64")]
15233unsafe fn static_tls_tp() -> usize {
15234    let tp: usize;
15235    core::arch::asm!("mv {}, tp", out(reg) tp, options(nostack));
15236    tp
15237}
15238
15239#[cfg(target_arch = "riscv64")]
15240unsafe fn set_static_tls_tp(tp: usize) {
15241    core::arch::asm!("mv tp, {}", in(reg) tp, options(nostack));
15242}
15243
15244static mut STATIC_TLS_BLOCK_SIZE: usize = 0;
15245static mut STATIC_TLS_TP_OFFSET: usize = 0;
15246static mut STATIC_TLS_VAR_OFFSET: usize = 0;
15247static mut STATIC_TLS_TLS_SIZE: usize = 0;
15248static mut STATIC_TLS_IMAGE: *const u8 = core::ptr::null();
15249static mut STATIC_TLS_FILESZ: usize = 0;
15250static mut STATIC_TLS_CANARY: u64 = 0;
15251
15252// Word indices in the 256-byte TCB. Keep in sync with libc/src/ldso/mod.rs.
15253const TCB_GENERATION: usize = 1;
15254const TCB_TLS_SIZE: usize = 2;
15255const TCB_MODULE_COUNT: usize = 3;
15256const TCB_TLSDESC: usize = 4;
15257const TCB_CANARY: usize = 5;
15258const TCB_ERRNO: usize = 6;
15259const TCB_GETRANDOM: usize = 7;
15260const TCB_THREAD: usize = 8;
15261
15262unsafe fn static_tls_init_block(block: *mut u8) -> *mut u8 {
15263    if block.is_null() || STATIC_TLS_BLOCK_SIZE == 0 {
15264        return core::ptr::null_mut();
15265    }
15266    let var_base = block.add(STATIC_TLS_VAR_OFFSET);
15267    if STATIC_TLS_TLS_SIZE > 0 {
15268        core::ptr::write_bytes(var_base, 0, STATIC_TLS_TLS_SIZE);
15269    }
15270    if STATIC_TLS_FILESZ > 0 && !STATIC_TLS_IMAGE.is_null() {
15271        core::ptr::copy_nonoverlapping(STATIC_TLS_IMAGE, var_base, STATIC_TLS_FILESZ);
15272    }
15273    let tp = block.add(STATIC_TLS_TP_OFFSET);
15274    let tcb = if cfg!(target_arch = "x86_64") {
15275        tp as usize
15276    } else {
15277        block as usize
15278    };
15279    core::ptr::write_unaligned(tcb as *mut u64, tcb as u64);
15280    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_GENERATION), 1);
15281    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_TLS_SIZE), STATIC_TLS_TLS_SIZE as u64);
15282    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_MODULE_COUNT), 1);
15283    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_TLSDESC), 0);
15284    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_CANARY), STATIC_TLS_CANARY);
15285    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_ERRNO), 0);
15286    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_GETRANDOM), 0);
15287    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_THREAD), 0);
15288    tp
15289}
15290
15291unsafe fn static_tls_create_block() -> *mut u8 {
15292    if STATIC_TLS_BLOCK_SIZE == 0 {
15293        return core::ptr::null_mut();
15294    }
15295    let block = sys_mmap(
15296        core::ptr::null_mut(),
15297        STATIC_TLS_BLOCK_SIZE,
15298        PROT_READ | PROT_WRITE,
15299        MAP_PRIVATE | MAP_ANONYMOUS,
15300        -1,
15301        0,
15302    );
15303    if block.is_null() || block == MMAP_FAILED {
15304        return core::ptr::null_mut();
15305    }
15306    static_tls_init_block(block)
15307}
15308
15309#[repr(C)]
15310pub struct TlsIndex {
15311    pub ti_module: usize,
15312    pub ti_offset: usize,
15313}
15314
15315/// Global-dynamic TLS access.  The dynamic loader intercepts this symbol for
15316/// dynamically linked programs and uses its own multi-module implementation.
15317/// A static executable has only module 0, so resolve directly against the
15318/// static TLS block created by `init_static_tls()`.
15319static mut TLS_GET_ADDR_IMPL: usize = 0;
15320
15321/// The dynamic loader installs its multi-module TLS resolver here before
15322/// running constructors.  Keeping a dispatch pointer means a program that
15323/// obtains `__tls_get_addr` through `dlsym` still reaches the loader's
15324/// implementation rather than the static fallback below.
15325#[no_mangle]
15326pub unsafe extern "C" fn __keel_set_tls_get_addr(f: usize) {
15327    TLS_GET_ADDR_IMPL = f;
15328}
15329
15330#[no_mangle]
15331pub unsafe extern "C" fn __tls_get_addr(ti: *const TlsIndex) -> *mut u8 {
15332    if TLS_GET_ADDR_IMPL != 0 {
15333        let f: unsafe extern "C" fn(*const TlsIndex) -> *mut u8 =
15334            core::mem::transmute(TLS_GET_ADDR_IMPL);
15335        return f(ti);
15336    }
15337    if ti.is_null() || (*ti).ti_module != 0 || !RC_STATIC_EXEC {
15338        return core::ptr::null_mut();
15339    }
15340    let tp = static_tls_tp();
15341    if tp == 0 {
15342        return core::ptr::null_mut();
15343    }
15344    (tp - STATIC_TLS_TP_OFFSET + STATIC_TLS_VAR_OFFSET + (*ti).ti_offset) as *mut u8
15345}
15346
15347/// Static executables have no dynamic loader to build a TCB.  Allocate one
15348/// from PT_TLS so that `%fs`/TP-relative TLS accesses and errno work.
15349unsafe fn init_static_tls() {
15350    if static_tls_tp() != 0 {
15351        return;
15352    }
15353    let phdr = getauxval(3) as usize; // AT_PHDR
15354    let phnum = getauxval(5) as usize; // AT_PHNUM
15355    let phent = getauxval(4) as usize; // AT_PHENT
15356    if phdr == 0 || phnum == 0 || phent < 56 {
15357        return;
15358    }
15359
15360    let mut tls_vaddr = 0usize;
15361    let mut tls_filesz = 0usize;
15362    let mut tls_memsz = 0usize;
15363    let mut tls_align = 1usize;
15364    let mut exec_base = __keel_static_base;
15365    let mut i = 0usize;
15366    while i < phnum {
15367        let ph = phdr + i * phent;
15368        let p_type = core::ptr::read_unaligned(ph as *const u32);
15369        if p_type == 3 {
15370            // PT_INTERP means the dynamic loader already owns TLS.
15371            return;
15372        }
15373        if p_type == 6 {
15374            // PT_PHDR
15375            if exec_base == 0 {
15376                let p_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
15377                exec_base = phdr.wrapping_sub(p_vaddr);
15378            }
15379        } else if p_type == 7 {
15380            // PT_TLS
15381            tls_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
15382            tls_filesz = core::ptr::read_unaligned((ph + 32) as *const u64) as usize;
15383            tls_memsz = core::ptr::read_unaligned((ph + 40) as *const u64) as usize;
15384            let align = core::ptr::read_unaligned((ph + 48) as *const u64) as usize;
15385            if align > 1 {
15386                tls_align = align;
15387            }
15388        }
15389        i += 1;
15390    }
15391
15392    let tcb_size = 256usize;
15393    #[cfg(target_arch = "x86_64")]
15394    let gap = 0usize;
15395    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
15396    let gap = if cfg!(target_arch = "aarch64") { 16usize } else { 0usize };
15397
15398    let tls_size = if tls_align > 1 {
15399        (tls_memsz + tls_align - 1) & !(tls_align - 1)
15400    } else {
15401        tls_memsz
15402    };
15403    let total = tcb_size + gap + tls_size + tls_align;
15404    STATIC_TLS_BLOCK_SIZE = total;
15405    STATIC_TLS_TP_OFFSET = if cfg!(target_arch = "x86_64") {
15406        tls_size
15407    } else {
15408        tcb_size
15409    };
15410    STATIC_TLS_VAR_OFFSET = if cfg!(target_arch = "x86_64") {
15411        0
15412    } else {
15413        tcb_size + gap
15414    };
15415    STATIC_TLS_TLS_SIZE = tls_size;
15416    STATIC_TLS_IMAGE = (exec_base + tls_vaddr) as *const u8;
15417    STATIC_TLS_FILESZ = tls_filesz;
15418    let random = getauxval(25) as *const u8; // AT_RANDOM
15419    STATIC_TLS_CANARY = if random.is_null() {
15420        0xdefaced_cafebeefu64
15421    } else {
15422        core::ptr::read_unaligned(random as *const u64)
15423            ^ core::ptr::read_unaligned(random.add(8) as *const u64)
15424    };
15425
15426    let block = sys_mmap(
15427        core::ptr::null_mut(),
15428        total,
15429        PROT_READ | PROT_WRITE,
15430        MAP_PRIVATE | MAP_ANONYMOUS,
15431        -1,
15432        0,
15433    );
15434    if block.is_null() || block == MMAP_FAILED {
15435        return;
15436    }
15437    let tp = static_tls_init_block(block);
15438    if tp.is_null() {
15439        return;
15440    }
15441    set_static_tls_tp(tp as usize);
15442    RC_STATIC_EXEC = true;
15443}
15444
15445
15446#[no_mangle]
15447pub unsafe extern "C" fn __libc_start_main(
15448    main: MainFn,
15449    argc: c_int,
15450    argv: *const *const c_char,
15451    _init: *const c_void,
15452    _fini: *const c_void,
15453    _rtld_fini: *const c_void,
15454    _stack_end: *const c_void,
15455) -> ! {
15456    let envp = argv.add((argc + 1) as usize);
15457    let mut aux = envp;
15458    while !(*aux).is_null() {
15459        aux = aux.add(1);
15460    }
15461    __auxv = aux.add(1) as *const usize;
15462    init_static_tls();
15463    errno_init();
15464    // Register the main thread during startup.  pthread_exit() uses the
15465    // thread table to decide whether it is the last thread; if the main
15466    // thread only registered lazily, a worker exiting first could call
15467    // exit() while the main thread was still alive.  Register slot 0
15468    // directly: pthread_self() would otherwise scan the whole static thread
15469    // table and fault in roughly 1 MiB on every process start.
15470    register_main_thread();
15471
15472    __environ = envp as *mut *mut c_char;
15473    environ = __environ; // sync environ alias
15474    ___environ = __environ;
15475    _environ = __environ;
15476
15477    // glibc-compatible program name globals.
15478    if !argv.is_null() && argc > 0 {
15479        let argv0 = *argv;
15480        __progname_full = argv0 as *mut c_char;
15481        program_invocation_name = argv0 as *mut c_char;
15482        let mut base = argv0;
15483        let mut p = argv0;
15484        while *p != 0 {
15485            if *p == b'/' as c_char { base = p.add(1); }
15486            p = p.add(1);
15487        }
15488        __progname = base as *mut c_char;
15489        program_invocation_short_name = base as *mut c_char;
15490    }
15491
15492    __stdio_init();
15493    run_static_init();
15494
15495    let mut set: SigSetT = 0;
15496    sigemptyset(&mut set);
15497    sigaddset(&mut set, SIGCANCEL);
15498    sigprocmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
15499
15500    if !_init.is_null() {
15501        let init_fn: InitFn = core::mem::transmute(_init);
15502        init_fn();
15503    }
15504
15505    // aarch64/riscv64 GCC reads __stack_chk_guard as a global (GOT-based for PIE),
15506    // so we must initialize it from AT_RANDOM before calling main.
15507    // x86_64 uses %fs:0x28 which the kernel already set up.
15508    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
15509    {
15510        let random_ptr = getauxval(25) as *const u8; // AT_RANDOM = 25
15511        if !random_ptr.is_null() {
15512            let a = core::ptr::read_unaligned(random_ptr as *const u64);
15513            let b = core::ptr::read_unaligned(random_ptr.add(8) as *const u64);
15514            __stack_chk_guard = (a ^ b) as usize;
15515        } else {
15516            // Linux always supplies AT_RANDOM; keep a nonzero fallback for
15517            // the unlikely case where the auxiliary vector is absent.
15518            __stack_chk_guard = 0xdefaced_cafebeef;
15519        }
15520    }
15521
15522    let result = main(argc, argv, envp);
15523
15524    if !_fini.is_null() {
15525        let fini_fn: InitFn = core::mem::transmute(_fini);
15526        fini_fn();
15527    }
15528
15529    exit(result);
15530}
15531
15532type LdsoDlopenFn = unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void;
15533type LdsoDlsymFn = unsafe extern "C" fn(*mut c_void, *const c_char, *mut c_void) -> *mut c_void;
15534type LdsoDlcloseFn = unsafe extern "C" fn(*mut c_void) -> c_int;
15535type LdsoDlerrorFn = unsafe extern "C" fn() -> *const c_char;
15536
15537static mut LDSO_DLOPEN: Option<LdsoDlopenFn> = None;
15538static mut LDSO_DLSYM: Option<LdsoDlsymFn> = None;
15539static mut LDSO_DLCLOSE: Option<LdsoDlcloseFn> = None;
15540static mut LDSO_DLERROR: Option<LdsoDlerrorFn> = None;
15541
15542#[no_mangle]
15543pub unsafe extern "C" fn __ldso_register_dlopen(f: LdsoDlopenFn) {
15544    LDSO_DLOPEN = Some(f);
15545}
15546
15547#[no_mangle]
15548pub unsafe extern "C" fn __ldso_register_dlsym(f: LdsoDlsymFn) {
15549    LDSO_DLSYM = Some(f);
15550}
15551
15552#[no_mangle]
15553pub unsafe extern "C" fn __ldso_register_dlclose(f: LdsoDlcloseFn) {
15554    LDSO_DLCLOSE = Some(f);
15555}
15556
15557#[no_mangle]
15558pub unsafe extern "C" fn __ldso_register_dlerror(f: LdsoDlerrorFn) {
15559    LDSO_DLERROR = Some(f);
15560}
15561
15562#[no_mangle]
15563pub unsafe extern "C" fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void {
15564    if let Some(f) = LDSO_DLOPEN {
15565        f(filename, flags)
15566    } else {
15567        null_mut()
15568    }
15569}
15570
15571#[no_mangle]
15572pub unsafe extern "C" fn dlsym_impl(
15573    handle: *mut c_void,
15574    symbol: *const c_char,
15575    ra: *mut c_void,
15576) -> *mut c_void {
15577    if let Some(f) = LDSO_DLSYM {
15578        f(handle, symbol, ra)
15579    } else {
15580        null_mut()
15581    }
15582}
15583
15584// dlsym() must pass its own return address to the loader so that
15585// RTLD_NEXT can identify the calling object.  Keep the public entry
15586// point in assembly and tail-jump into the Rust implementation.
15587#[no_mangle]
15588#[unsafe(naked)]
15589#[cfg(target_arch = "x86_64")]
15590pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15591    core::arch::naked_asm!("mov rdx, [rsp]", "jmp dlsym_impl");
15592}
15593
15594#[no_mangle]
15595#[unsafe(naked)]
15596#[cfg(target_arch = "aarch64")]
15597pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15598    core::arch::naked_asm!("mov x2, x30", "b dlsym_impl");
15599}
15600
15601#[no_mangle]
15602#[unsafe(naked)]
15603#[cfg(target_arch = "riscv64")]
15604pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15605    core::arch::naked_asm!("mv a2, ra", "la t0, dlsym_impl", "jr t0");
15606}
15607
15608#[no_mangle]
15609pub unsafe extern "C" fn dlclose(handle: *mut c_void) -> c_int {
15610    if let Some(f) = LDSO_DLCLOSE {
15611        f(handle)
15612    } else {
15613        0
15614    }
15615}
15616
15617#[no_mangle]
15618pub unsafe extern "C" fn dlerror() -> *const c_char {
15619    if let Some(f) = LDSO_DLERROR {
15620        f()
15621    } else {
15622        core::ptr::null()
15623    }
15624}
15625
15626include!("crypt_impl.rs");
15627include!("statvfs.rs");
15628include!("daemon.rs");
15629include!("safety.rs");
15630include!("dn_expand.rs");
15631include!("lrand48.rs");
15632include!("strverscmp.rs");
15633include!("syscall.rs");
15634include!("pthread_atfork.rs");
15635include!("fenv.rs");
15636include!("locale_ctype.rs");
15637include!("regression_stubs.rs");
15638include!("ctype_tables.rs");
15639include!("wctype_tables.rs");
15640include!("netdb_extra.rs");
15641include!("compat_extra.rs");
15642include!("stdio_extra.rs");
15643include!("ns_parse.rs");
15644include!("fts.rs");
15645include!("ifaddrs.rs");
15646include!("dl_extra.rs");
15647include!("des.rs");
15648include!("path_extra.rs");
15649include!("wordexp.rs");
15650include!("getopt_impl.rs");
15651
15652// ============================================================
15653// regex.h
15654// ============================================================
15655
15656// musl defines regoff_t as _Addr (long on every Linux target), not int.
15657type regoff_t = c_long;
15658
15659#[repr(C)]
15660pub struct regex_t {
15661    pub re_nsub: usize,
15662    pub __opaque: *mut c_void,
15663    pub __padding: [*mut c_void; 4],
15664    pub __nsub2: usize,
15665    pub __padding2: c_char,
15666}
15667
15668#[repr(C)]
15669pub struct regmatch_t {
15670    pub rm_so: regoff_t,
15671    pub rm_eo: regoff_t,
15672}
15673
15674include!("regex.rs");
15675include!("tz.rs");
15676
15677// The dynamic loader is part of libc, mirroring musl's single-file design.
15678// It is compiled as a module so its private syscall/string helpers do not
15679// collide with the libc namespace; its exported entry points remain global.
15680#[allow(dead_code, deref_nullptr)]
15681mod ldso;
15682
15683#[cfg(test)]
15684mod libc_unit_stub {
15685    #[test]
15686    fn stub() {
15687        assert!(true);
15688    }
15689}
15690
15691// ============================================================
15692// fmax/fmin and related helpers
15693// ============================================================
15694
15695#[inline]
15696pub(crate) fn fmax_impl(x: f64, y: f64) -> f64 {
15697    if x.is_nan() { return y; }
15698    if y.is_nan() { return x; }
15699    if x == 0.0 && y == 0.0 {
15700        return if x.is_sign_negative() && y.is_sign_negative() { -0.0 } else { 0.0 };
15701    }
15702    if x > y { x } else { y }
15703}
15704
15705#[inline]
15706pub(crate) fn fmin_impl(x: f64, y: f64) -> f64 {
15707    if x.is_nan() { return y; }
15708    if y.is_nan() { return x; }
15709    if x == 0.0 && y == 0.0 {
15710        return if x.is_sign_negative() || y.is_sign_negative() { -0.0 } else { 0.0 };
15711    }
15712    if x < y { x } else { y }
15713}
15714
15715#[inline]
15716pub(crate) fn fmaxf_impl(x: f32, y: f32) -> f32 {
15717    if x.is_nan() { return y; }
15718    if y.is_nan() { return x; }
15719    if x == 0.0 && y == 0.0 {
15720        return if x.is_sign_negative() && y.is_sign_negative() { -0.0 } else { 0.0 };
15721    }
15722    if x > y { x } else { y }
15723}
15724
15725#[inline]
15726pub(crate) fn fminf_impl(x: f32, y: f32) -> f32 {
15727    if x.is_nan() { return y; }
15728    if y.is_nan() { return x; }
15729    if x == 0.0 && y == 0.0 {
15730        return if x.is_sign_negative() || y.is_sign_negative() { -0.0 } else { 0.0 };
15731    }
15732    if x < y { x } else { y }
15733}
15734
15735#[inline(never)]
15736#[no_mangle]
15737pub unsafe extern "C" fn fmax(x: f64, y: f64) -> f64 {
15738    fmax_impl(x, y)
15739}
15740
15741#[inline(never)]
15742#[no_mangle]
15743pub unsafe extern "C" fn fmin(x: f64, y: f64) -> f64 {
15744    fmin_impl(x, y)
15745}
15746
15747#[no_mangle]
15748pub unsafe extern "C" fn fminf(x: f32, y: f32) -> f32 {
15749    fminf_impl(x, y)
15750}
15751
15752#[no_mangle]
15753pub unsafe extern "C" fn fdim(x: f64, y: f64) -> f64 {
15754    if x.is_nan() || y.is_nan() {
15755        return f64::NAN;
15756    }
15757    if x > y { x - y } else { 0.0 }
15758}
15759
15760#[no_mangle]
15761pub unsafe extern "C" fn fma(x: f64, y: f64, z: f64) -> f64 {
15762    if (x.is_infinite() && y == 0.0) || (y.is_infinite() && x == 0.0) {
15763        feraiseexcept(FE_INVALID);
15764        return f64::NAN;
15765    }
15766    if x.is_nan() || y.is_nan() || z.is_nan() {
15767        return f64::NAN;
15768    }
15769    let r = libm::fma(x, y, z);
15770    // inf-inf is invalid; libm may return NaN without raising.
15771    if r.is_nan() {
15772        feraiseexcept(FE_INVALID);
15773    }
15774    r
15775}
15776
15777#[no_mangle]
15778pub unsafe extern "C" fn ilogb(x: f64) -> i32 {
15779    if x.is_nan() {
15780        feraiseexcept(FE_INVALID);
15781        return -0x7fffffff - 1; // FP_ILOGBNAN
15782    }
15783    if x == 0.0 || x.is_infinite() {
15784        feraiseexcept(FE_INVALID);
15785        return if x == 0.0 { -0x7fffffff - 1 } else { 0x7fffffff };
15786    }
15787    let bits = x.to_bits();
15788    let exp = ((bits >> 52) & 0x7ff) as i32;
15789    if exp == 0 {
15790        // subnormal
15791        let mut v = bits & 0xfffffffffffff;
15792        let mut e = -1022;
15793        while v < (1u64 << 52) { v <<= 1; e -= 1; }
15794        e
15795    } else {
15796        exp - 1023
15797    }
15798}
15799
15800#[no_mangle]
15801pub unsafe extern "C" fn logb(x: f64) -> f64 {
15802    if x.is_nan() { return x; }
15803    if x == 0.0 { return __math_divzero(1); }
15804    let bits = x.to_bits();
15805    let exp = ((bits >> 52) & 0x7ff) as i32;
15806    if exp == 0 {
15807        // subnormal
15808        let mut v = bits & 0xfffffffffffff;
15809        let mut e = -1022i32;
15810        while v < (1u64 << 52) { v <<= 1; e -= 1; }
15811        e as f64
15812    } else if exp == 0x7ff {
15813        x * x // infinity * infinity = infinity (preserves sign)
15814    } else {
15815        (exp - 1023) as f64
15816    }
15817}
15818
15819#[no_mangle]
15820pub unsafe extern "C" fn nearbyint(x: f64) -> f64 {
15821    let had_inexact = fetestexcept(FE_INEXACT) & FE_INEXACT != 0;
15822    let r = libm::rint(x);
15823    if !had_inexact {
15824        feclearexcept(FE_INEXACT);
15825    }
15826    r
15827}
15828
15829#[no_mangle]
15830pub unsafe extern "C" fn nextafter(x: f64, y: f64) -> f64 {
15831    if x.is_nan() || y.is_nan() { return x + y; }
15832    if x == 0.0 && y == 0.0 { return y; }
15833    if x == y { return x; }
15834    let r = libm::nextafter(x, y);
15835    if r.is_infinite() && x.is_finite() {
15836        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
15837    } else if r != x {
15838        let bits = r.to_bits();
15839        let is_subnormal = (bits & 0x7ff0000000000000) == 0 && (bits & 0xfffffffffffff) != 0;
15840        if r == 0.0 || is_subnormal {
15841            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
15842        }
15843    }
15844    r
15845}
15846
15847#[no_mangle]
15848pub unsafe extern "C" fn nexttoward(x: f64, y: f64) -> f64 {
15849    // On x86_64, long double = f64, so nexttoward = nextafter
15850    if x == 0.0 && y == 0.0 {
15851        return if y.is_sign_negative() { -0.0 } else { 0.0 };
15852    }
15853    nextafter(x, y)
15854}
15855
15856#[no_mangle]
15857pub unsafe extern "C" fn remainder(x: f64, y: f64) -> f64 {
15858    if x.is_nan() || y.is_nan() { return x + y; }
15859    if y == 0.0 || x.is_infinite() { return __math_invalid(x); }
15860    libm::remainder(x, y)
15861}
15862
15863#[no_mangle]
15864pub unsafe extern "C" fn remquo(x: f64, y: f64, quo: *mut i32) -> f64 {
15865    if x.is_nan() || y.is_nan() {
15866        if !quo.is_null() { *quo = 0; }
15867        return x + y;
15868    }
15869    if y == 0.0 || x.is_infinite() {
15870        if !quo.is_null() { *quo = 0; }
15871        return __math_invalid(x);
15872    }
15873    let (r, q) = libm::remquo(x, y);
15874    if !quo.is_null() { *quo = q; }
15875    r
15876}
15877
15878#[no_mangle]
15879pub unsafe extern "C" fn exp2(x: f64) -> f64 {
15880    exp2_impl(x)
15881}
15882
15883#[no_mangle]
15884pub unsafe extern "C" fn expm1(x: f64) -> f64 {
15885    let r = libm::expm1(x);
15886    // Raise UNDERFLOW for very small results that underflow
15887    if r != 0.0 && x != 0.0 && libm::fabs(x) < 1e-307 {
15888        feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
15889    }
15890    r
15891}
15892
15893#[no_mangle]
15894pub unsafe extern "C" fn log1p(x: f64) -> f64 {
15895    if x == -1.0 {
15896        feraiseexcept(FE_DIVBYZERO);
15897        return f64::NEG_INFINITY;
15898    }
15899    libm::log1p(x)
15900}
15901
15902#[no_mangle]
15903pub unsafe extern "C" fn acosh(x: f64) -> f64 {
15904    if x < 1.0 {
15905        feraiseexcept(FE_INVALID);
15906        return f64::NAN;
15907    }
15908    libm::acosh(x)
15909}
15910
15911#[no_mangle]
15912pub unsafe extern "C" fn asinh(x: f64) -> f64 {
15913    if x == 0.0 { return x; }
15914    libm::asinh(x)
15915}
15916
15917#[no_mangle]
15918pub unsafe extern "C" fn atanh(x: f64) -> f64 {
15919    if x == 0.0 { return x; }
15920    let e = ((x.to_bits() >> 52) & 0x7ff) as i32;
15921    if e < 0x3ff - 32 {
15922        feraiseexcept(FE_INEXACT);
15923        if e == 0 { feraiseexcept(FE_UNDERFLOW); }
15924        return x;
15925    }
15926    if x == 1.0 {
15927        feraiseexcept(FE_DIVBYZERO);
15928        return f64::INFINITY;
15929    }
15930    if x == -1.0 {
15931        feraiseexcept(FE_DIVBYZERO);
15932        return f64::NEG_INFINITY;
15933    }
15934    if x.is_nan() { return x; }
15935    let ax = libm::fabs(x);
15936    if ax > 1.0 {
15937        feraiseexcept(FE_INVALID);
15938        return f64::NAN;
15939    }
15940    if ax < 0.5 {
15941        // For small x: use log1p formula with |x| and negate
15942        let r = libm::log1p(2.0 * (ax + ax * ax / (1.0 - ax))) / 2.0;
15943        if x < 0.0 { -r } else { r }
15944    } else {
15945        // For larger x: use log formula with |x| and negate
15946        let r = 0.5 * libm::log((1.0 + ax) / (1.0 - ax));
15947        if x < 0.0 { -r } else { r }
15948    }
15949}
15950
15951#[no_mangle]
15952pub unsafe extern "C" fn cbrt(x: f64) -> f64 {
15953    libm::cbrt(x)
15954}
15955
15956#[no_mangle]
15957pub unsafe extern "C" fn erf(x: f64) -> f64 {
15958    erf_impl(x)
15959}
15960
15961#[no_mangle]
15962pub unsafe extern "C" fn erfc(x: f64) -> f64 {
15963    erfc_impl(x)
15964}
15965
15966#[no_mangle]
15967pub unsafe extern "C" fn lgamma(x: f64) -> f64 {
15968    lgamma_impl(x)
15969}
15970
15971#[no_mangle]
15972pub unsafe extern "C" fn tgamma(x: f64) -> f64 {
15973    tgamma_impl(x)
15974}
15975
15976#[no_mangle]
15977pub unsafe extern "C" fn lround(x: f64) -> core::ffi::c_long {
15978    libm::round(x) as core::ffi::c_long
15979}
15980
15981#[no_mangle]
15982pub unsafe extern "C" fn llround(x: f64) -> i64 {
15983    libm::round(x) as i64
15984}
15985
15986// ============================================================
15987// Complex math functions - using (f64, f64) pairs
15988// ============================================================
15989
15990// Helper: complex number as (real, imag) pair
15991// cabs: magnitude = sqrt(re^2 + im^2)
15992#[no_mangle]
15993pub unsafe extern "C" fn cabs(z: (f64, f64)) -> f64 {
15994    libm::sqrt(z.0 * z.0 + z.1 * z.1)
15995}
15996
15997#[no_mangle]
15998pub unsafe extern "C" fn cabsf(z: (f32, f32)) -> f32 {
15999    libm::sqrtf(z.0 * z.0 + z.1 * z.1)
16000}
16001
16002#[no_mangle]
16003pub unsafe extern "C" fn cabsl(z: (f64, f64)) -> f64 {
16004    cabs(z)
16005}
16006
16007#[no_mangle]
16008pub unsafe extern "C" fn carg(z: (f64, f64)) -> f64 {
16009    libm::atan2(z.1, z.0)
16010}
16011
16012#[no_mangle]
16013pub unsafe extern "C" fn cargf(z: (f32, f32)) -> f32 {
16014    libm::atan2f(z.1, z.0)
16015}
16016
16017#[no_mangle]
16018pub unsafe extern "C" fn cargl(z: (f64, f64)) -> f64 {
16019    carg(z)
16020}
16021
16022#[no_mangle]
16023pub unsafe extern "C" fn cimag(z: (f64, f64)) -> f64 {
16024    z.1
16025}
16026
16027#[no_mangle]
16028pub unsafe extern "C" fn cimagf(z: (f32, f32)) -> f32 {
16029    z.1
16030}
16031
16032#[no_mangle]
16033pub unsafe extern "C" fn cimagl(z: (f64, f64)) -> f64 {
16034    z.1
16035}
16036
16037#[no_mangle]
16038pub unsafe extern "C" fn creal(z: (f64, f64)) -> f64 {
16039    z.0
16040}
16041
16042#[no_mangle]
16043pub unsafe extern "C" fn crealf(z: (f32, f32)) -> f32 {
16044    z.0
16045}
16046
16047#[no_mangle]
16048pub unsafe extern "C" fn creall(z: (f64, f64)) -> f64 {
16049    z.0
16050}
16051
16052#[no_mangle]
16053pub unsafe extern "C" fn conj(z: (f64, f64)) -> (f64, f64) {
16054    (z.0, -z.1)
16055}
16056
16057#[no_mangle]
16058pub unsafe extern "C" fn conjf(z: (f32, f32)) -> (f32, f32) {
16059    (z.0, -z.1)
16060}
16061
16062#[no_mangle]
16063pub unsafe extern "C" fn conjl(z: (f64, f64)) -> (f64, f64) {
16064    conj(z)
16065}
16066
16067#[no_mangle]
16068pub unsafe extern "C" fn cproj(z: (f64, f64)) -> (f64, f64) {
16069    if z.0.is_infinite() || z.1.is_infinite() {
16070        (f64::INFINITY, if z.1.is_sign_positive() { 0.0 } else { -0.0 })
16071    } else {
16072        z
16073    }
16074}
16075
16076#[no_mangle]
16077pub unsafe extern "C" fn cprojf(z: (f32, f32)) -> (f32, f32) {
16078    if z.0.is_infinite() || z.1.is_infinite() {
16079        (f32::INFINITY, if z.1.is_sign_positive() { 0.0 } else { -0.0 })
16080    } else {
16081        z
16082    }
16083}
16084
16085#[no_mangle]
16086pub unsafe extern "C" fn cprojl(z: (f64, f64)) -> (f64, f64) {
16087    cproj(z)
16088}
16089
16090// cexp: e^z = e^(re + i*im) = e^re * (cos(im) + i*sin(im))
16091#[no_mangle]
16092pub unsafe extern "C" fn cexp(z: (f64, f64)) -> (f64, f64) {
16093    let r = libm::exp(z.0);
16094    (r * libm::cos(z.1), r * libm::sin(z.1))
16095}
16096
16097#[no_mangle]
16098pub unsafe extern "C" fn cexpf(z: (f32, f32)) -> (f32, f32) {
16099    let r = libm::expf(z.0);
16100    (r * libm::cosf(z.1), r * libm::sinf(z.1))
16101}
16102
16103#[no_mangle]
16104pub unsafe extern "C" fn cexpl(z: (f64, f64)) -> (f64, f64) {
16105    cexp(z)
16106}
16107
16108// clog: ln(z) = ln|z| + i*arg(z)
16109#[no_mangle]
16110pub unsafe extern "C" fn clog(z: (f64, f64)) -> (f64, f64) {
16111    (libm::log(cabs(z)), carg(z))
16112}
16113
16114#[no_mangle]
16115pub unsafe extern "C" fn clogf(z: (f32, f32)) -> (f32, f32) {
16116    (libm::logf(cabsf(z)), cargf(z))
16117}
16118
16119#[no_mangle]
16120pub unsafe extern "C" fn clogl(z: (f64, f64)) -> (f64, f64) {
16121    clog(z)
16122}
16123
16124// csqrt: sqrt(z) = sqrt((|z|+re)/2) + i*sign(im)*sqrt((|z|-re)/2)
16125#[no_mangle]
16126pub unsafe extern "C" fn csqrt(z: (f64, f64)) -> (f64, f64) {
16127    let r = cabs(z);
16128    let sign = if z.1 < 0.0 { -1.0 } else { 1.0 };
16129    (libm::sqrt((r + z.0) / 2.0), sign * libm::sqrt((r - z.0) / 2.0))
16130}
16131
16132#[no_mangle]
16133pub unsafe extern "C" fn csqrtf(z: (f32, f32)) -> (f32, f32) {
16134    let r = cabsf(z);
16135    let sign = if z.1 < 0.0 { -1.0f32 } else { 1.0f32 };
16136    (libm::sqrtf((r + z.0) / 2.0), sign * libm::sqrtf((r - z.0) / 2.0))
16137}
16138
16139#[no_mangle]
16140pub unsafe extern "C" fn csqrtl(z: (f64, f64)) -> (f64, f64) {
16141    csqrt(z)
16142}
16143
16144// cpow: z^w = e^(w * log(z))
16145#[no_mangle]
16146pub unsafe extern "C" fn cpow(z: (f64, f64), w: (f64, f64)) -> (f64, f64) {
16147    let log_z = clog(z);
16148    let exp_arg = (w.0 * log_z.0 - w.1 * log_z.1, w.0 * log_z.1 + w.1 * log_z.0);
16149    cexp(exp_arg)
16150}
16151
16152#[no_mangle]
16153pub unsafe extern "C" fn cpowf(z: (f32, f32), w: (f32, f32)) -> (f32, f32) {
16154    let log_z = clogf(z);
16155    let exp_arg = (w.0 * log_z.0 - w.1 * log_z.1, w.0 * log_z.1 + w.1 * log_z.0);
16156    cexpf(exp_arg)
16157}
16158
16159#[no_mangle]
16160pub unsafe extern "C" fn cpowl(z: (f64, f64), w: (f64, f64)) -> (f64, f64) {
16161    cpow(z, w)
16162}
16163
16164// ccos: cos(z) = cos(re)*cosh(im) - i*sin(re)*sinh(im)
16165#[no_mangle]
16166pub unsafe extern "C" fn ccos(z: (f64, f64)) -> (f64, f64) {
16167    (libm::cos(z.0) * libm::cosh(z.1), -libm::sin(z.0) * libm::sinh(z.1))
16168}
16169
16170#[no_mangle]
16171pub unsafe extern "C" fn ccosf(z: (f32, f32)) -> (f32, f32) {
16172    (libm::cosf(z.0) * libm::coshf(z.1), -libm::sinf(z.0) * libm::sinhf(z.1))
16173}
16174
16175#[no_mangle]
16176pub unsafe extern "C" fn ccosl(z: (f64, f64)) -> (f64, f64) {
16177    ccos(z)
16178}
16179
16180// csin: sin(z) = sin(re)*cosh(im) + i*cos(re)*sinh(im)
16181#[no_mangle]
16182pub unsafe extern "C" fn csin(z: (f64, f64)) -> (f64, f64) {
16183    (libm::sin(z.0) * libm::cosh(z.1), libm::cos(z.0) * libm::sinh(z.1))
16184}
16185
16186#[no_mangle]
16187pub unsafe extern "C" fn csinf(z: (f32, f32)) -> (f32, f32) {
16188    (libm::sinf(z.0) * libm::coshf(z.1), libm::cosf(z.0) * libm::sinhf(z.1))
16189}
16190
16191#[no_mangle]
16192pub unsafe extern "C" fn csinl(z: (f64, f64)) -> (f64, f64) {
16193    csin(z)
16194}
16195
16196// ctan: tan(z) = sin(2re)/(cos(2re)+cosh(2im)) + i*sinh(2im)/(cos(2re)+cosh(2im))
16197#[no_mangle]
16198pub unsafe extern "C" fn ctan(z: (f64, f64)) -> (f64, f64) {
16199    let d = libm::cos(2.0 * z.0) + libm::cosh(2.0 * z.1);
16200    (libm::sin(2.0 * z.0) / d, libm::sinh(2.0 * z.1) / d)
16201}
16202
16203#[no_mangle]
16204pub unsafe extern "C" fn ctanf(z: (f32, f32)) -> (f32, f32) {
16205    let d = libm::cosf(2.0 * z.0) + libm::coshf(2.0 * z.1);
16206    (libm::sinf(2.0 * z.0) / d, libm::sinhf(2.0 * z.1) / d)
16207}
16208
16209#[no_mangle]
16210pub unsafe extern "C" fn ctanl(z: (f64, f64)) -> (f64, f64) {
16211    ctan(z)
16212}
16213
16214// ccosh: cosh(z) = cosh(re)*cos(im) + i*sinh(re)*sin(im)
16215#[no_mangle]
16216pub unsafe extern "C" fn ccosh(z: (f64, f64)) -> (f64, f64) {
16217    (libm::cosh(z.0) * libm::cos(z.1), libm::sinh(z.0) * libm::sin(z.1))
16218}
16219
16220#[no_mangle]
16221pub unsafe extern "C" fn ccoshf(z: (f32, f32)) -> (f32, f32) {
16222    (libm::coshf(z.0) * libm::cosf(z.1), libm::sinhf(z.0) * libm::sinf(z.1))
16223}
16224
16225#[no_mangle]
16226pub unsafe extern "C" fn ccoshl(z: (f64, f64)) -> (f64, f64) {
16227    ccosh(z)
16228}
16229
16230// csinh: sinh(z) = sinh(re)*cos(im) + i*cosh(re)*sin(im)
16231#[no_mangle]
16232pub unsafe extern "C" fn csinh(z: (f64, f64)) -> (f64, f64) {
16233    (libm::sinh(z.0) * libm::cos(z.1), libm::cosh(z.0) * libm::sin(z.1))
16234}
16235
16236#[no_mangle]
16237pub unsafe extern "C" fn csinhf(z: (f32, f32)) -> (f32, f32) {
16238    (libm::sinhf(z.0) * libm::cosf(z.1), libm::coshf(z.0) * libm::sinf(z.1))
16239}
16240
16241#[no_mangle]
16242pub unsafe extern "C" fn csinhl(z: (f64, f64)) -> (f64, f64) {
16243    csinh(z)
16244}
16245
16246// ctanh: tanh(z) = sinh(2re)/(cosh(2re)+cos(2im)) + i*sin(2im)/(cosh(2re)+cos(2im))
16247#[no_mangle]
16248pub unsafe extern "C" fn ctanh(z: (f64, f64)) -> (f64, f64) {
16249    let d = libm::cosh(2.0 * z.0) + libm::cos(2.0 * z.1);
16250    (libm::sinh(2.0 * z.0) / d, libm::sin(2.0 * z.1) / d)
16251}
16252
16253#[no_mangle]
16254pub unsafe extern "C" fn ctanhf(z: (f32, f32)) -> (f32, f32) {
16255    let d = libm::coshf(2.0 * z.0) + libm::cosf(2.0 * z.1);
16256    (libm::sinhf(2.0 * z.0) / d, libm::sinf(2.0 * z.1) / d)
16257}
16258
16259#[no_mangle]
16260pub unsafe extern "C" fn ctanhl(z: (f64, f64)) -> (f64, f64) {
16261    ctanh(z)
16262}
16263
16264// cacos: acos(z) = pi/2 - asin(z)
16265// asin(z) = -i * log(i*z + sqrt(1 - z^2))
16266#[no_mangle]
16267pub unsafe extern "C" fn cacos(z: (f64, f64)) -> (f64, f64) {
16268    let asin_z = casin(z);
16269    (3.14159265358979323846264338327950288419716939937510582097494459230781640 / 2.0 - asin_z.0, -asin_z.1)
16270}
16271
16272#[no_mangle]
16273pub unsafe extern "C" fn cacosf(z: (f32, f32)) -> (f32, f32) {
16274    let asin_z = casinf(z);
16275    (3.14159265358979323846264338327950288419716939937510582097494459230781640f32 / 2.0 - asin_z.0, -asin_z.1)
16276}
16277
16278#[no_mangle]
16279pub unsafe extern "C" fn cacosl(z: (f64, f64)) -> (f64, f64) {
16280    cacos(z)
16281}
16282
16283// casin: asin(z) = -i * log(i*z + sqrt(1 - z^2))
16284#[no_mangle]
16285pub unsafe extern "C" fn casin(z: (f64, f64)) -> (f64, f64) {
16286    // i*z = (-z.1, z.0)
16287    let iz = (-z.1, z.0);
16288    // 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)
16289    let one_minus_z2 = (1.0 - z.0 * z.0 + z.1 * z.1, -2.0 * z.0 * z.1);
16290    let sqrt_val = csqrt(one_minus_z2);
16291    let arg = clog((iz.0 + sqrt_val.0, iz.1 + sqrt_val.1));
16292    // -i * log(...) = (arg.1, -arg.0)
16293    (arg.1, -arg.0)
16294}
16295
16296#[no_mangle]
16297pub unsafe extern "C" fn casinf(z: (f32, f32)) -> (f32, f32) {
16298    let iz = (-z.1, z.0);
16299    let one_minus_z2 = (1.0 - z.0 * z.0 + z.1 * z.1, -2.0 * z.0 * z.1);
16300    let sqrt_val = csqrtf(one_minus_z2);
16301    let arg = clogf((iz.0 + sqrt_val.0, iz.1 + sqrt_val.1));
16302    (arg.1, -arg.0)
16303}
16304
16305#[no_mangle]
16306pub unsafe extern "C" fn casinl(z: (f64, f64)) -> (f64, f64) {
16307    casin(z)
16308}
16309
16310// catan: atan(z) = (i/2) * log((1 - i*z)/(1 + i*z))
16311#[no_mangle]
16312pub unsafe extern "C" fn catan(z: (f64, f64)) -> (f64, f64) {
16313    // i*z = (-z.1, z.0)
16314    // 1 - i*z = (1 + z.1, -z.0)
16315    // 1 + i*z = (1 - z.1, z.0)
16316    let num = (1.0 + z.1, -z.0);
16317    let den = (1.0 - z.1, z.0);
16318    let ratio = cdiv(num, den);
16319    let log_ratio = clog(ratio);
16320    // (i/2) * log = (-log.1/2, log.0/2)
16321    (-log_ratio.1 / 2.0, log_ratio.0 / 2.0)
16322}
16323
16324#[no_mangle]
16325pub unsafe extern "C" fn catanf(z: (f32, f32)) -> (f32, f32) {
16326    let num = (1.0 + z.1, -z.0);
16327    let den = (1.0 - z.1, z.0);
16328    let ratio = cdivf(num, den);
16329    let log_ratio = clogf(ratio);
16330    (-log_ratio.1 / 2.0, log_ratio.0 / 2.0)
16331}
16332
16333#[no_mangle]
16334pub unsafe extern "C" fn catanl(z: (f64, f64)) -> (f64, f64) {
16335    catan(z)
16336}
16337
16338// Helper: complex division
16339fn cdiv(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
16340    let d = b.0 * b.0 + b.1 * b.1;
16341    ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
16342}
16343
16344fn cdivf(a: (f32, f32), b: (f32, f32)) -> (f32, f32) {
16345    let d = b.0 * b.0 + b.1 * b.1;
16346    ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
16347}
16348
16349// cacosh: acosh(z) = log(z + sqrt(z^2 - 1))
16350#[no_mangle]
16351pub unsafe extern "C" fn cacosh(z: (f64, f64)) -> (f64, f64) {
16352    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16353    let z2_minus_1 = (z2.0 - 1.0, z2.1);
16354    let sqrt_val = csqrt(z2_minus_1);
16355    clog((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16356}
16357
16358#[no_mangle]
16359pub unsafe extern "C" fn cacoshf(z: (f32, f32)) -> (f32, f32) {
16360    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16361    let z2_minus_1 = (z2.0 - 1.0, z2.1);
16362    let sqrt_val = csqrtf(z2_minus_1);
16363    clogf((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16364}
16365
16366#[no_mangle]
16367pub unsafe extern "C" fn cacoshl(z: (f64, f64)) -> (f64, f64) {
16368    cacosh(z)
16369}
16370
16371// casinh: asinh(z) = log(z + sqrt(z^2 + 1))
16372#[no_mangle]
16373pub unsafe extern "C" fn casinh(z: (f64, f64)) -> (f64, f64) {
16374    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16375    let z2_plus_1 = (z2.0 + 1.0, z2.1);
16376    let sqrt_val = csqrt(z2_plus_1);
16377    clog((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16378}
16379
16380#[no_mangle]
16381pub unsafe extern "C" fn casinhf(z: (f32, f32)) -> (f32, f32) {
16382    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16383    let z2_plus_1 = (z2.0 + 1.0, z2.1);
16384    let sqrt_val = csqrtf(z2_plus_1);
16385    clogf((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16386}
16387
16388#[no_mangle]
16389pub unsafe extern "C" fn casinhl(z: (f64, f64)) -> (f64, f64) {
16390    casinh(z)
16391}
16392
16393// catanh: atanh(z) = (1/2) * log((1+z)/(1-z))
16394#[no_mangle]
16395pub unsafe extern "C" fn catanh(z: (f64, f64)) -> (f64, f64) {
16396    let num = (1.0 + z.0, z.1);
16397    let den = (1.0 - z.0, -z.1);
16398    let ratio = cdiv(num, den);
16399    let log_ratio = clog(ratio);
16400    (log_ratio.0 / 2.0, log_ratio.1 / 2.0)
16401}
16402
16403#[no_mangle]
16404pub unsafe extern "C" fn catanhf(z: (f32, f32)) -> (f32, f32) {
16405    let num = (1.0 + z.0, z.1);
16406    let den = (1.0 - z.0, -z.1);
16407    let ratio = cdivf(num, den);
16408    let log_ratio = clogf(ratio);
16409    (log_ratio.0 / 2.0, log_ratio.1 / 2.0)
16410}
16411
16412#[no_mangle]
16413pub unsafe extern "C" fn catanhl(z: (f64, f64)) -> (f64, f64) {
16414    catanh(z)
16415}
16416
16417// ============================================================
16418// Float math functions (f32 versions)
16419// ============================================================
16420
16421#[inline(never)]
16422#[no_mangle]
16423pub unsafe extern "C" fn fmaxf(x: f32, y: f32) -> f32 {
16424    fmaxf_impl(x, y)
16425}
16426
16427#[no_mangle]
16428pub unsafe extern "C" fn fdimf(x: f32, y: f32) -> f32 {
16429    if x.is_nan() || y.is_nan() {
16430        return f32::NAN;
16431    }
16432    if x > y { x - y } else { 0.0 }
16433}
16434
16435#[no_mangle]
16436pub unsafe extern "C" fn fmaf(x: f32, y: f32, z: f32) -> f32 {
16437    if (x.is_infinite() && y == 0.0) || (y.is_infinite() && x == 0.0) {
16438        feraiseexcept(FE_INVALID);
16439        return f32::NAN;
16440    }
16441    if x.is_nan() || y.is_nan() || z.is_nan() {
16442        return f32::NAN;
16443    }
16444    let r = libm::fmaf(x, y, z);
16445    if r.is_nan() {
16446        feraiseexcept(FE_INVALID);
16447    }
16448    r
16449}
16450
16451#[no_mangle]
16452pub unsafe extern "C" fn ilogbf(x: f32) -> i32 {
16453    if x.is_nan() {
16454        feraiseexcept(FE_INVALID);
16455        return -0x7fffffff - 1;
16456    }
16457    if x == 0.0 || x.is_infinite() {
16458        feraiseexcept(FE_INVALID);
16459        return if x == 0.0 { -0x7fffffff - 1 } else { 0x7fffffff };
16460    }
16461    let bits = x.to_bits();
16462    let exp = ((bits >> 23) & 0xff) as i32;
16463    if exp == 0 {
16464        let mut v = bits & 0x7fffff;
16465        let mut e = -126;
16466        while v < (1u32 << 23) { v <<= 1; e -= 1; }
16467        e
16468    } else {
16469        exp - 127
16470    }
16471}
16472
16473#[no_mangle]
16474pub unsafe extern "C" fn logbf(x: f32) -> f32 {
16475    if x.is_nan() { return x; }
16476    if x == 0.0 { return __math_divzerof(1); }
16477    let bits = x.to_bits();
16478    let exp = ((bits >> 23) & 0xff) as i32;
16479    if exp == 0 {
16480        let mut v = bits & 0x7fffff;
16481        let mut e = -126i32;
16482        while v < (1u32 << 23) { v <<= 1; e -= 1; }
16483        e as f32
16484    } else if exp == 0xff {
16485        x * x
16486    } else {
16487        (exp - 127) as f32
16488    }
16489}
16490
16491#[no_mangle]
16492pub unsafe extern "C" fn nearbyintf(x: f32) -> f32 {
16493    let had_inexact = fetestexcept(FE_INEXACT) & FE_INEXACT != 0;
16494    let r = libm::rintf(x);
16495    if !had_inexact {
16496        feclearexcept(FE_INEXACT);
16497    }
16498    r
16499}
16500
16501#[no_mangle]
16502pub unsafe extern "C" fn nextafterf(x: f32, y: f32) -> f32 {
16503    if x.is_nan() || y.is_nan() { return x + y; }
16504    if x == 0.0 && y == 0.0 { return y; }
16505    if x == y { return x; }
16506    let r = libm::nextafterf(x, y);
16507    if r.is_infinite() && x.is_finite() {
16508        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
16509    } else if r != x {
16510        let bits = r.to_bits();
16511        let is_subnormal = (bits & 0x7f800000) == 0 && (bits & 0x7fffff) != 0;
16512        if r == 0.0 || is_subnormal {
16513            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16514        }
16515    }
16516    r
16517}
16518
16519#[no_mangle]
16520#[cfg(target_arch = "x86_64")]
16521pub unsafe extern "C" fn nexttowardf(x: f32, y: f64) -> f32 {
16522    if y.is_nan() { return (x as f64 + y) as f32; }
16523    if x == 0.0 && y == 0.0 {
16524        return if y.is_sign_negative() { -0.0 } else { 0.0 };
16525    }
16526    if (x as f64) == y { return x; }
16527    nextafterf(x, if y > x as f64 { f32::INFINITY } else { f32::NEG_INFINITY })
16528}
16529
16530#[no_mangle]
16531#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
16532pub unsafe extern "C" fn nexttowardf(x: f32, y: f128) -> f32 {
16533    if y.is_nan() { return (x as f128 + y) as f32; }
16534    if (x as f128) == y { return x; }
16535    nextafterf(x, if y > x as f128 { f32::INFINITY } else { f32::NEG_INFINITY })
16536}
16537
16538#[no_mangle]
16539pub unsafe extern "C" fn remainderf(x: f32, y: f32) -> f32 {
16540    if x.is_nan() || y.is_nan() { return x + y; }
16541    if y == 0.0 || x.is_infinite() { return __math_invalidf(x); }
16542    libm::remainderf(x, y)
16543}
16544
16545#[no_mangle]
16546pub unsafe extern "C" fn remquof(x: f32, y: f32, quo: *mut i32) -> f32 {
16547    if x.is_nan() || y.is_nan() {
16548        if !quo.is_null() { *quo = 0; }
16549        return x + y;
16550    }
16551    if y == 0.0 || x.is_infinite() {
16552        if !quo.is_null() { *quo = 0; }
16553        return __math_invalidf(x);
16554    }
16555    let (r, q) = libm::remquof(x, y);
16556    if !quo.is_null() { *quo = q; }
16557    r
16558}
16559
16560#[no_mangle]
16561pub unsafe extern "C" fn exp2f(x: f32) -> f32 {
16562    if x == f32::INFINITY { return f32::INFINITY; }
16563    if x == f32::NEG_INFINITY { return 0.0; }
16564    if x.is_nan() { return f32::NAN; }
16565    let r = libm::exp2f(x);
16566    if r.is_infinite() && x.is_finite() {
16567        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
16568    } else if r == 0.0 && x < -149.0 {
16569        feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16570    } else if r != 0.0 && x != libm::truncf(x) {
16571        let bits = r.to_bits();
16572        if (bits & 0x7f800000) == 0 {
16573            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16574        }
16575    }
16576    r
16577}
16578
16579#[no_mangle]
16580pub unsafe extern "C" fn expm1f(x: f32) -> f32 {
16581    libm::expm1f(x)
16582}
16583
16584#[no_mangle]
16585pub unsafe extern "C" fn log1pf(x: f32) -> f32 {
16586    if x == -1.0 {
16587        feraiseexcept(FE_DIVBYZERO);
16588        return f32::NEG_INFINITY;
16589    }
16590    libm::log1pf(x)
16591}
16592
16593#[no_mangle]
16594pub unsafe extern "C" fn acoshf(x: f32) -> f32 {
16595    if x < 1.0 {
16596        feraiseexcept(FE_INVALID);
16597        return f32::NAN;
16598    }
16599    libm::acoshf(x)
16600}
16601
16602#[no_mangle]
16603pub unsafe extern "C" fn asinhf(x: f32) -> f32 {
16604    if x == 0.0 { return x; }
16605    libm::asinhf(x)
16606}
16607
16608#[no_mangle]
16609pub unsafe extern "C" fn atanhf(x: f32) -> f32 {
16610    if x == 0.0 { return x; }
16611    let e = ((x.to_bits() >> 23) & 0xff) as i32;
16612    if e < 0x7f - 32 {
16613        feraiseexcept(FE_INEXACT);
16614        if e == 0 { feraiseexcept(FE_UNDERFLOW); }
16615        return x;
16616    }
16617    if x == 1.0 {
16618        feraiseexcept(FE_DIVBYZERO);
16619        return f32::INFINITY;
16620    }
16621    if x == -1.0 {
16622        feraiseexcept(FE_DIVBYZERO);
16623        return f32::NEG_INFINITY;
16624    }
16625    if x.is_nan() { return x; }
16626    let ax = libm::fabsf(x);
16627    if ax > 1.0 {
16628        feraiseexcept(FE_INVALID);
16629        return f32::NAN;
16630    }
16631    if ax < 0.5 {
16632        let r = libm::log1pf(2.0 * (ax + ax * ax / (1.0 - ax))) / 2.0;
16633        if x < 0.0 { -r } else { r }
16634    } else {
16635        let r = 0.5 * libm::logf((1.0 + ax) / (1.0 - ax));
16636        if x < 0.0 { -r } else { r }
16637    }
16638}
16639
16640#[no_mangle]
16641pub unsafe extern "C" fn cbrtf(x: f32) -> f32 {
16642    libm::cbrtf(x)
16643}
16644
16645#[no_mangle]
16646pub unsafe extern "C" fn erff(x: f32) -> f32 {
16647    libm::erff(x)
16648}
16649
16650#[no_mangle]
16651pub unsafe extern "C" fn erfcf(x: f32) -> f32 {
16652    libm::erfcf(x)
16653}
16654
16655#[no_mangle]
16656pub unsafe extern "C" fn lgammaf(x: f32) -> f32 {
16657    if x.is_nan() {
16658        crate::set_signgam(1);
16659        return x;
16660    }
16661    if x == 0.0 {
16662        crate::set_signgam(if x.is_sign_negative() { -1 } else { 1 });
16663        feraiseexcept(FE_DIVBYZERO);
16664        return f32::INFINITY;
16665    }
16666    let (r, sign) = libm::lgammaf_r(x);
16667    crate::set_signgam(sign);
16668    r
16669}
16670
16671#[no_mangle]
16672pub unsafe extern "C" fn tgammaf(x: f32) -> f32 {
16673    if x.is_nan() { return x; }
16674    if x == 0.0 {
16675        feraiseexcept(FE_DIVBYZERO);
16676        return if x.is_sign_negative() { f32::NEG_INFINITY } else { f32::INFINITY };
16677    }
16678    if x.is_infinite() {
16679        return if x.is_sign_negative() { __math_invalidf(x) } else { f32::INFINITY };
16680    }
16681    if x < 0.0 && x == libm::floorf(x) {
16682        feraiseexcept(FE_INVALID);
16683        return f32::NAN;
16684    }
16685    libm::tgammaf(x)
16686}
16687
16688#[no_mangle]
16689pub unsafe extern "C" fn lroundf(x: f32) -> core::ffi::c_long {
16690    libm::roundf(x) as core::ffi::c_long
16691}
16692
16693#[no_mangle]
16694pub unsafe extern "C" fn llroundf(x: f32) -> i64 {
16695    libm::roundf(x) as i64
16696}
16697
16698// ============================================================
16699// Wide char functions
16700// ============================================================
16701
16702#[no_mangle]
16703pub unsafe extern "C" fn wcscasecmp(s1: *const u32, s2: *const u32) -> i32 {
16704    let mut i = 0;
16705    loop {
16706        let c1 = *s1.add(i);
16707        let c2 = *s2.add(i);
16708        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16709        let l1 = if c1 >= 'A' as u32 && c1 <= 'Z' as u32 { c1 + 32 } else { c1 };
16710        let l2 = if c2 >= 'A' as u32 && c2 <= 'Z' as u32 { c2 + 32 } else { c2 };
16711        if l1 != l2 { return (l1 as i32) - (l2 as i32); }
16712        i += 1;
16713    }
16714}
16715
16716#[no_mangle]
16717pub unsafe extern "C" fn wcscasecmp_l(s1: *const u32, s2: *const u32, _loc: *mut core::ffi::c_void) -> i32 {
16718    wcscasecmp(s1, s2)
16719}
16720
16721#[no_mangle]
16722pub unsafe extern "C" fn wcsncasecmp(s1: *const u32, s2: *const u32, n: usize) -> i32 {
16723    let mut i = 0;
16724    while i < n {
16725        let c1 = *s1.add(i);
16726        let c2 = *s2.add(i);
16727        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16728        let l1 = if c1 >= 'A' as u32 && c1 <= 'Z' as u32 { c1 + 32 } else { c1 };
16729        let l2 = if c2 >= 'A' as u32 && c2 <= 'Z' as u32 { c2 + 32 } else { c2 };
16730        if l1 != l2 { return (l1 as i32) - (l2 as i32); }
16731        i += 1;
16732    }
16733    0
16734}
16735
16736#[no_mangle]
16737pub unsafe extern "C" fn wcsncasecmp_l(s1: *const u32, s2: *const u32, n: usize, _loc: *mut core::ffi::c_void) -> i32 {
16738    wcsncasecmp(s1, s2, n)
16739}
16740
16741#[no_mangle]
16742pub unsafe extern "C" fn wcscoll(s1: *const u32, s2: *const u32) -> i32 {
16743    // musl's C locale compares wide characters by codepoint.
16744    let mut i = 0;
16745    loop {
16746        let c1 = *s1.add(i);
16747        let c2 = *s2.add(i);
16748        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16749        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
16750        i += 1;
16751    }
16752}
16753
16754unsafe fn wc_in_set(c: u32, set: *const u32) -> bool {
16755    let mut i = 0usize;
16756    while *set.add(i) != 0 {
16757        if *set.add(i) == c { return true; }
16758        i += 1;
16759    }
16760    false
16761}
16762
16763#[no_mangle]
16764pub unsafe extern "C" fn wcstok(s: *mut u32, sep: *const u32, p: *mut *mut u32) -> *mut u32 {
16765    if sep.is_null() || p.is_null() { return core::ptr::null_mut(); }
16766    let mut src = if s.is_null() {
16767        if (*p).is_null() { return core::ptr::null_mut(); }
16768        *p
16769    } else { s };
16770    while *src != 0 && wc_in_set(*src, sep) { src = src.add(1); }
16771    if *src == 0 { return core::ptr::null_mut(); }
16772    let start = src;
16773    while *src != 0 && !wc_in_set(*src, sep) { src = src.add(1); }
16774    if *src != 0 {
16775        *src = 0;
16776        *p = src.add(1);
16777    } else {
16778        *p = src;
16779    }
16780    start
16781}
16782
16783#[no_mangle]
16784pub unsafe extern "C" fn wcswcs(haystack: *const u32, needle: *const u32) -> *mut u32 {
16785    if *needle == 0 { return haystack as *mut u32; }
16786    let mut i = 0;
16787    while *haystack.add(i) != 0 {
16788        let mut j = 0;
16789        while *needle.add(j) != 0 && *haystack.add(i + j) == *needle.add(j) {
16790            j += 1;
16791        }
16792        if *needle.add(j) == 0 { return haystack.add(i) as *mut u32; }
16793        i += 1;
16794    }
16795    core::ptr::null_mut()
16796}
16797
16798#[no_mangle]
16799pub unsafe extern "C" fn wcswidth(s: *const u32, n: usize) -> i32 {
16800    let mut width = 0i32;
16801    let mut i = 0usize;
16802    while i < n {
16803        let c = *s.add(i);
16804        if c == 0 { break; }
16805        let w = wcwidth(c);
16806        if w < 0 { return w; }
16807        width += w;
16808        i += 1;
16809    }
16810    width
16811}
16812
16813#[no_mangle]
16814pub unsafe extern "C" fn wcsftime(s: *mut u32, maxsize: usize, fmt: *const u32, tm: *const c_void) -> usize {
16815    if s.is_null() || fmt.is_null() || maxsize == 0 { return 0; }
16816    // Convert the wide format string to multibyte, let strftime do the work,
16817    // then convert the result back. Both buffers scale with the inputs.
16818    let wlen = wcslen(fmt as *const wchar_t);
16819    let cfmt_cap = match wlen.checked_mul(4).and_then(|v| v.checked_add(1)) {
16820        Some(v) => v,
16821        None => return 0,
16822    };
16823    let cfmt = crate::malloc(cfmt_cap) as *mut u8;
16824    if cfmt.is_null() { ERRNO!() = ENOMEM; return 0; }
16825    let mut o = 0usize;
16826    let mut i = 0usize;
16827    let mut st: c_uint = 0;
16828    while *fmt.add(i) != 0 {
16829        let n = wcrtomb(
16830            cfmt.add(o) as *mut c_char,
16831            *fmt.add(i) as c_int,
16832            &mut st as *mut c_uint,
16833        );
16834        if n == !0usize || o + n >= cfmt_cap {
16835            crate::free(cfmt as *mut c_void);
16836            return 0;
16837        }
16838        o += n;
16839        i += 1;
16840    }
16841    *cfmt.add(o) = 0;
16842    let out_cap = match maxsize.checked_mul(4).and_then(|v| v.checked_add(1)) {
16843        Some(v) => v,
16844        None => { crate::free(cfmt as *mut c_void); return 0; }
16845    };
16846    let out = crate::malloc(out_cap) as *mut u8;
16847    if out.is_null() {
16848        crate::free(cfmt as *mut c_void);
16849        ERRNO!() = ENOMEM;
16850        return 0;
16851    }
16852    let n = strftime(out as *mut c_char, out_cap, cfmt as *const c_char, tm as *const tm);
16853    crate::free(cfmt as *mut c_void);
16854    if n == 0 {
16855        crate::free(out as *mut c_void);
16856        return 0;
16857    }
16858    let mut ws = 0usize;
16859    let mut p = 0usize;
16860    while p < n && ws + 1 < maxsize {
16861        let mut wc: c_int = 0;
16862        let mut st2: c_uint = 0;
16863        let r = mbrtowc(&mut wc, out.add(p) as *const c_char, n - p, &mut st2);
16864        if r == !0usize {
16865            crate::free(out as *mut c_void);
16866            return 0;
16867        }
16868        if r == 0 || r == !1usize { break; }
16869        *s.add(ws) = wc as u32;
16870        ws += 1;
16871        p += r;
16872    }
16873    *s.add(ws) = 0;
16874    crate::free(out as *mut c_void);
16875    ws
16876}
16877
16878#[no_mangle]
16879pub unsafe extern "C" fn mbsnrtowcs(
16880    dst: *mut u32,
16881    src: *mut *const u8,
16882    nms: usize,
16883    len: usize,
16884    st: *mut core::ffi::c_void,
16885) -> usize {
16886    if src.is_null() { return 0; }
16887    let mut s = *src;
16888    if s.is_null() { return 0; }
16889    let state = st as *mut c_uint;
16890    let limit = if dst.is_null() { usize::MAX } else { len };
16891    let mut count = 0usize;
16892    let mut n = nms;
16893    while count < limit && n > 0 {
16894        let c = *s;
16895        if c == 0 {
16896            if !dst.is_null() {
16897                if count < len { *dst.add(count) = 0; }
16898                *src = core::ptr::null();
16899            }
16900            return count;
16901        }
16902        let mut wc: c_int = 0;
16903        let r = mbrtowc(&mut wc, s as *const c_char, n, state);
16904        if r == !0usize {
16905            *src = s;
16906            return !0usize;
16907        }
16908        if r == !1usize { break; }
16909        if !dst.is_null() { *dst.add(count) = wc as u32; }
16910        count += 1;
16911        s = s.add(r);
16912        n -= r;
16913    }
16914    *src = s;
16915    count
16916}
16917
16918#[no_mangle]
16919pub unsafe extern "C" fn wcsnrtombs(dst: *mut u8, src: *mut *const u32, nwc: usize, len: usize, _st: *mut core::ffi::c_void) -> usize {
16920    // Port of musl's wcsnrtombs: nwc counts wide characters, len counts
16921    // output bytes, and a converted NUL terminates the source pointer.
16922    let mut ws = *src;
16923    let mut wn = nwc;
16924    let mut cnt = 0usize;
16925    let mut n = len;
16926    let mut d = dst;
16927    while !ws.is_null() && wn > 0 {
16928        let c = *ws;
16929        let mut tmp = [0u8; 8];
16930        let mut state: c_uint = 0;
16931        let l = wcrtomb(tmp.as_mut_ptr() as *mut c_char, c as c_int, &mut state);
16932        if l == !0usize {
16933            return !0usize;
16934        }
16935        if !d.is_null() {
16936            if l > n {
16937                break;
16938            }
16939            core::ptr::copy_nonoverlapping(tmp.as_ptr(), d, l);
16940            d = d.add(l);
16941            n -= l;
16942        }
16943        if c == 0 {
16944            ws = core::ptr::null();
16945            break;
16946        }
16947        ws = ws.add(1);
16948        wn -= 1;
16949        cnt += l;
16950    }
16951    if !dst.is_null() {
16952        *src = ws;
16953    }
16954    cnt
16955}
16956
16957// ============================================================
16958// Thread sync functions (C11 threads)
16959// ============================================================
16960
16961
16962// C11 thread types
16963pub type thrd_start_t = Option<unsafe extern "C" fn(arg: *mut core::ffi::c_void) -> i32>;
16964
16965// C11 threads: thin wrappers around the pthread implementation.
16966#[no_mangle]
16967pub unsafe extern "C" fn thrd_create(thr: *mut usize, func: thrd_start_t, arg: *mut core::ffi::c_void) -> i32 {
16968    let mut thread: u64 = 0;
16969    let r = pthread_create(&mut thread, core::ptr::null(), core::mem::transmute(func), arg);
16970    if r == 0 {
16971        *thr = thread as usize;
16972        0 // thrd_success
16973    } else {
16974        -1 // thrd_nomem
16975    }
16976}
16977
16978#[no_mangle]
16979pub unsafe extern "C" fn thrd_join(thr: usize, res: *mut i32) -> i32 {
16980    let mut retval: *mut core::ffi::c_void = core::ptr::null_mut();
16981    let r = pthread_join(thr as u64, &mut retval);
16982    if r == 0 {
16983        if !res.is_null() { *res = retval as i32; }
16984        0
16985    } else {
16986        -1
16987    }
16988}
16989
16990#[no_mangle]
16991pub unsafe extern "C" fn thrd_exit(res: i32) {
16992    pthread_exit(res as *mut core::ffi::c_void);
16993}
16994
16995#[no_mangle]
16996pub unsafe extern "C" fn thrd_detach(thr: usize) -> i32 {
16997    let r = pthread_detach(thr as u64);
16998    if r == 0 { 0 } else { -1 }
16999}
17000
17001#[no_mangle]
17002pub unsafe extern "C" fn thrd_current() -> usize {
17003    pthread_self() as usize
17004}
17005
17006#[no_mangle]
17007pub unsafe extern "C" fn thrd_equal(thr1: usize, thr2: usize) -> i32 {
17008    (thr1 == thr2) as i32
17009}
17010
17011#[no_mangle]
17012pub unsafe extern "C" fn thrd_sleep(duration: *const core::ffi::c_void, remaining: *mut core::ffi::c_void) -> i32 {
17013    nanosleep(duration as *const timespec, remaining as *mut timespec)
17014}
17015
17016#[no_mangle]
17017pub unsafe extern "C" fn thrd_yield() {
17018    sched_yield();
17019}
17020
17021// Mutex
17022#[no_mangle]
17023pub unsafe extern "C" fn mtx_init(mtx: *mut usize, _mtx_type: i32) -> i32 {
17024    let r = pthread_mutex_init(mtx as *mut pthread_mutex_t, core::ptr::null());
17025    if r == 0 { 0 } else { -1 }
17026}
17027
17028#[no_mangle]
17029pub unsafe extern "C" fn mtx_lock(mtx: *mut usize) -> i32 {
17030    let r = pthread_mutex_lock(mtx as *mut pthread_mutex_t);
17031    if r == 0 { 0 } else { -1 }
17032}
17033
17034#[no_mangle]
17035pub unsafe extern "C" fn mtx_trylock(mtx: *mut usize) -> i32 {
17036    let r = pthread_mutex_trylock(mtx as *mut pthread_mutex_t);
17037    if r == 0 { 0 } else { -1 }
17038}
17039
17040#[no_mangle]
17041pub unsafe extern "C" fn mtx_unlock(mtx: *mut usize) -> i32 {
17042    let r = pthread_mutex_unlock(mtx as *mut pthread_mutex_t);
17043    if r == 0 { 0 } else { -1 }
17044}
17045
17046#[no_mangle]
17047pub unsafe extern "C" fn mtx_destroy(mtx: *mut usize) {
17048    pthread_mutex_destroy(mtx as *mut pthread_mutex_t);
17049}
17050
17051#[no_mangle]
17052pub unsafe extern "C" fn mtx_timedlock(mtx: *mut usize, ts: *const core::ffi::c_void) -> i32 {
17053    let r = pthread_mutex_timedlock(mtx as *mut pthread_mutex_t, ts as *const timespec);
17054    if r == 0 { 0 } else { -1 }
17055}
17056
17057// Condition variable
17058#[no_mangle]
17059pub unsafe extern "C" fn cnd_init(cnd: *mut usize) -> i32 {
17060    let r = pthread_cond_init(cnd as *mut pthread_cond_t, core::ptr::null());
17061    if r == 0 { 0 } else { -1 }
17062}
17063
17064#[no_mangle]
17065pub unsafe extern "C" fn cnd_signal(cnd: *mut usize) -> i32 {
17066    let r = pthread_cond_signal(cnd as *mut pthread_cond_t);
17067    if r == 0 { 0 } else { -1 }
17068}
17069
17070#[no_mangle]
17071pub unsafe extern "C" fn cnd_broadcast(cnd: *mut usize) -> i32 {
17072    let r = pthread_cond_broadcast(cnd as *mut pthread_cond_t);
17073    if r == 0 { 0 } else { -1 }
17074}
17075
17076#[no_mangle]
17077pub unsafe extern "C" fn cnd_wait(cnd: *mut usize, mtx: *mut usize) -> i32 {
17078    let r = pthread_cond_wait(cnd as *mut pthread_cond_t, mtx as *mut pthread_mutex_t);
17079    if r == 0 { 0 } else { -1 }
17080}
17081
17082#[no_mangle]
17083pub unsafe extern "C" fn cnd_timedwait(cnd: *mut usize, mtx: *mut usize, ts: *const core::ffi::c_void) -> i32 {
17084    let r = pthread_cond_timedwait(cnd as *mut pthread_cond_t, mtx as *mut pthread_mutex_t, ts as *const timespec);
17085    if r == 0 { 0 } else { -1 }
17086}
17087
17088#[no_mangle]
17089pub unsafe extern "C" fn cnd_destroy(cnd: *mut usize) {
17090    pthread_cond_destroy(cnd as *mut pthread_cond_t);
17091}
17092
17093// Thread-specific storage
17094#[no_mangle]
17095pub unsafe extern "C" fn tss_create(key: *mut u32, dtor: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>) -> i32 {
17096    let r = pthread_key_create(key, dtor);
17097    if r == 0 { 0 } else { -1 }
17098}
17099
17100#[no_mangle]
17101pub unsafe extern "C" fn tss_delete(key: u32) {
17102    pthread_key_delete(key);
17103}
17104
17105#[no_mangle]
17106pub unsafe extern "C" fn tss_set(key: u32, val: *mut core::ffi::c_void) -> i32 {
17107    let r = pthread_setspecific(key, val);
17108    if r == 0 { 0 } else { -1 }
17109}
17110
17111#[no_mangle]
17112pub unsafe extern "C" fn tss_get(key: u32) -> *mut core::ffi::c_void {
17113    pthread_getspecific(key)
17114}
17115
17116// call_once
17117#[no_mangle]
17118pub unsafe extern "C" fn call_once(flag: *mut u32, func: Option<unsafe extern "C" fn()>) {
17119    if flag.is_null() { return; }
17120    let state = &*(flag as *const AtomicU32);
17121    if state.load(Ordering::Acquire) == 2 { return; }
17122    if state.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).is_ok() {
17123        if let Some(f) = func { f(); }
17124        state.store(2, Ordering::Release);
17125    } else {
17126        while state.load(Ordering::Acquire) != 2 {
17127            core::hint::spin_loop();
17128        }
17129    }
17130}
17131
17132// ============================================================
17133// Network functions
17134// ============================================================
17135
17136// accept4 - Linux-specific extension
17137#[no_mangle]
17138pub unsafe extern "C" fn accept4(fd: i32, addr: *mut core::ffi::c_void, addrlen: *mut u32, flags: i32) -> i32 {
17139    syscall_ret(<Arch as Syscalls>::syscall4(SYS_ACCEPT4, fd as i64, addr as i64, addrlen as i64, flags as i64)) as i32
17140}
17141
17142// getifaddrs / freeifaddrs
17143// ============================================================
17144// epoll/eventfd/signalfd/timerfd
17145// ============================================================
17146
17147#[no_mangle]
17148pub unsafe extern "C" fn epoll_create(size: i32) -> i32 {
17149    #[cfg(target_arch = "x86_64")]
17150    { syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE, size as i64)) as i32 }
17151    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
17152    {
17153        if size < 1 {
17154            ERRNO!() = EINVAL;
17155            return -1;
17156        }
17157        syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE1, 0)) as i32
17158    }
17159}
17160
17161#[no_mangle]
17162pub unsafe extern "C" fn epoll_create1(flags: i32) -> i32 {
17163    syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE1, flags as i64)) as i32
17164}
17165
17166#[no_mangle]
17167pub unsafe extern "C" fn epoll_ctl(epfd: i32, op: i32, fd: i32, event: *mut core::ffi::c_void) -> i32 {
17168    syscall_ret(<Arch as Syscalls>::syscall4(SYS_EPOLL_CTL, epfd as i64, op as i64, fd as i64, event as i64)) as i32
17169}
17170
17171#[no_mangle]
17172pub unsafe extern "C" fn epoll_wait(epfd: i32, events: *mut core::ffi::c_void, maxevents: i32, timeout: i32) -> i32 {
17173    #[cfg(target_arch = "x86_64")]
17174    {
17175        syscall_ret(<Arch as Syscalls>::syscall4(
17176            SYS_EPOLL_WAIT,
17177            epfd as i64,
17178            events as i64,
17179            maxevents as i64,
17180            timeout as i64,
17181        )) as i32
17182    }
17183    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
17184    {
17185        epoll_pwait(epfd, events, maxevents, timeout, core::ptr::null())
17186    }
17187}
17188
17189#[no_mangle]
17190pub unsafe extern "C" fn epoll_pwait(
17191    epfd: i32,
17192    events: *mut core::ffi::c_void,
17193    maxevents: i32,
17194    timeout: i32,
17195    sigmask: *const u64,
17196) -> i32 {
17197    syscall_ret(<Arch as Syscalls>::syscall6(
17198        SYS_EPOLL_PWAIT,
17199        epfd as i64,
17200        events as i64,
17201        maxevents as i64,
17202        timeout as i64,
17203        sigmask as i64,
17204        8,
17205    )) as i32
17206}
17207
17208#[no_mangle]
17209pub unsafe extern "C" fn eventfd(initval: u32, flags: i32) -> i32 {
17210    syscall_ret(<Arch as Syscalls>::syscall2(SYS_EVENTFD2, initval as i64, flags as i64)) as i32
17211}
17212
17213#[no_mangle]
17214pub unsafe extern "C" fn eventfd_read(fd: i32, value: *mut u64) -> i32 {
17215    let n = crate::read(fd, value as *mut core::ffi::c_void, 8);
17216    if n == 8 { 0 } else { -1 }
17217}
17218
17219#[no_mangle]
17220pub unsafe extern "C" fn eventfd_write(fd: i32, value: u64) -> i32 {
17221    let n = crate::write(fd, &value as *const u64 as *const core::ffi::c_void, 8);
17222    if n == 8 { 0 } else { -1 }
17223}
17224
17225#[no_mangle]
17226pub unsafe extern "C" fn signalfd(fd: i32, mask: *const u64, flags: i32) -> i32 {
17227    syscall_ret(<Arch as Syscalls>::syscall4(SYS_SIGNALFD4, fd as i64, mask as i64, 8, flags as i64)) as i32
17228}
17229
17230#[no_mangle]
17231pub unsafe extern "C" fn timerfd_create(clockid: i32, flags: i32) -> i32 {
17232    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMERFD_CREATE, clockid as i64, flags as i64)) as i32
17233}
17234
17235#[no_mangle]
17236pub 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 {
17237    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
17238}
17239
17240#[no_mangle]
17241pub unsafe extern "C" fn timerfd_gettime(fd: i32, curr_value: *mut core::ffi::c_void) -> i32 {
17242    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMERFD_GETTIME, fd as i64, curr_value as i64)) as i32
17243}
17244
17245// ============================================================
17246// System functions
17247// ============================================================
17248
17249#[no_mangle]
17250pub unsafe extern "C" fn prctl(option: i32, mut args: ...) -> i32 {
17251    let a1 = args.next_arg::<i64>();
17252    let a2 = args.next_arg::<i64>();
17253    let a3 = args.next_arg::<i64>();
17254    let a4 = args.next_arg::<i64>();
17255    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PRCTL, option as i64, a1, a2, a3, a4)) as i32
17256}
17257
17258#[no_mangle]
17259pub unsafe extern "C" fn quotactl(cmd: i32, special: *const core::ffi::c_char, id: i32, addr: *mut core::ffi::c_char) -> i32 {
17260    syscall_ret(<Arch as Syscalls>::syscall4(sysno(179, 60), cmd as i64, special as i64, id as i64, addr as i64)) as i32
17261}
17262
17263#[no_mangle]
17264pub unsafe extern "C" fn klogctl(type_: i32, bufp: *mut core::ffi::c_char, len: i32) -> i32 {
17265    syscall_ret(<Arch as Syscalls>::syscall3(sysno(103, 116), type_ as i64, bufp as i64, len as i64)) as i32
17266}
17267
17268static mut SYSLOG_IDENT: [core::ffi::c_char; 64] = [0; 64];
17269static mut SYSLOG_OPTIONS: i32 = 0;
17270static mut SYSLOG_FACILITY: i32 = 1;
17271
17272#[no_mangle]
17273pub unsafe extern "C" fn openlog(ident: *const core::ffi::c_char, option: i32, facility: i32) {
17274    SYSLOG_OPTIONS = option;
17275    SYSLOG_FACILITY = facility & 0x3f8;
17276    SYSLOG_IDENT[0] = 0;
17277    if !ident.is_null() {
17278        let mut i = 0;
17279        while i < 63 && *ident.add(i) != 0 {
17280            SYSLOG_IDENT[i] = *ident.add(i);
17281            i += 1;
17282        }
17283        SYSLOG_IDENT[i] = 0;
17284    }
17285}
17286
17287#[repr(C)]
17288struct SockAddrUn {
17289    sun_family: u16,
17290    sun_path: [core::ffi::c_char; 108],
17291}
17292
17293unsafe fn syslog_emit(priority: i32, msg: *const core::ffi::c_char, len: usize) {
17294    let mut out = [0u8; 1200];
17295    let mut o = 0usize;
17296    let pri = (SYSLOG_FACILITY | (priority & 7)) as u32;
17297    out[o] = b'<'; o += 1;
17298    if pri >= 100 { out[o] = b'0' + (pri / 100) as u8; o += 1; }
17299    if pri >= 10 { out[o] = b'0' + ((pri / 10) % 10) as u8; o += 1; }
17300    out[o] = b'0' + (pri % 10) as u8; o += 1;
17301    out[o] = b'>'; o += 1;
17302    let mut i = 0;
17303    while i < 63 && SYSLOG_IDENT[i] != 0 && o + 1 < out.len() {
17304        out[o] = SYSLOG_IDENT[i] as u8; o += 1; i += 1;
17305    }
17306    if SYSLOG_OPTIONS & 1 != 0 {
17307        out[o] = b'['; o += 1;
17308        let mut pid = crate::getpid() as u32;
17309        let mut digits = [0u8; 10];
17310        let mut d = 0;
17311        if pid == 0 { digits[0] = b'0'; d = 1; }
17312        while pid > 0 { digits[d] = b'0' + (pid % 10) as u8; pid /= 10; d += 1; }
17313        while d > 0 { d -= 1; out[o] = digits[d]; o += 1; }
17314        out[o] = b']'; o += 1;
17315    }
17316    out[o] = b':'; o += 1; out[o] = b' '; o += 1;
17317    let copy = core::cmp::min(len, out.len() - o - 1);
17318    core::ptr::copy_nonoverlapping(msg as *const u8, out.as_mut_ptr().add(o), copy);
17319    o += copy;
17320    let fd = crate::socket(AF_UNIX, SOCK_DGRAM, 0);
17321    if fd >= 0 {
17322        let mut sa: SockAddrUn = core::mem::zeroed();
17323        sa.sun_family = AF_UNIX as u16;
17324        let path = b"/dev/log";
17325        for i in 0..path.len() { sa.sun_path[i] = path[i] as core::ffi::c_char; }
17326        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);
17327        crate::close(fd);
17328        if r >= 0 { return; }
17329    }
17330    crate::write(2, out.as_ptr() as *const core::ffi::c_void, o);
17331    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
17332}
17333
17334#[no_mangle]
17335pub unsafe extern "C" fn vsyslog(priority: c_int, fmt: *const c_char, ap: VaList) {
17336    let mut msg = [0 as c_char; 1024];
17337    let n = vsnprintf(msg.as_mut_ptr(), msg.len(), fmt, ap);
17338    if n > 0 { syslog_emit(priority, msg.as_ptr(), core::cmp::min(n as usize, msg.len() - 1)); }
17339}
17340
17341#[no_mangle]
17342pub unsafe extern "C" fn syslog(priority: c_int, fmt: *const c_char, args: ...) {
17343    vsyslog(priority, fmt, args);
17344}
17345
17346#[no_mangle]
17347pub unsafe extern "C" fn closelog() {
17348    // Nothing to do
17349}
17350
17351#[no_mangle]
17352pub unsafe extern "C" fn setlogmask(mask: i32) -> i32 {
17353    static mut LOG_MASK: i32 = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80;
17354    let old = LOG_MASK;
17355    if mask != 0 { LOG_MASK = mask; }
17356    old
17357}
17358
17359#[no_mangle]
17360pub unsafe extern "C" fn acct(filename: *const core::ffi::c_char) -> i32 {
17361    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ACCT, filename as i64)) as i32
17362}
17363
17364#[no_mangle]
17365pub unsafe extern "C" fn swapon(path: *const core::ffi::c_char, flags: i32) -> i32 {
17366    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SWAPON, path as i64, flags as i64)) as i32
17367}
17368
17369#[no_mangle]
17370pub unsafe extern "C" fn swapoff(path: *const core::ffi::c_char) -> i32 {
17371    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SWAPOFF, path as i64)) as i32
17372}
17373
17374#[no_mangle]
17375pub unsafe extern "C" fn syncfs(fd: i32) -> i32 {
17376    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SYNCFS, fd as i64)) as i32
17377}
17378
17379#[no_mangle]
17380pub unsafe extern "C" fn sync_file_range(fd: i32, offset: i64, nbytes: u64, flags: u32) -> i32 {
17381    syscall_ret(<Arch as Syscalls>::syscall4(sysno(277, 84), fd as i64, offset, nbytes as i64, flags as i64)) as i32
17382}
17383
17384#[no_mangle]
17385pub unsafe extern "C" fn posix_fadvise(fd: i32, offset: i64, len: u64, advice: i32) -> i32 {
17386    // POSIX returns the error number directly, not -1/errno.
17387    let r = <Arch as Syscalls>::syscall4(sysno(221, 223), fd as i64, offset, len as i64, advice as i64);
17388    if r < 0 { (-r) as i32 } else { 0 }
17389}
17390
17391#[no_mangle]
17392pub unsafe extern "C" fn posix_fallocate(fd: i32, offset: i64, len: u64) -> i32 {
17393    let r = <Arch as Syscalls>::syscall3(SYS_FALLOCATE, fd as i64, offset, len as i64);
17394    if r < 0 { (-r) as i32 } else { 0 }
17395}
17396
17397#[no_mangle]
17398pub unsafe extern "C" fn readahead(fd: i32, offset: i64, count: usize) -> isize {
17399    // musl declares readahead() as ssize_t; returning int leaves the upper
17400    // half of rax undefined for callers that expect a 64-bit result.
17401    syscall_ret(<Arch as Syscalls>::syscall3(sysno(187, 213), fd as i64, offset, count as i64)) as isize
17402}
17403
17404#[no_mangle]
17405pub unsafe extern "C" fn fallocate(fd: i32, mode: i32, offset: i64, len: u64) -> i32 {
17406    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FALLOCATE, fd as i64, mode as i64, offset, len as i64)) as i32
17407}
17408
17409// ============================================================
17410// Terminal functions
17411// ============================================================
17412
17413#[no_mangle]
17414pub unsafe extern "C" fn tcgetattr(fd: i32, termios_p: *mut core::ffi::c_void) -> i32 {
17415    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5401, termios_p as i64)) as i32
17416}
17417
17418#[no_mangle]
17419pub unsafe extern "C" fn tcsetattr(fd: i32, optional_actions: i32, termios_p: *const core::ffi::c_void) -> i32 {
17420    let cmd = match optional_actions {
17421        0 => 0x5402,
17422        1 => 0x5403,
17423        2 => 0x5404,
17424        _ => 0x5402,
17425    };
17426    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, cmd, termios_p as i64)) as i32
17427}
17428
17429#[no_mangle]
17430pub unsafe extern "C" fn tcdrain(fd: i32) -> i32 {
17431    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5409, 1)) as i32
17432}
17433
17434#[no_mangle]
17435pub unsafe extern "C" fn tcflush(fd: i32, queue_selector: i32) -> i32 {
17436    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540B, queue_selector as i64)) as i32
17437}
17438
17439#[no_mangle]
17440pub unsafe extern "C" fn tcflow(fd: i32, action: i32) -> i32 {
17441    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540A, action as i64)) as i32
17442}
17443
17444#[no_mangle]
17445pub unsafe extern "C" fn tcsendbreak(fd: i32, duration: i32) -> i32 {
17446    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5425, duration as i64)) as i32
17447}
17448
17449#[no_mangle]
17450pub unsafe extern "C" fn tcgetsid(fd: i32) -> i32 {
17451    let mut sid: i32 = 0;
17452    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5429, &mut sid as *mut i32 as i64);
17453    if r < 0 { -1 } else { sid }
17454}
17455
17456#[no_mangle]
17457pub unsafe extern "C" fn tcgetpgrp(fd: i32) -> i32 {
17458    let mut pgrp: i32 = 0;
17459    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540F, &mut pgrp as *mut i32 as i64);
17460    if r < 0 { -1 } else { pgrp }
17461}
17462
17463#[no_mangle]
17464pub unsafe extern "C" fn tcsetpgrp(fd: i32, pgrp: i32) -> i32 {
17465    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5410, &pgrp as *const i32 as i64)) as i32
17466}
17467
17468// ============================================================
17469// Memory locking functions
17470// ============================================================
17471
17472// ============================================================
17473
17474// ============================================================
17475// POSIX message queue functions
17476// ============================================================
17477
17478#[no_mangle]
17479pub unsafe extern "C" fn mq_open(name: *const core::ffi::c_char, oflag: i32, mut args: ...) -> i32 {
17480    if name.is_null() { ERRNO!() = EINVAL; return -1; }
17481    let mut p = name as *const u8;
17482    if *p == b'/' { p = p.add(1); }
17483    let mut mode: u32 = 0;
17484    let mut attr: *const core::ffi::c_void = core::ptr::null();
17485    if oflag & 0o100 != 0 {
17486        mode = args.next_arg::<u32>();
17487        attr = args.next_arg::<*const core::ffi::c_void>();
17488    }
17489    syscall_ret(<Arch as Syscalls>::syscall4(
17490        sysno(240, 180),
17491        p as i64,
17492        oflag as i64,
17493        mode as i64,
17494        attr as i64,
17495    )) as i32
17496}
17497
17498#[no_mangle]
17499pub unsafe extern "C" fn mq_close(mqdes: i32) -> i32 {
17500    crate::close(mqdes as i32)
17501}
17502
17503#[no_mangle]
17504pub unsafe extern "C" fn mq_unlink(name: *const core::ffi::c_char) -> i32 {
17505    if name.is_null() { ERRNO!() = EINVAL; return -1; }
17506    let mut p = name as *const u8;
17507    if *p == b'/' { p = p.add(1); }
17508    let r = <Arch as Syscalls>::syscall1(sysno(241, 181), p as i64);
17509    if r < 0 {
17510        // The kernel reports EPERM for an unlink while the queue is open.
17511        let e = if (-r) as c_int == 1 { 13 } else { (-r) as c_int };
17512        ERRNO!() = e;
17513        -1
17514    } else {
17515        0
17516    }
17517}
17518
17519#[no_mangle]
17520pub unsafe extern "C" fn mq_send(mqdes: i32, msg_ptr: *const core::ffi::c_char, msg_len: usize, msg_prio: u32) -> i32 {
17521    mq_timedsend(mqdes, msg_ptr, msg_len, msg_prio, core::ptr::null())
17522}
17523
17524#[no_mangle]
17525pub unsafe extern "C" fn mq_receive(mqdes: i32, msg_ptr: *mut core::ffi::c_char, msg_len: usize, msg_prio: *mut u32) -> isize {
17526    mq_timedreceive(mqdes, msg_ptr, msg_len, msg_prio, core::ptr::null())
17527}
17528
17529#[no_mangle]
17530pub unsafe extern "C" fn mq_timedsend(
17531    mqdes: i32,
17532    msg_ptr: *const core::ffi::c_char,
17533    msg_len: usize,
17534    msg_prio: u32,
17535    abs_timeout: *const core::ffi::c_void,
17536) -> i32 {
17537    syscall_ret(<Arch as Syscalls>::syscall5(
17538        sysno(242, 182),
17539        mqdes as i64,
17540        msg_ptr as i64,
17541        msg_len as i64,
17542        msg_prio as i64,
17543        abs_timeout as i64,
17544    )) as i32
17545}
17546
17547#[no_mangle]
17548pub unsafe extern "C" fn mq_timedreceive(
17549    mqdes: i32,
17550    msg_ptr: *mut core::ffi::c_char,
17551    msg_len: usize,
17552    msg_prio: *mut u32,
17553    abs_timeout: *const core::ffi::c_void,
17554) -> isize {
17555    syscall_ret(<Arch as Syscalls>::syscall5(
17556        sysno(243, 183),
17557        mqdes as i64,
17558        msg_ptr as i64,
17559        msg_len as i64,
17560        msg_prio as i64,
17561        abs_timeout as i64,
17562    )) as isize
17563}
17564
17565#[repr(C)]
17566pub struct SigEventFull {
17567    sigev_value: usize,
17568    sigev_signo: i32,
17569    sigev_notify: i32,
17570    sigev_function: usize,
17571    sigev_attributes: usize,
17572    sigev_pad: [u8; 32],
17573}
17574
17575struct MqNotifyArgs {
17576    sem: sem_t,
17577    sock: i32,
17578    mqd: i32,
17579    err: i32,
17580    func: usize,
17581    value: usize,
17582}
17583
17584unsafe extern "C" fn mq_notify_thread(arg: *mut c_void) -> *mut c_void {
17585    let a = &mut *(arg as *mut MqNotifyArgs);
17586    let sock = a.sock;
17587    let mqd = a.mqd;
17588    let func = a.func;
17589    let value = a.value;
17590    let zeros = [0u8; 32];
17591    let sev2 = SigEventFull {
17592        sigev_value: zeros.as_ptr() as usize,
17593        sigev_signo: sock,
17594        sigev_notify: 2, // SIGEV_THREAD, consumed by the kernel as a netlink fd
17595        sigev_function: 0,
17596        sigev_attributes: 0,
17597        sigev_pad: [0; 32],
17598    };
17599    let r = <Arch as Syscalls>::syscall2(sysno(244, 184), mqd as i64, &sev2 as *const SigEventFull as i64);
17600    a.err = if r < 0 { (-r) as i32 } else { 0 };
17601    sem_post(&mut a.sem);
17602    if a.err != 0 { return core::ptr::null_mut(); }
17603    pthread_detach(pthread_self());
17604    let mut buf = [0u8; 32];
17605    let n = recv(sock, buf.as_mut_ptr() as *mut c_void, buf.len(), 0x4000 | 0x100);
17606    crate::close(sock);
17607    if n as usize == buf.len() && buf[buf.len() - 1] == 1 && func != 0 {
17608        let f: extern "C" fn(usize) = core::mem::transmute(func);
17609        f(value);
17610    }
17611    core::ptr::null_mut()
17612}
17613
17614#[no_mangle]
17615pub unsafe extern "C" fn mq_notify(mqdes: i32, sev: *const core::ffi::c_void) -> i32 {
17616    if sev.is_null() {
17617        return syscall_ret(<Arch as Syscalls>::syscall2(sysno(244, 184), mqdes as i64, 0)) as i32;
17618    }
17619    let ev = &*(sev as *const SigEventFull);
17620    if ev.sigev_notify != 2 {
17621        return syscall_ret(<Arch as Syscalls>::syscall2(sysno(244, 184), mqdes as i64, sev as i64)) as i32;
17622    }
17623
17624    // SIGEV_THREAD is emulated with a netlink socket and a helper thread,
17625    // matching musl. The kernel only deals with the socket.
17626    let sock = socket(16 /* AF_NETLINK */, 3 | 0x80000 /* SOCK_RAW|SOCK_CLOEXEC */, 0);
17627    if sock < 0 { return -1; }
17628    let mut a = MqNotifyArgs {
17629        sem: core::mem::zeroed(),
17630        sock,
17631        mqd: mqdes,
17632        err: 0,
17633        func: ev.sigev_function,
17634        value: ev.sigev_value,
17635    };
17636    sem_init(&mut a.sem, 0, 0);
17637
17638    let mut attr: pthread_attr_t = core::mem::zeroed();
17639    if ev.sigev_attributes != 0 {
17640        attr = core::ptr::read(ev.sigev_attributes as *const pthread_attr_t);
17641    } else {
17642        pthread_attr_init(&mut attr);
17643    }
17644    pthread_attr_setdetachstate(&mut attr, PTHREAD_CREATE_JOINABLE);
17645
17646    let mut all: SigSetT = 0;
17647    sigfillset(&mut all);
17648    let mut orig: SigSetT = 0;
17649    pthread_sigmask(0 /* SIG_BLOCK */, &all, &mut orig);
17650
17651    let mut td: PthreadT = 0;
17652    let r = pthread_create(&mut td, &attr, mq_notify_thread as *const () as usize, &mut a as *mut MqNotifyArgs as *mut c_void);
17653    pthread_sigmask(2 /* SIG_SETMASK */, &orig, core::ptr::null_mut());
17654    if r != 0 {
17655        crate::close(sock);
17656        ERRNO!() = 11;
17657        return -1;
17658    }
17659    sem_wait(&mut a.sem);
17660    sem_destroy(&mut a.sem);
17661    if a.err != 0 {
17662        crate::close(sock);
17663        pthread_join(td, core::ptr::null_mut());
17664        ERRNO!() = a.err;
17665        return -1;
17666    }
17667    0
17668}
17669
17670#[no_mangle]
17671pub unsafe extern "C" fn mq_getattr(mqdes: i32, attr: *mut core::ffi::c_void) -> i32 {
17672    mq_setattr(mqdes, core::ptr::null(), attr)
17673}
17674
17675#[no_mangle]
17676pub unsafe extern "C" fn mq_setattr(
17677    mqdes: i32,
17678    new: *const core::ffi::c_void,
17679    old: *mut core::ffi::c_void,
17680) -> i32 {
17681    syscall_ret(<Arch as Syscalls>::syscall3(
17682        sysno(245, 185),
17683        mqdes as i64,
17684        new as i64,
17685        old as i64,
17686    )) as i32
17687}
17688
17689// ============================================================
17690// pthread functions
17691// ============================================================
17692
17693#[no_mangle]
17694pub unsafe extern "C" fn pthread_getaffinity_np(thread: usize, cpusetsize: usize, cpuset: *mut u8) -> i32 {
17695    sched_getaffinity(thread as i32, cpusetsize, cpuset)
17696}
17697
17698#[no_mangle]
17699pub unsafe extern "C" fn pthread_setaffinity_np(thread: usize, cpusetsize: usize, cpuset: *const u8) -> i32 {
17700    sched_setaffinity(thread as i32, cpusetsize, cpuset)
17701}
17702
17703// ============================================================
17704// sched functions
17705// ============================================================
17706
17707#[no_mangle]
17708pub unsafe extern "C" fn sched_yield() -> i32 {
17709    syscall_ret(<Arch as Syscalls>::syscall0(sysno(24, 124))) as i32
17710}
17711
17712#[no_mangle]
17713pub unsafe extern "C" fn sched_get_priority_max(policy: i32) -> i32 {
17714    syscall_ret(<Arch as Syscalls>::syscall1(sysno(146, 125), policy as i64)) as i32
17715}
17716
17717#[no_mangle]
17718pub unsafe extern "C" fn sched_get_priority_min(policy: i32) -> i32 {
17719    syscall_ret(<Arch as Syscalls>::syscall1(sysno(147, 126), policy as i64)) as i32
17720}
17721
17722#[no_mangle]
17723pub unsafe extern "C" fn sched_getparam(pid: i32, param: *mut core::ffi::c_void) -> i32 {
17724    syscall_ret(<Arch as Syscalls>::syscall2(sysno(143, 121), pid as i64, param as i64)) as i32
17725}
17726
17727#[no_mangle]
17728pub unsafe extern "C" fn sched_setparam(pid: i32, param: *const core::ffi::c_void) -> i32 {
17729    syscall_ret(<Arch as Syscalls>::syscall2(sysno(142, 118), pid as i64, param as i64)) as i32
17730}
17731
17732#[no_mangle]
17733pub unsafe extern "C" fn sched_getscheduler(pid: i32) -> i32 {
17734    syscall_ret(<Arch as Syscalls>::syscall1(sysno(145, 120), pid as i64)) as i32
17735}
17736
17737#[no_mangle]
17738pub unsafe extern "C" fn sched_setscheduler(pid: i32, policy: i32, param: *const core::ffi::c_void) -> i32 {
17739    syscall_ret(<Arch as Syscalls>::syscall3(sysno(144, 119), pid as i64, policy as i64, param as i64)) as i32
17740}
17741
17742#[no_mangle]
17743pub unsafe extern "C" fn sched_setaffinity(pid: i32, cpusetsize: usize, cpuset: *const u8) -> i32 {
17744    syscall_ret(<Arch as Syscalls>::syscall3(sysno(203, 122), pid as i64, cpusetsize as i64, cpuset as i64)) as i32
17745}
17746
17747#[no_mangle]
17748pub unsafe extern "C" fn sched_getaffinity(pid: i32, cpusetsize: usize, cpuset: *mut u8) -> i32 {
17749    let r = <Arch as Syscalls>::syscall3(sysno(204, 123), pid as i64, cpusetsize as i64, cpuset as i64);
17750    if r < 0 {
17751        ERRNO!() = (-r) as c_int;
17752        return -1;
17753    }
17754    // The kernel returns the number of bytes copied, not 0.
17755    0
17756}
17757
17758#[cold]
17759unsafe fn sched_getcpu_syscall(cpu: *mut u32) -> i32 {
17760    let r = <Arch as Syscalls>::syscall3(sysno(309, 168), cpu as i64, 0, 0);
17761    if r == 0 {
17762        core::ptr::read_unaligned(cpu) as i32
17763    } else {
17764        syscall_ret(r) as i32
17765    }
17766}
17767
17768#[no_mangle]
17769pub unsafe extern "C" fn sched_getcpu() -> i32 {
17770    // Both the vDSO and the syscall fill the slot on success.  A 16-byte
17771    // scratch area keeps the write away from the return address; a 4-byte
17772    // slot overlaps the compiler's push and triggers a store-forwarding
17773    // stall on the vDSO write (measured ~2.5 ns).
17774    let mut cpu = core::mem::MaybeUninit::<[u64; 2]>::uninit();
17775    let cpu_ptr = cpu.as_mut_ptr() as *mut u32;
17776    if vdso_getcpu(cpu_ptr) {
17777        return core::ptr::read_unaligned(cpu_ptr) as i32;
17778    }
17779    sched_getcpu_syscall(cpu_ptr)
17780}
17781
17782#[no_mangle]
17783pub unsafe extern "C" fn sched_rr_get_interval(pid: i32, tp: *mut core::ffi::c_void) -> i32 {
17784    syscall_ret(<Arch as Syscalls>::syscall2(sysno(148, 127), pid as i64, tp as i64)) as i32
17785}
17786
17787// ============================================================
17788// timer/clock functions
17789// ============================================================
17790
17791#[no_mangle]
17792pub unsafe extern "C" fn timer_create(clockid: i32, sevp: *mut core::ffi::c_void, timerid: *mut i32) -> i32 {
17793    syscall_ret(<Arch as Syscalls>::syscall3(sysno(222, 107), clockid as i64, sevp as i64, timerid as i64)) as i32
17794}
17795
17796#[no_mangle]
17797pub unsafe extern "C" fn timer_delete(timerid: i32) -> i32 {
17798    syscall_ret(<Arch as Syscalls>::syscall1(sysno(226, 111), timerid as i64)) as i32
17799}
17800
17801#[no_mangle]
17802pub 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 {
17803    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
17804}
17805
17806#[no_mangle]
17807pub unsafe extern "C" fn timer_gettime(timerid: i32, curr_value: *mut core::ffi::c_void) -> i32 {
17808    syscall_ret(<Arch as Syscalls>::syscall2(sysno(224, 108), timerid as i64, curr_value as i64)) as i32
17809}
17810
17811#[no_mangle]
17812pub unsafe extern "C" fn timer_getoverrun(timerid: i32) -> i32 {
17813    syscall_ret(<Arch as Syscalls>::syscall1(sysno(225, 109), timerid as i64)) as i32
17814}
17815
17816#[no_mangle]
17817pub unsafe extern "C" fn clock_adjtime(_clockid: i32, buf: *mut core::ffi::c_void) -> i32 {
17818    syscall_ret(<Arch as Syscalls>::syscall2(SYS_ADJTIMEX, buf as i64, 0)) as i32
17819}
17820
17821#[no_mangle]
17822pub unsafe extern "C" fn clock_getcpuclockid(pid: i32, clockid: *mut i32) -> i32 {
17823    if clockid.is_null() { return EINVAL; }
17824    let id: i32 = ((-(pid as i64) - 1) * 8 + 2) as i32;
17825    let mut ts: timespec = core::mem::zeroed();
17826    let r = <Arch as Syscalls>::syscall2(SYS_CLOCK_GETRES, id as i64, &mut ts as *mut timespec as i64);
17827    if r < 0 {
17828        let e = (-r) as c_int;
17829        return if e == EINVAL { 3 } else { e };
17830    }
17831    *clockid = id;
17832    0
17833}
17834
17835// ============================================================
17836// String functions
17837// ============================================================
17838
17839#[no_mangle]
17840pub unsafe extern "C" fn strcoll(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> i32 {
17841    // musl's C locale compares byte strings directly (strcmp semantics).
17842    let mut i = 0;
17843    loop {
17844        let c1 = *s1.add(i) as u8;
17845        let c2 = *s2.add(i) as u8;
17846        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
17847        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
17848        i += 1;
17849    }
17850}
17851
17852#[no_mangle]
17853pub unsafe extern "C" fn strxfrm(dest: *mut core::ffi::c_char, src: *const core::ffi::c_char, n: usize) -> usize {
17854    let mut i = 0;
17855    while i < n {
17856        let c = *src.add(i);
17857        *dest.add(i) = c;
17858        if c == 0 { break; }
17859        i += 1;
17860    }
17861    i
17862}
17863
17864// ============================================================
17865// Directory functions
17866// ============================================================
17867
17868#[no_mangle]
17869pub unsafe extern "C" fn scandir(
17870    dirp: *const core::ffi::c_char,
17871    namelist: *mut *mut *mut core::ffi::c_void,
17872    filter: Option<unsafe extern "C" fn(*const core::ffi::c_void) -> i32>,
17873    compar: Option<unsafe extern "C" fn(*const core::ffi::c_void, *const core::ffi::c_void) -> i32>,
17874) -> c_int {
17875    if dirp.is_null() || namelist.is_null() {
17876        ERRNO!() = EINVAL;
17877        return -1;
17878    }
17879    *namelist = core::ptr::null_mut();
17880    let dir = opendir(dirp);
17881    if dir.is_null() { return -1; }
17882
17883    let mut cap = 16usize;
17884    let mut count = 0usize;
17885    let mut list = crate::malloc(cap * core::mem::size_of::<*mut c_void>()) as *mut *mut c_void;
17886    if list.is_null() { closedir(dir); ERRNO!() = ENOMEM; return -1; }
17887
17888    loop {
17889        let ent = readdir(dir);
17890        if ent.is_null() { break; }
17891        if let Some(filter) = filter {
17892            if filter(ent as *const c_void) == 0 { continue; }
17893        }
17894        if count == cap {
17895            let new_cap = match cap.checked_mul(2) {
17896                Some(n) => n,
17897                None => {
17898                    for i in 0..count { crate::free(*list.add(i)); }
17899                    crate::free(list as *mut c_void);
17900                    closedir(dir);
17901                    ERRNO!() = ENOMEM;
17902                    return -1;
17903                }
17904            };
17905            let p = crate::realloc(
17906                list as *mut c_void,
17907                new_cap * core::mem::size_of::<*mut c_void>(),
17908            ) as *mut *mut c_void;
17909            if p.is_null() {
17910                for i in 0..count { crate::free(*list.add(i)); }
17911                crate::free(list as *mut c_void);
17912                closedir(dir);
17913                ERRNO!() = ENOMEM;
17914                return -1;
17915            }
17916            list = p;
17917            cap = new_cap;
17918        }
17919        let name = (ent as *const u8).add(core::mem::offset_of!(linux_dirent64, d_name))
17920            as *const core::ffi::c_char;
17921        let copy = crate::strdup(name);
17922        if copy.is_null() {
17923            for i in 0..count { crate::free(*list.add(i)); }
17924            crate::free(list as *mut c_void);
17925            closedir(dir);
17926            ERRNO!() = ENOMEM;
17927            return -1;
17928        }
17929        *list.add(count) = copy as *mut c_void;
17930        count += 1;
17931    }
17932    closedir(dir);
17933
17934    if let Some(compar) = compar {
17935        if count > 1 {
17936            qsort(
17937                list as *mut c_void,
17938                count,
17939                core::mem::size_of::<*mut c_void>(),
17940                compar,
17941            );
17942        }
17943    }
17944    *namelist = list;
17945    count as c_int
17946}
17947
17948#[no_mangle]
17949pub unsafe extern "C" fn alphasort(a: *const *const core::ffi::c_void, b: *const *const core::ffi::c_void) -> i32 {
17950    let s1 = *a as *const core::ffi::c_char;
17951    let s2 = *b as *const core::ffi::c_char;
17952    crate::strcmp(s1 as *const u8, s2 as *const u8)
17953}
17954
17955#[no_mangle]
17956pub unsafe extern "C" fn versionsort(a: *const *const core::ffi::c_void, b: *const *const core::ffi::c_void) -> i32 {
17957    let s1 = *a as *const core::ffi::c_char;
17958    let s2 = *b as *const core::ffi::c_char;
17959    crate::strcmp(s1 as *const u8, s2 as *const u8)
17960}
17961
17962// ============================================================
17963
17964
17965// ============================================================
17966// err functions
17967// ============================================================
17968
17969unsafe fn vwarn_impl(fmt: *const c_char, ap: VaList, with_errno: bool) {
17970    let mut buf = [0 as c_char; 1024];
17971    let n = vsnprintf(buf.as_mut_ptr(), buf.len(), fmt, ap);
17972    if n > 0 {
17973        let l = core::cmp::min(n as usize, buf.len() - 1);
17974        crate::write(2, buf.as_ptr() as *const c_void, l);
17975    }
17976    if with_errno {
17977        let e = ERRNO!();
17978        crate::write(2, b": ".as_ptr() as *const c_void, 2);
17979        let msg = strerror(e);
17980        crate::write(2, msg as *const c_void, crate::strlen(msg));
17981    }
17982    crate::write(2, b"\n".as_ptr() as *const c_void, 1);
17983}
17984
17985#[no_mangle]
17986pub unsafe extern "C" fn verr(eval: c_int, fmt: *const c_char, ap: VaList) {
17987    vwarn_impl(fmt, ap, true);
17988    crate::exit(eval);
17989}
17990
17991#[no_mangle]
17992pub unsafe extern "C" fn verrx(eval: c_int, fmt: *const c_char, ap: VaList) {
17993    vwarn_impl(fmt, ap, false);
17994    crate::exit(eval);
17995}
17996
17997#[no_mangle]
17998pub unsafe extern "C" fn vwarn(fmt: *const c_char, ap: VaList) {
17999    vwarn_impl(fmt, ap, true);
18000}
18001
18002#[no_mangle]
18003pub unsafe extern "C" fn vwarnx(fmt: *const c_char, ap: VaList) {
18004    vwarn_impl(fmt, ap, false);
18005}
18006
18007#[no_mangle]
18008pub unsafe extern "C" fn err(eval: c_int, fmt: *const c_char, args: ...) {
18009    verr(eval, fmt, args);
18010}
18011
18012#[no_mangle]
18013pub unsafe extern "C" fn errx(eval: c_int, fmt: *const c_char, args: ...) {
18014    verrx(eval, fmt, args);
18015}
18016
18017#[no_mangle]
18018pub unsafe extern "C" fn warn(fmt: *const c_char, args: ...) {
18019    vwarn(fmt, args);
18020}
18021
18022#[no_mangle]
18023pub unsafe extern "C" fn warnx(fmt: *const c_char, args: ...) {
18024    vwarnx(fmt, args);
18025}
18026
18027// ============================================================
18028// ecvt functions
18029// ============================================================
18030
18031#[no_mangle]
18032pub unsafe extern "C" fn ecvt(value: f64, ndigit: i32, decpt: *mut i32, sign: *mut i32) -> *mut core::ffi::c_char {
18033    static mut BUF: [core::ffi::c_char; 80] = [0; 80];
18034    if value < 0.0 { *sign = 1; } else { *sign = 0; }
18035    let v = if value < 0.0 { -value } else { value };
18036    if v == 0.0 { *decpt = 0; BUF[0] = 0; return BUF.as_mut_ptr(); }
18037    let mut d = 0i32;
18038    let mut tmp = v;
18039    while tmp >= 10.0 { tmp /= 10.0; d += 1; }
18040    while tmp < 1.0 { tmp *= 10.0; d -= 1; }
18041    *decpt = d + 1;
18042    let mut i = 0;
18043    let mut val = tmp;
18044    while i < ndigit as usize && i < 79 {
18045        let digit = val as i32;
18046        BUF[i] = (b'0' + digit as u8) as c_char;
18047        val = (val - digit as f64) * 10.0;
18048        i += 1;
18049    }
18050    BUF[i] = 0;
18051    BUF.as_mut_ptr()
18052}
18053
18054#[no_mangle]
18055pub unsafe extern "C" fn fcvt(value: f64, ndigit: i32, decpt: *mut i32, sign: *mut i32) -> *mut core::ffi::c_char {
18056    static mut BUF: [core::ffi::c_char; 80] = [0; 80];
18057    if value < 0.0 { *sign = 1; } else { *sign = 0; }
18058    let v = if value < 0.0 { -value } else { value };
18059    if v == 0.0 { *decpt = 0; BUF[0] = 0; return BUF.as_mut_ptr(); }
18060    let mut d = 0i32;
18061    let mut tmp = v;
18062    while tmp >= 10.0 { tmp /= 10.0; d += 1; }
18063    while tmp < 1.0 { tmp *= 10.0; d -= 1; }
18064    *decpt = d + 1;
18065    let mut val = tmp;
18066    let mut i = 0;
18067    while i < (*decpt) as usize && i < 79 {
18068        let digit = val as i32;
18069        BUF[i] = (b'0' + digit as u8) as c_char;
18070        val = (val - digit as f64) * 10.0;
18071        i += 1;
18072    }
18073    if ndigit > 0 && i < 79 {
18074        BUF[i] = '.' as c_char;
18075        i += 1;
18076        let mut frac = val;
18077        let mut j = 0;
18078        while j < ndigit as usize && i < 79 {
18079            let digit = frac as i32;
18080            BUF[i] = (b'0' + digit as u8) as c_char;
18081            frac = (frac - digit as f64) * 10.0;
18082            i += 1;
18083            j += 1;
18084        }
18085    }
18086    BUF[i] = 0;
18087    BUF.as_mut_ptr()
18088}
18089
18090#[no_mangle]
18091pub unsafe extern "C" fn gcvt(value: f64, ndigit: i32, buf: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
18092    if buf.is_null() {
18093        return buf;
18094    }
18095    // musl implements gcvt as sprintf("%.*g"); cap the write at a size that
18096    // always covers %g's output for the requested precision.
18097    let cap = if ndigit > 0 {
18098        (ndigit as usize).saturating_mul(2).saturating_add(32).min(4096)
18099    } else {
18100        32
18101    };
18102    crate::snprintf(buf, cap, b"%.*g\0".as_ptr() as *const core::ffi::c_char, ndigit, value);
18103    buf
18104}
18105
18106// ============================================================
18107// usershell functions
18108// ============================================================
18109
18110static mut SHELLS: [*const core::ffi::c_char; 3] = [
18111    b"/bin/sh\0".as_ptr() as *const core::ffi::c_char,
18112    b"/bin/bash\0".as_ptr() as *const core::ffi::c_char,
18113    core::ptr::null(),
18114];
18115static mut SHELL_IDX: usize = 0;
18116
18117#[no_mangle]
18118pub unsafe extern "C" fn getusershell() -> *mut core::ffi::c_char {
18119    let s = SHELLS[SHELL_IDX];
18120    if s.is_null() {
18121        SHELL_IDX = 0;
18122        return core::ptr::null_mut();
18123    }
18124    SHELL_IDX += 1;
18125    s as *mut core::ffi::c_char
18126}
18127
18128#[no_mangle]
18129pub unsafe extern "C" fn setusershell() {
18130    SHELL_IDX = 0;
18131}
18132
18133#[no_mangle]
18134pub unsafe extern "C" fn endusershell() {
18135    SHELL_IDX = 0;
18136}
18137
18138// ============================================================
18139// ether functions
18140// ============================================================
18141
18142#[no_mangle]
18143pub unsafe extern "C" fn ether_aton(s: *const core::ffi::c_char) -> *mut u8 {
18144    static mut EA: [u8; 6] = [0; 6];
18145    if ether_aton_r(s, EA.as_mut_ptr()).is_null() { core::ptr::null_mut() } else { EA.as_mut_ptr() }
18146}
18147
18148#[no_mangle]
18149pub unsafe extern "C" fn ether_aton_r(s: *const core::ffi::c_char, ea: *mut u8) -> *mut u8 {
18150    if ea.is_null() { return core::ptr::null_mut(); }
18151    let mut i = 0;
18152    let mut j = 0;
18153    let mut val: u32 = 0;
18154    let mut digits = 0;
18155    while *s.add(i) != 0 && j < 6 {
18156        let c = *s.add(i);
18157        if c == ':' as c_char {
18158            if digits == 0 { return core::ptr::null_mut(); }
18159            *ea.add(j) = val as u8;
18160            j += 1;
18161            val = 0;
18162            digits = 0;
18163        } 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) {
18164            let d = if c >= '0' as c_char && c <= '9' as c_char { (c - '0' as c_char) as u32 }
18165                   else if c >= 'a' as c_char { (c - 'a' as c_char + 10) as u32 }
18166                   else { (c - 'A' as c_char + 10) as u32 };
18167            val = val * 16 + d;
18168            if val > 255 { return core::ptr::null_mut(); }
18169            digits += 1;
18170            if digits > 2 { return core::ptr::null_mut(); }
18171        } else {
18172            return core::ptr::null_mut();
18173        }
18174        i += 1;
18175    }
18176    if digits == 0 || j != 5 { return core::ptr::null_mut(); }
18177    *ea.add(j) = val as u8;
18178    ea
18179}
18180
18181#[no_mangle]
18182pub unsafe extern "C" fn ether_ntoa(ea: *const u8) -> *mut core::ffi::c_char {
18183    static mut BUF: [core::ffi::c_char; 18] = [0; 18];
18184    ether_ntoa_r(ea, BUF.as_mut_ptr());
18185    BUF.as_mut_ptr()
18186}
18187
18188#[no_mangle]
18189pub unsafe extern "C" fn ether_ntoa_r(ea: *const u8, buf: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
18190    let a = *ea.add(0); let b = *ea.add(1); let c = *ea.add(2);
18191    let d = *ea.add(3); let e = *ea.add(4); let f = *ea.add(5);
18192    let hex = b"0123456789abcdef\0".as_ptr() as *const u8;
18193    let mut i = 0;
18194    *buf.add(i) = *hex.add((a >> 4) as usize) as c_char; i += 1;
18195    *buf.add(i) = *hex.add((a & 0xf) as usize) as c_char; i += 1;
18196    *buf.add(i) = ':' as c_char; i += 1;
18197    *buf.add(i) = *hex.add((b >> 4) as usize) as c_char; i += 1;
18198    *buf.add(i) = *hex.add((b & 0xf) as usize) as c_char; i += 1;
18199    *buf.add(i) = ':' as c_char; i += 1;
18200    *buf.add(i) = *hex.add((c >> 4) as usize) as c_char; i += 1;
18201    *buf.add(i) = *hex.add((c & 0xf) as usize) as c_char; i += 1;
18202    *buf.add(i) = ':' as c_char; i += 1;
18203    *buf.add(i) = *hex.add((d >> 4) as usize) as c_char; i += 1;
18204    *buf.add(i) = *hex.add((d & 0xf) as usize) as c_char; i += 1;
18205    *buf.add(i) = ':' as c_char; i += 1;
18206    *buf.add(i) = *hex.add((e >> 4) as usize) as c_char; i += 1;
18207    *buf.add(i) = *hex.add((e & 0xf) as usize) as c_char; i += 1;
18208    *buf.add(i) = ':' as c_char; i += 1;
18209    *buf.add(i) = *hex.add((f >> 4) as usize) as c_char; i += 1;
18210    *buf.add(i) = *hex.add((f & 0xf) as usize) as c_char; i += 1;
18211    *buf.add(i) = 0;
18212    buf
18213}
18214
18215// ============================================================
18216// utmpx functions
18217// ============================================================
18218
18219#[no_mangle]
18220pub unsafe extern "C" fn getutxent() -> *mut core::ffi::c_void {
18221    getutent()
18222}
18223
18224#[no_mangle]
18225pub unsafe extern "C" fn getutxid(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
18226    getutid(ut)
18227}
18228
18229#[no_mangle]
18230pub unsafe extern "C" fn getutxline(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
18231    getutline(ut)
18232}
18233
18234#[no_mangle]
18235pub unsafe extern "C" fn pututxline(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
18236    pututline(ut)
18237}
18238
18239#[no_mangle]
18240pub unsafe extern "C" fn setutxent() {
18241    setutent()
18242}
18243
18244#[no_mangle]
18245pub unsafe extern "C" fn endutxent() {
18246    endutent()
18247}
18248
18249// ============================================================
18250// exec functions
18251// ============================================================
18252
18253#[no_mangle]
18254pub unsafe extern "C" fn execv(path: *const core::ffi::c_char, argv: *const *const core::ffi::c_char) -> i32 {
18255    crate::execve(path, argv, __environ as *const *const core::ffi::c_char)
18256}
18257
18258#[no_mangle]
18259pub unsafe extern "C" fn execlp(file: *const core::ffi::c_char, _args: ...) -> i32 {
18260    let mut cap = 16usize;
18261    let mut argv = malloc(cap * core::mem::size_of::<*const core::ffi::c_char>()) as *mut *const core::ffi::c_char;
18262    if argv.is_null() { ERRNO!() = ENOMEM; return -1; }
18263    let mut i = 0usize;
18264    let mut args = _args;
18265    loop {
18266        let arg = args.next_arg::<*const core::ffi::c_char>();
18267        if arg.is_null() { break; }
18268        if i + 1 >= cap {
18269            cap = match cap.checked_mul(2) { Some(v) => v, None => { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; } };
18270            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;
18271            if grown.is_null() { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; }
18272            argv = grown;
18273        }
18274        *argv.add(i) = arg;
18275        i += 1;
18276    }
18277    *argv.add(i) = core::ptr::null();
18278    let r = execvp(file, argv);
18279    free(argv as *mut c_void);
18280    r
18281}
18282
18283#[no_mangle]
18284pub unsafe extern "C" fn execvp(file: *const core::ffi::c_char, argv: *const *const core::ffi::c_char) -> i32 {
18285    execvpe(file, argv, __environ as *const *const core::ffi::c_char)
18286}
18287
18288unsafe fn write_decimal(dst: *mut c_char, mut value: usize) -> usize {
18289    let mut tmp = [0u8; 20];
18290    let mut n = 0usize;
18291    if value == 0 {
18292        tmp[0] = b'0';
18293        n = 1;
18294    } else {
18295        while value > 0 {
18296            tmp[n] = b'0' + (value % 10) as u8;
18297            value /= 10;
18298            n += 1;
18299        }
18300    }
18301    for i in 0..n {
18302        *dst.add(i) = tmp[n - 1 - i] as c_char;
18303    }
18304    n
18305}
18306
18307#[no_mangle]
18308pub unsafe extern "C" fn fexecve(fd: i32, argv: *const *const core::ffi::c_char, envp: *const *const core::ffi::c_char) -> i32 {
18309    // Read /proc/self/fd/N to get the path
18310    let mut path: [core::ffi::c_char; 64] = [0; 64];
18311    let mut i = 0;
18312    let src = b"/proc/self/fd/\0".as_ptr() as *const core::ffi::c_char;
18313    while i < 63 && *src.add(i) != 0 { path[i] = *src.add(i); i += 1; }
18314    if fd < 0 { ERRNO!() = EBADF; return -1; }
18315    i += write_decimal(path.as_mut_ptr().add(i), fd as usize);
18316    path[i] = 0;
18317    crate::execve(path.as_ptr(), argv, envp)
18318}
18319
18320// ============================================================
18321// conf functions
18322// ============================================================
18323
18324#[no_mangle]
18325pub unsafe extern "C" fn confstr(name: i32, buf: *mut core::ffi::c_char, len: usize) -> usize {
18326    // _CS_PATH is the only value with content; the POSIX_V6/V7 option
18327    // strings are empty on Linux. Truncation follows snprintf semantics.
18328    let value: &[u8] = if name == 0 {
18329        b"/bin:/usr/bin"
18330    } else if (1..=37).contains(&name) {
18331        b""
18332    } else {
18333        ERRNO!() = EINVAL;
18334        return 0;
18335    };
18336    let need = value.len() + 1;
18337    if !buf.is_null() && len > 0 {
18338        let n = core::cmp::min(value.len(), len - 1);
18339        core::ptr::copy_nonoverlapping(value.as_ptr(), buf as *mut u8, n);
18340        *buf.add(n) = 0;
18341    }
18342    need
18343}
18344
18345#[no_mangle]
18346pub unsafe extern "C" fn pathconf(_path: *const core::ffi::c_char, name: i32) -> i64 {
18347    fpathconf(-1, name)
18348}
18349
18350#[no_mangle]
18351pub unsafe extern "C" fn fpathconf(_fd: i32, name: i32) -> i64 {
18352    // Same policy as musl's conf/fpathconf.c: the values are filesystem
18353    // independent defaults, so the path/fd argument is not consulted.
18354    match name {
18355        0 => 8,       // _PC_LINK_MAX (_POSIX_LINK_MAX)
18356        1 => 255,     // _PC_MAX_CANON
18357        2 => 255,     // _PC_MAX_INPUT
18358        3 => 255,     // _PC_NAME_MAX
18359        4 => 4096,    // _PC_PATH_MAX
18360        5 => 4096,    // _PC_PIPE_BUF
18361        6 => 1,       // _PC_CHOWN_RESTRICTED
18362        7 => 1,       // _PC_NO_TRUNC
18363        8 => 0,       // _PC_VDISABLE
18364        9 => 1,       // _PC_SYNC_IO
18365        10 => -1,     // _PC_ASYNC_IO
18366        11 => -1,     // _PC_PRIO_IO
18367        12 => -1,     // _PC_SOCK_MAXBUF
18368        13 => 64,     // _PC_FILESIZEBITS
18369        14..=17 => 4096, // _PC_REC_*_XFER_SIZE/_ALIGN
18370        18 => 4096,   // _PC_ALLOC_SIZE_MIN
18371        19 => -1,     // _PC_SYMLINK_MAX
18372        20 => 1,      // _PC_2_SYMLINKS
18373        _ => {
18374            ERRNO!() = EINVAL;
18375            -1
18376        }
18377    }
18378}
18379
18380// ============================================================
18381// exp10 functions
18382// ============================================================
18383
18384#[no_mangle]
18385pub unsafe extern "C" fn exp10(x: f64) -> f64 {
18386    libm::pow(10.0, x)
18387}
18388
18389#[no_mangle]
18390pub unsafe extern "C" fn exp10f(x: f32) -> f32 {
18391    libm::powf(10.0, x)
18392}
18393
18394// ============================================================
18395// memory functions
18396// ============================================================
18397
18398#[no_mangle]
18399pub unsafe extern "C" fn explicit_bzero(s: *mut u8, n: usize) {
18400    core::ptr::write_bytes(s, 0, n);
18401    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
18402}
18403
18404#[no_mangle]
18405pub unsafe extern "C" fn memccpy(dest: *mut u8, src: *const u8, c: i32, n: usize) -> *mut u8 {
18406    let mut i = 0;
18407    while i < n {
18408        let byte = *src.add(i);
18409        *dest.add(i) = byte;
18410        if byte == c as u8 {
18411            return dest.add(i + 1);
18412        }
18413        i += 1;
18414    }
18415    core::ptr::null_mut()
18416}
18417
18418// ============================================================
18419// *at functions
18420// ============================================================
18421
18422#[no_mangle]
18423pub unsafe extern "C" fn faccessat(dirfd: i32, pathname: *const core::ffi::c_char, mode: i32, flags: i32) -> i32 {
18424    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FACCESSAT, dirfd as i64, pathname as i64, mode as i64, flags as i64)) as i32
18425}
18426
18427#[no_mangle]
18428pub unsafe extern "C" fn fchmodat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32, flags: i32) -> i32 {
18429    if flags == 0 {
18430        return syscall_ret(<Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, pathname as i64, mode as i64, 0)) as i32;
18431    }
18432    if flags != 0x100 {
18433        // Only AT_SYMLINK_NOFOLLOW is defined for fchmodat.
18434        ERRNO!() = EINVAL;
18435        return -1;
18436    }
18437    syscall_ret(<Arch as Syscalls>::syscall4(sysno(452, 452), dirfd as i64, pathname as i64, mode as i64, flags as i64)) as i32
18438}
18439
18440#[no_mangle]
18441pub unsafe extern "C" fn fchownat(dirfd: i32, pathname: *const core::ffi::c_char, uid: u32, gid: u32, flags: i32) -> i32 {
18442    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
18443}
18444
18445#[no_mangle]
18446pub unsafe extern "C" fn linkat(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char, flags: i32) -> i32 {
18447    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
18448}
18449
18450#[no_mangle]
18451pub unsafe extern "C" fn mkdirat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18452    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, pathname as i64, mode as i64)) as i32
18453}
18454
18455#[no_mangle]
18456pub unsafe extern "C" fn mkfifoat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18457    mknodat(dirfd, pathname, mode | 0o010000, 0)
18458}
18459
18460#[no_mangle]
18461pub unsafe extern "C" fn mknodat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
18462    syscall_ret(<Arch as Syscalls>::syscall4(sysno(259, 33), dirfd as i64, pathname as i64, mode as i64, dev as i64)) as i32
18463}
18464
18465#[no_mangle]
18466pub unsafe extern "C" fn readlinkat(dirfd: i32, pathname: *const core::ffi::c_char, buf: *mut core::ffi::c_char, bufsiz: usize) -> isize {
18467    syscall_ret(<Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, pathname as i64, buf as i64, bufsiz as i64)) as isize
18468}
18469
18470#[no_mangle]
18471pub unsafe extern "C" fn renameat(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char) -> i32 {
18472    syscall_ret(<Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, 0)) as i32
18473}
18474
18475#[no_mangle]
18476pub unsafe extern "C" fn renameat2(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char, flags: u32) -> i32 {
18477    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
18478}
18479
18480#[no_mangle]
18481pub unsafe extern "C" fn symlinkat(target: *const core::ffi::c_char, newdirfd: i32, linkpath: *const core::ffi::c_char) -> i32 {
18482    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)) as i32
18483}
18484
18485#[no_mangle]
18486pub unsafe extern "C" fn unlinkat(dirfd: i32, pathname: *const core::ffi::c_char, flags: i32) -> i32 {
18487    syscall_ret(<Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, pathname as i64, flags as i64)) as i32
18488}
18489
18490#[no_mangle]
18491pub unsafe extern "C" fn utimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
18492    utimensat(AT_FDCWD, filename, times as *const timespec, 0)
18493}
18494
18495#[no_mangle]
18496pub unsafe extern "C" fn futimes(fd: i32, times: *const core::ffi::c_void) -> i32 {
18497    utimensat(fd, core::ptr::null(), times as *const timespec, 0)
18498}
18499
18500// ============================================================
18501// inotify functions
18502// ============================================================
18503
18504#[no_mangle]
18505pub unsafe extern "C" fn inotify_init() -> i32 {
18506    syscall_ret(<Arch as Syscalls>::syscall1(sysno(253, 26), 0)) as i32
18507}
18508
18509#[no_mangle]
18510pub unsafe extern "C" fn inotify_init1(flags: i32) -> i32 {
18511    syscall_ret(<Arch as Syscalls>::syscall1(sysno(294, 26), flags as i64)) as i32
18512}
18513
18514#[no_mangle]
18515pub unsafe extern "C" fn inotify_add_watch(fd: i32, pathname: *const core::ffi::c_char, mask: u32) -> i32 {
18516    syscall_ret(<Arch as Syscalls>::syscall3(sysno(254, 27), fd as i64, pathname as i64, mask as i64)) as i32
18517}
18518
18519#[no_mangle]
18520pub unsafe extern "C" fn inotify_rm_watch(fd: i32, wd: i32) -> i32 {
18521    syscall_ret(<Arch as Syscalls>::syscall2(sysno(255, 28), fd as i64, wd as i64)) as i32
18522}
18523
18524#[no_mangle]
18525pub unsafe extern "C" fn fanotify_init(flags: i32, event_f_flags: i32) -> i32 {
18526    syscall_ret(<Arch as Syscalls>::syscall2(sysno(300, 262), flags as i64, event_f_flags as i64)) as i32
18527}
18528
18529#[no_mangle]
18530pub unsafe extern "C" fn fanotify_mark(fd: i32, flags: i32, mask: u64, dirfd: i32, pathname: *const core::ffi::c_char) -> i32 {
18531    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
18532}
18533
18534// ============================================================
18535// ffs functions
18536// ============================================================
18537
18538#[no_mangle]
18539pub unsafe extern "C" fn ffs(x: i32) -> i32 {
18540    if x == 0 { return 0; }
18541    x.trailing_zeros() as i32 + 1
18542}
18543
18544#[no_mangle]
18545pub unsafe extern "C" fn ffsl(x: i64) -> i32 {
18546    if x == 0 { return 0; }
18547    x.trailing_zeros() as i32 + 1
18548}
18549
18550#[no_mangle]
18551pub unsafe extern "C" fn ffsll(x: i64) -> i32 {
18552    if x == 0 { return 0; }
18553    x.trailing_zeros() as i32 + 1
18554}
18555
18556// ============================================================
18557// More system functions
18558// ============================================================
18559
18560#[no_mangle]
18561pub unsafe extern "C" fn fchdir(fd: i32) -> i32 {
18562    syscall_ret(<Arch as Syscalls>::syscall1(SYS_FCHDIR, fd as i64)) as i32
18563}
18564
18565#[no_mangle]
18566pub unsafe extern "C" fn fchown(fd: i32, uid: u32, gid: u32) -> i32 {
18567    syscall_ret(<Arch as Syscalls>::syscall3(SYS_FCHOWN, fd as i64, uid as i64, gid as i64)) as i32
18568}
18569
18570#[no_mangle]
18571pub unsafe extern "C" fn fdopendir(fd: i32) -> *mut core::ffi::c_void {
18572    if fd < 0 { ERRNO!() = 9; return core::ptr::null_mut(); }
18573    dir_stream_new(fd)
18574}
18575
18576#[no_mangle]
18577pub unsafe extern "C" fn getdtablesize() -> i32 {
18578    let mut rlim: Rlimit = core::mem::zeroed();
18579    if getrlimit(RLIMIT_NOFILE, &mut rlim) == 0 {
18580        rlim.rlim_cur as i32
18581    } else {
18582        1024
18583    }
18584}
18585
18586#[no_mangle]
18587pub unsafe extern "C" fn getentropy(buf: *mut u8, buflen: usize) -> i32 {
18588    if buflen > 256 {
18589        ERRNO!() = EIO;
18590        return -1;
18591    }
18592    let mut pos = buf;
18593    let mut left = buflen;
18594    while left > 0 {
18595        let r = getrandom(pos, left, 0);
18596        if r < 0 {
18597            if ERRNO!() == EINTR {
18598                continue;
18599            }
18600            return -1;
18601        }
18602        pos = pos.add(r as usize);
18603        left -= r as usize;
18604    }
18605    0
18606}
18607
18608#[no_mangle]
18609pub unsafe extern "C" fn getrandom(buf: *mut u8, buflen: usize, flags: u32) -> isize {
18610    if let Some(r) = vgetrandom(buf, buflen, flags) {
18611        return if r < 0 {
18612            ERRNO!() = (-r) as c_int;
18613            -1
18614        } else {
18615            r
18616        };
18617    }
18618    let r = <Arch as Syscalls>::syscall3(sysno(318, 278), buf as i64, buflen as i64, flags as i64);
18619    if r < 0 {
18620        ERRNO!() = (-r) as c_int;
18621        -1
18622    } else {
18623        r as isize
18624    }
18625}
18626
18627#[no_mangle]
18628pub unsafe extern "C" fn killpg(pgrp: i32, sig: i32) -> i32 {
18629    syscall_ret(<Arch as Syscalls>::syscall2(SYS_KILL, -pgrp as i64, sig as i64)) as i32
18630}
18631
18632#[no_mangle]
18633pub unsafe extern "C" fn mkfifo(pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18634    mknod(pathname, 0o010000 | mode, 0)
18635}
18636
18637// ============================================================
18638// Memory allocation functions
18639// ============================================================
18640
18641#[no_mangle]
18642pub unsafe extern "C" fn aligned_alloc(alignment: usize, size: usize) -> *mut core::ffi::c_void {
18643    alloc_aligned_impl(alignment, size) as *mut core::ffi::c_void
18644}
18645
18646#[no_mangle]
18647pub unsafe extern "C" fn memalign(alignment: usize, size: usize) -> *mut core::ffi::c_void {
18648    alloc_aligned_impl(alignment, size) as *mut core::ffi::c_void
18649}
18650
18651#[no_mangle]
18652pub unsafe extern "C" fn posix_memalign(memptr: *mut *mut core::ffi::c_void, alignment: usize, size: usize) -> i32 {
18653    if memptr.is_null() { return EINVAL; }
18654    if alignment < core::mem::size_of::<*mut core::ffi::c_void>() || !alignment.is_power_of_two() {
18655        return EINVAL;
18656    }
18657    let p = alloc_aligned_impl(alignment, size);
18658    if p.is_null() { return ENOMEM; }
18659    *memptr = p as *mut core::ffi::c_void;
18660    0
18661}
18662
18663#[no_mangle]
18664pub unsafe extern "C" fn valloc(size: usize) -> *mut core::ffi::c_void {
18665    alloc_aligned_impl(PAGE, size) as *mut core::ffi::c_void
18666}
18667
18668// ============================================================
18669// glob functions
18670// ============================================================
18671
18672// ============================================================
18673// wordexp functions
18674// ============================================================
18675
18676// ============================================================
18677// gettext functions
18678// ============================================================
18679
18680#[no_mangle]
18681pub unsafe extern "C" fn gettext(msgid: *const core::ffi::c_char) -> *const core::ffi::c_char {
18682    msgid
18683}
18684
18685#[no_mangle]
18686pub unsafe extern "C" fn dgettext(_domainname: *const core::ffi::c_char, msgid: *const core::ffi::c_char) -> *const core::ffi::c_char {
18687    msgid
18688}
18689
18690#[no_mangle]
18691pub unsafe extern "C" fn dcgettext(_domainname: *const core::ffi::c_char, msgid: *const core::ffi::c_char, _category: i32) -> *const core::ffi::c_char {
18692    msgid
18693}
18694
18695#[no_mangle]
18696pub unsafe extern "C" fn ngettext(msgid1: *const core::ffi::c_char, msgid2: *const core::ffi::c_char, n: u64) -> *const core::ffi::c_char {
18697    if n == 1 { msgid1 } else { msgid2 }
18698}
18699
18700#[no_mangle]
18701pub 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 {
18702    if n == 1 { msgid1 } else { msgid2 }
18703}
18704
18705#[no_mangle]
18706pub 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 {
18707    if n == 1 { msgid1 } else { msgid2 }
18708}
18709
18710#[no_mangle]
18711pub unsafe extern "C" fn textdomain(domainname: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18712    static mut DOMAIN: [core::ffi::c_char; 256] = [0; 256];
18713    if domainname.is_null() { return DOMAIN.as_mut_ptr(); }
18714    let mut i = 0;
18715    while i < 255 && *domainname.add(i) != 0 {
18716        DOMAIN[i] = *domainname.add(i);
18717        i += 1;
18718    }
18719    DOMAIN[i] = 0;
18720    DOMAIN.as_mut_ptr()
18721}
18722
18723#[no_mangle]
18724pub unsafe extern "C" fn bindtextdomain(_domainname: *const core::ffi::c_char, dirname: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18725    dirname as *mut core::ffi::c_char
18726}
18727
18728#[no_mangle]
18729pub unsafe extern "C" fn bind_textdomain_codeset(_domainname: *const core::ffi::c_char, codeset: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18730    codeset as *mut core::ffi::c_char
18731}
18732
18733// ============================================================
18734// Wide string functions
18735// ============================================================
18736
18737#[no_mangle]
18738pub unsafe extern "C" fn wmemcpy(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18739    let mut i = 0;
18740    while i < n {
18741        *dest.add(i) = *src.add(i);
18742        i += 1;
18743    }
18744    dest
18745}
18746
18747#[no_mangle]
18748pub unsafe extern "C" fn wmemmove(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18749    if dest as usize <= src as usize {
18750        let mut i = 0;
18751        while i < n {
18752            *dest.add(i) = *src.add(i);
18753            i += 1;
18754        }
18755    } else {
18756        let mut i = n;
18757        while i > 0 {
18758            i -= 1;
18759            *dest.add(i) = *src.add(i);
18760        }
18761    }
18762    dest
18763}
18764
18765#[no_mangle]
18766pub unsafe extern "C" fn wmemset(dest: *mut u32, c: u32, n: usize) -> *mut u32 {
18767    let mut i = 0;
18768    while i < n {
18769        *dest.add(i) = c;
18770        i += 1;
18771    }
18772    dest
18773}
18774
18775#[no_mangle]
18776pub unsafe extern "C" fn wmemcmp(s1: *const u32, s2: *const u32, n: usize) -> i32 {
18777    let mut i = 0;
18778    while i < n {
18779        let c1 = *s1.add(i);
18780        let c2 = *s2.add(i);
18781        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
18782        i += 1;
18783    }
18784    0
18785}
18786
18787#[no_mangle]
18788pub unsafe extern "C" fn wmemchr(s: *const u32, c: u32, n: usize) -> *mut u32 {
18789    let mut i = 0;
18790    while i < n {
18791        if *s.add(i) == c { return s.add(i) as *mut u32; }
18792        i += 1;
18793    }
18794    core::ptr::null_mut()
18795}
18796
18797#[no_mangle]
18798pub unsafe extern "C" fn wcpcpy(dest: *mut u32, src: *const u32) -> *mut u32 {
18799    let mut i = 0;
18800    loop {
18801        let c = *src.add(i);
18802        *dest.add(i) = c;
18803        if c == 0 { return dest.add(i); }
18804        i += 1;
18805    }
18806}
18807
18808#[no_mangle]
18809pub unsafe extern "C" fn wcpncpy(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18810    let mut i = 0;
18811    while i < n {
18812        let c = *src.add(i);
18813        *dest.add(i) = c;
18814        if c == 0 { return dest.add(i); }
18815        i += 1;
18816    }
18817    dest.add(n)
18818}
18819
18820#[no_mangle]
18821pub unsafe extern "C" fn wprintf(fmt: *const wchar_t, args: ...) -> c_int {
18822    vfwprintf(stdout, fmt, args)
18823}
18824
18825#[no_mangle]
18826pub unsafe extern "C" fn vwprintf(fmt: *const wchar_t, ap: core::ffi::VaList) -> c_int {
18827    vfwprintf(stdout, fmt, ap)
18828}
18829
18830// ============================================================
18831// C32 functions
18832// ============================================================
18833
18834#[no_mangle]
18835pub unsafe extern "C" fn c16rtomb(s: *mut u8, c16: u16, ps: *mut core::ffi::c_void) -> usize {
18836    // UTF-16 to UTF-8, with surrogate pairs tracked in the mbstate.
18837    let state = ps as *mut u32;
18838    let saved: u32 = if state.is_null() { 0 } else { *state };
18839    if s.is_null() {
18840        if !state.is_null() { *state = 0; }
18841        return 1;
18842    }
18843    let cp: u32;
18844    if saved != 0 {
18845        if c16 < 0xdc00 || c16 > 0xdfff {
18846            if !state.is_null() { *state = 0; }
18847            ERRNO!() = EILSEQ;
18848            return !0usize;
18849        }
18850        cp = 0x10000 + (((saved - 0xd800) << 10) | ((c16 as u32) - 0xdc00));
18851        if !state.is_null() { *state = 0; }
18852    } else if c16 >= 0xd800 && c16 <= 0xdbff {
18853        if !state.is_null() { *state = c16 as u32; }
18854        return 0;
18855    } else if c16 >= 0xdc00 && c16 <= 0xdfff {
18856        ERRNO!() = EILSEQ;
18857        return !0usize;
18858    } else {
18859        cp = c16 as u32;
18860    }
18861    if cp < 0x80 {
18862        *s = cp as u8;
18863        1
18864    } else if cp < 0x800 {
18865        *s = (0xc0 | (cp >> 6)) as u8;
18866        *s.add(1) = (0x80 | (cp & 0x3f)) as u8;
18867        2
18868    } else if cp < 0x10000 {
18869        *s = (0xe0 | (cp >> 12)) as u8;
18870        *s.add(1) = (0x80 | ((cp >> 6) & 0x3f)) as u8;
18871        *s.add(2) = (0x80 | (cp & 0x3f)) as u8;
18872        3
18873    } else {
18874        *s = (0xf0 | (cp >> 18)) as u8;
18875        *s.add(1) = (0x80 | ((cp >> 12) & 0x3f)) as u8;
18876        *s.add(2) = (0x80 | ((cp >> 6) & 0x3f)) as u8;
18877        *s.add(3) = (0x80 | (cp & 0x3f)) as u8;
18878        4
18879    }
18880}
18881
18882#[no_mangle]
18883pub unsafe extern "C" fn c32rtomb(s: *mut u8, c32: u32, _ps: *mut core::ffi::c_void) -> usize {
18884    if s.is_null() { return 1; }
18885    if c32 > 0x10ffff || (c32 >= 0xd800 && c32 <= 0xdfff) {
18886        ERRNO!() = EILSEQ;
18887        return !0usize;
18888    }
18889    if c32 < 0x80 {
18890        *s = c32 as u8;
18891        1
18892    } else if c32 < 0x800 {
18893        *s = (0xc0 | (c32 >> 6)) as u8;
18894        *s.add(1) = (0x80 | (c32 & 0x3f)) as u8;
18895        2
18896    } else if c32 < 0x10000 {
18897        *s = (0xe0 | (c32 >> 12)) as u8;
18898        *s.add(1) = (0x80 | ((c32 >> 6) & 0x3f)) as u8;
18899        *s.add(2) = (0x80 | (c32 & 0x3f)) as u8;
18900        3
18901    } else {
18902        *s = (0xf0 | (c32 >> 18)) as u8;
18903        *s.add(1) = (0x80 | ((c32 >> 12) & 0x3f)) as u8;
18904        *s.add(2) = (0x80 | ((c32 >> 6) & 0x3f)) as u8;
18905        *s.add(3) = (0x80 | (c32 & 0x3f)) as u8;
18906        4
18907    }
18908}
18909
18910#[no_mangle]
18911pub unsafe extern "C" fn mbrtoc16(pc16: *mut u16, s: *const u8, n: usize, _ps: *mut core::ffi::c_void) -> usize {
18912    if s.is_null() { return 0; }
18913    if n == 0 { return 1; }
18914    let c = *s;
18915    if c == 0 { return 0; }
18916    if c < 0x80 {
18917        if !pc16.is_null() { *pc16 = c as u16; }
18918        return 1;
18919    }
18920    if c < 0xC2 { return 1; } // Invalid
18921    if c < 0xE0 {
18922        if n < 2 { return 1; }
18923        let c2 = *s.add(1);
18924        if (c2 & 0xC0) != 0x80 { return 1; }
18925        if !pc16.is_null() { *pc16 = ((((c & 0x1F) as u32) << 6) | ((c2 & 0x3F) as u32)) as u16; }
18926        return 2;
18927    }
18928    if c < 0xF0 {
18929        if n < 3 { return 1; }
18930        let c2 = *s.add(1);
18931        let c3 = *s.add(2);
18932        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 { return 1; }
18933        if !pc16.is_null() { *pc16 = ((((c & 0x0F) as u32) << 12) | (((c2 & 0x3F) as u32) << 6) | ((c3 & 0x3F) as u32)) as u16; }
18934        return 3;
18935    }
18936    1
18937}
18938
18939#[no_mangle]
18940pub unsafe extern "C" fn mbrtoc32(pc32: *mut u32, s: *const u8, n: usize, _ps: *mut core::ffi::c_void) -> usize {
18941    if s.is_null() { return 0; }
18942    if n == 0 { return 1; }
18943    let c = *s;
18944    if c == 0 { return 0; }
18945    if c < 0x80 {
18946        if !pc32.is_null() { *pc32 = c as u32; }
18947        return 1;
18948    }
18949    if c < 0xC2 { return 1; } // Invalid
18950    if c < 0xE0 {
18951        if n < 2 { return 1; }
18952        let c2 = *s.add(1);
18953        if (c2 & 0xC0) != 0x80 { return 1; }
18954        if !pc32.is_null() { *pc32 = (((c & 0x1F) as u32) << 6) | ((c2 & 0x3F) as u32); }
18955        return 2;
18956    }
18957    if c < 0xF0 {
18958        if n < 3 { return 1; }
18959        let c2 = *s.add(1);
18960        let c3 = *s.add(2);
18961        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 { return 1; }
18962        if !pc32.is_null() { *pc32 = (((c & 0x0F) as u32) << 12) | (((c2 & 0x3F) as u32) << 6) | ((c3 & 0x3F) as u32); }
18963        return 3;
18964    }
18965    if c < 0xF5 {
18966        if n < 4 { return 1; }
18967        let c2 = *s.add(1);
18968        let c3 = *s.add(2);
18969        let c4 = *s.add(3);
18970        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80 { return 1; }
18971        if !pc32.is_null() { *pc32 = (((c & 0x07) as u32) << 18) | (((c2 & 0x3F) as u32) << 12) | (((c3 & 0x3F) as u32) << 6) | ((c4 & 0x3F) as u32); }
18972        return 4;
18973    }
18974    1
18975}
18976
18977// ============================================================
18978// Shadow functions
18979// ============================================================
18980
18981
18982
18983
18984// ============================================================
18985// chown functions
18986// ============================================================
18987
18988#[no_mangle]
18989pub unsafe extern "C" fn chown(path: *const core::ffi::c_char, uid: u32, gid: u32) -> i32 {
18990    syscall_ret(<Arch as Syscalls>::syscall5(
18991        SYS_FCHOWNAT,
18992        AT_FDCWD as i64,
18993        path as i64,
18994        uid as i64,
18995        gid as i64,
18996        0,
18997    )) as i32
18998}
18999
19000#[no_mangle]
19001pub unsafe extern "C" fn lchown(path: *const core::ffi::c_char, uid: u32, gid: u32) -> i32 {
19002    syscall_ret(<Arch as Syscalls>::syscall5(
19003        SYS_FCHOWNAT,
19004        AT_FDCWD as i64,
19005        path as i64,
19006        uid as i64,
19007        gid as i64,
19008        0x100, // AT_SYMLINK_NOFOLLOW
19009    )) as i32
19010}
19011
19012// ============================================================
19013// chroot functions
19014// ============================================================
19015
19016#[no_mangle]
19017pub unsafe extern "C" fn chroot(path: *const core::ffi::c_char) -> i32 {
19018    syscall_ret(<Arch as Syscalls>::syscall1(SYS_CHROOT, path as i64)) as i32
19019}
19020
19021#[no_mangle]
19022pub unsafe extern "C" fn get_current_dir_name() -> *mut core::ffi::c_char {
19023    static mut BUF: [core::ffi::c_char; 4096] = [0; 4096];
19024    let r = getcwd(BUF.as_mut_ptr(), 4096);
19025    if r.is_null() { core::ptr::null_mut() } else { BUF.as_mut_ptr() }
19026}
19027
19028// ============================================================
19029// I/O functions
19030// ============================================================
19031
19032#[no_mangle]
19033pub unsafe extern "C" fn creat(pathname: *const core::ffi::c_char, mode: u32) -> i32 {
19034    // O_WRONLY | O_CREAT | O_TRUNC. The previous flags included O_EXCL.
19035    open(pathname, 1 | 0o100 | 0o1000, mode as i32)
19036}
19037
19038#[no_mangle]
19039pub unsafe extern "C" fn openat(dirfd: i32, pathname: *const core::ffi::c_char, flags: i32, mode: u32) -> i32 {
19040    syscall_ret(<Arch as Syscalls>::syscall4(SYS_OPENAT, dirfd as i64, pathname as i64, flags as i64, mode as i64)) as i32
19041}
19042
19043#[no_mangle]
19044pub unsafe extern "C" fn pwrite(fd: i32, buf: *const u8, count: usize, offset: i64) -> isize {
19045    syscall_ret(<Arch as Syscalls>::syscall4(sysno(18, 68), fd as i64, buf as i64, count as i64, offset)) as isize
19046}
19047
19048#[no_mangle]
19049pub unsafe extern "C" fn readv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32) -> isize {
19050    syscall_ret(<Arch as Syscalls>::syscall3(sysno(19, 65), fd as i64, iov as i64, iovcnt as i64)) as isize
19051}
19052
19053#[no_mangle]
19054pub unsafe extern "C" fn writev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32) -> isize {
19055    syscall_ret(<Arch as Syscalls>::syscall3(sysno(20, 66), fd as i64, iov as i64, iovcnt as i64)) as isize
19056}
19057
19058// ============================================================
19059// Lock functions
19060// ============================================================
19061
19062#[no_mangle]
19063pub unsafe extern "C" fn flock(fd: i32, operation: i32) -> i32 {
19064    syscall_ret(<Arch as Syscalls>::syscall2(SYS_FLOCK, fd as i64, operation as i64)) as i32
19065}
19066
19067#[repr(C)]
19068struct FlockArg {
19069    l_type: i16,
19070    l_whence: i16,
19071    l_start: i64,
19072    l_len: i64,
19073    l_pid: i32,
19074}
19075
19076#[no_mangle]
19077pub unsafe extern "C" fn lockf(fd: i32, cmd: i32, len: i64) -> i32 {
19078    // POSIX lockf commands map onto fcntl record locks relative to the
19079    // current file offset.
19080    const F_RDLCK: i16 = 0;
19081    const F_WRLCK: i16 = 1;
19082    const F_UNLCK: i16 = 2;
19083    const F_SETLK: i64 = 6;
19084    const F_SETLKW: i64 = 7;
19085    const SEEK_CUR: i16 = 1;
19086    let (l_type, wait) = match cmd {
19087        0 => (F_UNLCK, false), // F_ULOCK
19088        1 => (F_WRLCK, true),  // F_LOCK
19089        2 => (F_WRLCK, false), // F_TLOCK
19090        3 => (F_RDLCK, false), // F_TEST
19091        _ => {
19092            ERRNO!() = EINVAL;
19093            return -1;
19094        }
19095    };
19096    let fl = FlockArg { l_type, l_whence: SEEK_CUR, l_start: 0, l_len: len, l_pid: 0 };
19097    let r = <Arch as Syscalls>::syscall3(
19098        SYS_FCNTL,
19099        fd as i64,
19100        if wait { F_SETLKW } else { F_SETLK },
19101        &fl as *const FlockArg as i64,
19102    );
19103    syscall_ret(r) as c_int
19104}
19105
19106// ============================================================
19107// Hostname/login functions
19108// ============================================================
19109
19110#[no_mangle]
19111pub unsafe extern "C" fn getdomainname(name: *mut core::ffi::c_char, len: usize) -> i32 {
19112    if name.is_null() || len == 0 {
19113        ERRNO!() = EINVAL;
19114        return -1;
19115    }
19116    let mut uts: UtsName = core::mem::zeroed();
19117    let r = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
19118    if r < 0 {
19119        ERRNO!() = (-r) as c_int;
19120        return -1;
19121    }
19122    let mut n = 0usize;
19123    while n < uts.domainname.len() && uts.domainname[n] != 0 { n += 1; }
19124    if n >= len {
19125        ERRNO!() = EINVAL;
19126        return -1;
19127    }
19128    core::ptr::copy_nonoverlapping(uts.domainname.as_ptr(), name as *mut u8, n);
19129    *name.add(n) = 0;
19130    0
19131}
19132
19133#[no_mangle]
19134pub unsafe extern "C" fn setdomainname(name: *const core::ffi::c_char, len: usize) -> i32 {
19135    syscall_ret(<Arch as Syscalls>::syscall2(sysno(171, 162), name as i64, len as i64)) as i32
19136}
19137
19138#[no_mangle]
19139pub unsafe extern "C" fn sethostname(name: *const core::ffi::c_char, len: usize) -> i32 {
19140    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)) as i32
19141}
19142
19143#[no_mangle]
19144pub unsafe extern "C" fn getlogin_r(name: *mut core::ffi::c_char, bufsize: usize) -> i32 {
19145    let user = getlogin();
19146    if user.is_null() { return ENXIO; }
19147    let len = crate::strlen(user);
19148    if len >= bufsize { return 34; } // ERANGE
19149    core::ptr::copy_nonoverlapping(user, name, len + 1);
19150    0
19151}
19152
19153#[no_mangle]
19154pub unsafe extern "C" fn cuserid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
19155    let user = crate::getenv(b"USER\0".as_ptr() as *const core::ffi::c_char);
19156    if user.is_null() { return core::ptr::null_mut(); }
19157    if s.is_null() {
19158        static mut BUF: [core::ffi::c_char; 32] = [0; 32];
19159        let mut i = 0;
19160        while i < 31 && *user.add(i) != 0 { BUF[i] = *user.add(i); i += 1; }
19161        BUF[i] = 0;
19162        BUF.as_mut_ptr()
19163    } else {
19164        let mut i = 0;
19165        while i < 31 && *user.add(i) != 0 { *s.add(i) = *user.add(i); i += 1; }
19166        *s.add(i) = 0;
19167        s
19168    }
19169}
19170
19171// ============================================================
19172// Group and passwd functions
19173// ============================================================
19174
19175#[repr(C)]
19176#[derive(Copy, Clone)]
19177pub struct Passwd {
19178    pub pw_name: *mut c_char,
19179    pub pw_passwd: *mut c_char,
19180    pub pw_uid: u32,
19181    pub pw_gid: u32,
19182    pub pw_gecos: *mut c_char,
19183    pub pw_dir: *mut c_char,
19184    pub pw_shell: *mut c_char,
19185}
19186
19187#[repr(C)]
19188#[derive(Copy, Clone)]
19189pub struct Group {
19190    pub gr_name: *mut c_char,
19191    pub gr_passwd: *mut c_char,
19192    pub gr_gid: u32,
19193    pub gr_mem: *mut *mut c_char,
19194}
19195
19196static mut PWD_ENT: Passwd = Passwd {
19197    pw_name: core::ptr::null_mut(), pw_passwd: core::ptr::null_mut(),
19198    pw_uid: 0, pw_gid: 0, pw_gecos: core::ptr::null_mut(),
19199    pw_dir: core::ptr::null_mut(), pw_shell: core::ptr::null_mut(),
19200};
19201static mut PWD_LINE: *mut c_char = core::ptr::null_mut();
19202static mut PWD_LINE_CAP: usize = 0;
19203static mut PWD_BUF: *mut c_char = core::ptr::null_mut();
19204static mut PWD_BUF_CAP: usize = 0;
19205static mut PWD_FILE: *mut FILE = core::ptr::null_mut();
19206
19207unsafe fn ensure_pwd_buf(n: usize) -> bool {
19208    if n <= PWD_BUF_CAP {
19209        return true;
19210    }
19211    let mut cap = if PWD_BUF_CAP == 0 { 1024 } else { PWD_BUF_CAP };
19212    while cap < n {
19213        cap *= 2;
19214    }
19215    let p = realloc(PWD_BUF as *mut c_void, cap) as *mut c_char;
19216    if p.is_null() {
19217        return false;
19218    }
19219    PWD_BUF = p;
19220    PWD_BUF_CAP = cap;
19221    true
19222}
19223
19224static mut GRP_ENT: Group = Group {
19225    gr_name: core::ptr::null_mut(), gr_passwd: core::ptr::null_mut(),
19226    gr_gid: 0, gr_mem: core::ptr::null_mut(),
19227};
19228static mut GRP_LINE: *mut c_char = core::ptr::null_mut();
19229static mut GRP_LINE_CAP: usize = 0;
19230static mut GRP_BUF: *mut c_char = core::ptr::null_mut();
19231static mut GRP_BUF_CAP: usize = 0;
19232static mut GRP_MEM: *mut *mut c_char = core::ptr::null_mut();
19233static mut GRP_MEM_CAP: usize = 0;
19234static mut GRP_FILE: *mut FILE = core::ptr::null_mut();
19235
19236unsafe fn ensure_grp_buf(n: usize) -> bool {
19237    if n <= GRP_BUF_CAP {
19238        return true;
19239    }
19240    let mut cap = if GRP_BUF_CAP == 0 { 2048 } else { GRP_BUF_CAP };
19241    while cap < n {
19242        cap *= 2;
19243    }
19244    let p = realloc(GRP_BUF as *mut c_void, cap) as *mut c_char;
19245    if p.is_null() {
19246        return false;
19247    }
19248    GRP_BUF = p;
19249    GRP_BUF_CAP = cap;
19250    true
19251}
19252
19253unsafe fn ensure_grp_mem(n: usize) -> bool {
19254    if n <= GRP_MEM_CAP {
19255        return true;
19256    }
19257    let mut cap = if GRP_MEM_CAP == 0 { 32 } else { GRP_MEM_CAP };
19258    while cap < n {
19259        cap *= 2;
19260    }
19261    let p = realloc(
19262        GRP_MEM as *mut c_void,
19263        cap * core::mem::size_of::<*mut c_char>(),
19264    ) as *mut *mut c_char;
19265    if p.is_null() {
19266        return false;
19267    }
19268    GRP_MEM = p;
19269    GRP_MEM_CAP = cap;
19270    true
19271}
19272
19273/// Copy colon-separated fields from `line` into `buf`, NUL-terminating each.
19274/// Returns the number of fields found, or None when `buf` is too small.
19275unsafe fn split_colon_fields(
19276    line: *const c_char,
19277    buf: *mut c_char,
19278    buflen: usize,
19279    fields: &mut [*mut c_char],
19280) -> Option<usize> {
19281    let mut src = line;
19282    let mut o = 0usize;
19283    let mut n = 0usize;
19284    while n < fields.len() {
19285        let start = o;
19286        while *src != 0 && *src != b':' as c_char {
19287            if o + 1 >= buflen { return None; }
19288            *buf.add(o) = *src;
19289            o += 1;
19290            src = src.add(1);
19291        }
19292        *buf.add(o) = 0;
19293        o += 1;
19294        fields[n] = buf.add(start);
19295        n += 1;
19296        if *src == 0 { break; }
19297        src = src.add(1);
19298    }
19299    Some(n)
19300}
19301
19302unsafe fn parse_passwd(line: *const c_char, ent: *mut Passwd, buf: *mut c_char, buflen: usize) -> bool {
19303    let mut fields: [*mut c_char; 7] = [core::ptr::null_mut(); 7];
19304    let n = match split_colon_fields(line, buf, buflen, &mut fields) {
19305        Some(n) => n,
19306        None => return false,
19307    };
19308    if n < 7 { return false; }
19309    (*ent).pw_name = fields[0];
19310    (*ent).pw_passwd = fields[1];
19311    (*ent).pw_uid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
19312    (*ent).pw_gid = crate::strtol(fields[3], core::ptr::null_mut(), 10) as u32;
19313    (*ent).pw_gecos = fields[4];
19314    (*ent).pw_dir = fields[5];
19315    (*ent).pw_shell = fields[6];
19316    true
19317}
19318
19319unsafe fn parse_group(line: *const c_char, ent: *mut Group, buf: *mut c_char, buflen: usize) -> bool {
19320    let mut fields: [*mut c_char; 4] = [core::ptr::null_mut(); 4];
19321    let n = match split_colon_fields(line, buf, buflen, &mut fields) {
19322        Some(n) => n,
19323        None => return false,
19324    };
19325    if n < 4 { return false; }
19326    (*ent).gr_name = fields[0];
19327    (*ent).gr_passwd = fields[1];
19328    (*ent).gr_gid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
19329    let mut count = 1usize;
19330    let mut m = fields[3];
19331    while *m != 0 {
19332        if *m == b',' as c_char { count += 1; }
19333        m = m.add(1);
19334    }
19335    if !ensure_grp_mem(count + 1) { return false; }
19336    let mut mi = 0usize;
19337    m = fields[3];
19338    if *m != 0 {
19339        loop {
19340            *GRP_MEM.add(mi) = m;
19341            mi += 1;
19342            while *m != 0 && *m != b',' as c_char { m = m.add(1); }
19343            if *m == 0 { break; }
19344            *m = 0;
19345            m = m.add(1);
19346        }
19347    }
19348    *GRP_MEM.add(mi) = core::ptr::null_mut();
19349    (*ent).gr_mem = GRP_MEM;
19350    true
19351}
19352
19353unsafe fn scan_passwd(mut matches: impl FnMut(*const Passwd) -> bool) -> *mut Passwd {
19354    setpwent();
19355    loop {
19356        let p = getpwent();
19357        if p.is_null() { break; }
19358        if matches(p) {
19359            endpwent();
19360            return p;
19361        }
19362    }
19363    endpwent();
19364    core::ptr::null_mut()
19365}
19366
19367#[no_mangle]
19368pub unsafe extern "C" fn getpwnam(name: *const c_char) -> *mut Passwd {
19369    if name.is_null() { return core::ptr::null_mut(); }
19370    scan_passwd(|p| crate::strcmp((*p).pw_name as *const u8, name as *const u8) == 0)
19371}
19372
19373#[no_mangle]
19374pub unsafe extern "C" fn getpwuid(uid: u32) -> *mut Passwd {
19375    scan_passwd(|p| (*p).pw_uid == uid)
19376}
19377
19378#[no_mangle]
19379pub unsafe extern "C" fn setpwent() {
19380    endpwent();
19381    PWD_FILE = crate::fopen(b"/etc/passwd\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19382}
19383
19384#[no_mangle]
19385pub unsafe extern "C" fn getpwent() -> *mut Passwd {
19386    if PWD_FILE.is_null() { setpwent(); if PWD_FILE.is_null() { return core::ptr::null_mut(); } }
19387    loop {
19388        let n = crate::getline(&raw mut PWD_LINE, &raw mut PWD_LINE_CAP, PWD_FILE);
19389        if n < 0 { return core::ptr::null_mut(); }
19390        let mut len = n as usize;
19391        if len > 0 && *PWD_LINE.add(len - 1) == b'\n' as c_char {
19392            *PWD_LINE.add(len - 1) = 0;
19393            len -= 1;
19394        }
19395        let need = len + 1;
19396        if !ensure_pwd_buf(need) { return core::ptr::null_mut(); }
19397        if parse_passwd(PWD_LINE, &raw mut PWD_ENT, PWD_BUF, need) {
19398            return &raw mut PWD_ENT;
19399        }
19400    }
19401}
19402
19403#[no_mangle]
19404pub unsafe extern "C" fn endpwent() {
19405    if !PWD_FILE.is_null() { crate::fclose(PWD_FILE); PWD_FILE = core::ptr::null_mut(); }
19406}
19407
19408unsafe fn getpw_r_inner(
19409    name: *const c_char,
19410    uid: Option<u32>,
19411    pwd: *mut Passwd,
19412    buf: *mut c_char,
19413    buflen: usize,
19414    result: *mut *mut Passwd,
19415) -> c_int {
19416    if pwd.is_null() || buf.is_null() || result.is_null() || (uid.is_none() && name.is_null()) {
19417        return EINVAL;
19418    }
19419    *result = core::ptr::null_mut();
19420    let f = crate::fopen(b"/etc/passwd\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19421    if f.is_null() { return ERRNO!(); }
19422    let mut line: *mut c_char = core::ptr::null_mut();
19423    let mut cap: usize = 0;
19424    let mut err = 0;
19425    loop {
19426        let n = crate::getline(&raw mut line, &raw mut cap, f);
19427        if n < 0 { break; }
19428        let mut len = n as usize;
19429        if len > 0 && *line.add(len - 1) == b'\n' as c_char {
19430            *line.add(len - 1) = 0;
19431            len -= 1;
19432        }
19433        if len + 1 > buflen {
19434            err = ERANGE;
19435            break;
19436        }
19437        if parse_passwd(line, pwd, buf, buflen) {
19438            let hit = if let Some(uid) = uid {
19439                (*pwd).pw_uid == uid
19440            } else {
19441                crate::strcmp((*pwd).pw_name as *const u8, name as *const u8) == 0
19442            };
19443            if hit {
19444                *result = pwd;
19445                break;
19446            }
19447        }
19448    }
19449    crate::free(line as *mut c_void);
19450    crate::fclose(f);
19451    err
19452}
19453
19454#[no_mangle]
19455pub 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 {
19456    getpw_r_inner(name, None, pwd, buf, buflen, result)
19457}
19458
19459#[no_mangle]
19460pub unsafe extern "C" fn getpwuid_r(uid: u32, pwd: *mut Passwd, buf: *mut c_char, buflen: usize, result: *mut *mut Passwd) -> c_int {
19461    getpw_r_inner(core::ptr::null(), Some(uid), pwd, buf, buflen, result)
19462}
19463
19464#[no_mangle]
19465pub unsafe extern "C" fn fgetpwent(f: *mut FILE) -> *mut Passwd {
19466    if f.is_null() { return core::ptr::null_mut(); }
19467    loop {
19468        let n = crate::getline(&raw mut PWD_LINE, &raw mut PWD_LINE_CAP, f);
19469        if n < 0 { return core::ptr::null_mut(); }
19470        let mut len = n as usize;
19471        if len > 0 && *PWD_LINE.add(len - 1) == b'\n' as c_char {
19472            *PWD_LINE.add(len - 1) = 0;
19473            len -= 1;
19474        }
19475        let need = len + 1;
19476        if !ensure_pwd_buf(need) { return core::ptr::null_mut(); }
19477        if parse_passwd(PWD_LINE, &raw mut PWD_ENT, PWD_BUF, need) {
19478            return &raw mut PWD_ENT;
19479        }
19480    }
19481}
19482
19483#[no_mangle]
19484pub unsafe extern "C" fn putpwent(f: *mut FILE, p: *const Passwd) -> c_int {
19485    if f.is_null() || p.is_null() { return -1; }
19486    crate::fprintf(f, b"%s:%s:%u:%u:%s:%s:%s\n\0".as_ptr() as *const c_char,
19487        (*p).pw_name, (*p).pw_passwd, (*p).pw_uid, (*p).pw_gid,
19488        (*p).pw_gecos, (*p).pw_dir, (*p).pw_shell)
19489}
19490
19491unsafe fn scan_group(mut matches: impl FnMut(*const Group) -> bool) -> *mut Group {
19492    setgrent();
19493    loop {
19494        let g = getgrent();
19495        if g.is_null() { break; }
19496        if matches(g) {
19497            endgrent();
19498            return g;
19499        }
19500    }
19501    endgrent();
19502    core::ptr::null_mut()
19503}
19504
19505#[no_mangle]
19506pub unsafe extern "C" fn getgrnam(name: *const c_char) -> *mut Group {
19507    if name.is_null() { return core::ptr::null_mut(); }
19508    scan_group(|g| crate::strcmp((*g).gr_name as *const u8, name as *const u8) == 0)
19509}
19510
19511#[no_mangle]
19512pub unsafe extern "C" fn getgrgid(gid: u32) -> *mut Group {
19513    scan_group(|g| (*g).gr_gid == gid)
19514}
19515
19516#[no_mangle]
19517pub unsafe extern "C" fn setgrent() {
19518    endgrent();
19519    GRP_FILE = crate::fopen(b"/etc/group\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19520}
19521
19522#[no_mangle]
19523pub unsafe extern "C" fn getgrent() -> *mut Group {
19524    if GRP_FILE.is_null() { setgrent(); if GRP_FILE.is_null() { return core::ptr::null_mut(); } }
19525    loop {
19526        let n = crate::getline(&raw mut GRP_LINE, &raw mut GRP_LINE_CAP, GRP_FILE);
19527        if n < 0 { return core::ptr::null_mut(); }
19528        let mut len = n as usize;
19529        if len > 0 && *GRP_LINE.add(len - 1) == b'\n' as c_char {
19530            *GRP_LINE.add(len - 1) = 0;
19531            len -= 1;
19532        }
19533        let need = len + 1;
19534        if !ensure_grp_buf(need) { return core::ptr::null_mut(); }
19535        if parse_group(GRP_LINE, &raw mut GRP_ENT, GRP_BUF, need) {
19536            return &raw mut GRP_ENT;
19537        }
19538    }
19539}
19540
19541#[no_mangle]
19542pub unsafe extern "C" fn endgrent() {
19543    if !GRP_FILE.is_null() { crate::fclose(GRP_FILE); GRP_FILE = core::ptr::null_mut(); }
19544}
19545
19546// Parses one group line into the caller's buffer.  The member pointer array
19547// is placed in the same buffer, after the strings, aligned to pointer size.
19548unsafe fn parse_group_r(line: *const c_char, ent: *mut Group, buf: *mut c_char, buflen: usize) -> c_int {
19549    const OK: c_int = 0;
19550    const BAD: c_int = -1;
19551    const NOSPACE: c_int = -2;
19552
19553    let mut fields: [*mut c_char; 4] = [core::ptr::null_mut(); 4];
19554    let n = match split_colon_fields(line, buf, buflen, &mut fields) {
19555        Some(n) => n,
19556        None => return NOSPACE,
19557    };
19558    if n < 4 { return BAD; }
19559
19560    let mut count = 1usize;
19561    let mut m = fields[3];
19562    while *m != 0 {
19563        if *m == b',' as c_char { count += 1; }
19564        m = m.add(1);
19565    }
19566    // The member pointer array lives after the copied strings in `buf`.
19567    let ptr_size = core::mem::size_of::<*mut c_char>();
19568    let base = buf as usize;
19569    let o = crate::strlen(buf) + 1;
19570    let aligned = match base
19571        .checked_add(o)
19572        .and_then(|v| v.checked_add(ptr_size - 1))
19573    {
19574        Some(v) => v & !(ptr_size - 1),
19575        None => return NOSPACE,
19576    };
19577    let ptr_bytes = match (count + 1).checked_mul(ptr_size) {
19578        Some(v) => v,
19579        None => return NOSPACE,
19580    };
19581    let need = match aligned.checked_sub(base).and_then(|v| v.checked_add(ptr_bytes)) {
19582        Some(v) => v,
19583        None => return NOSPACE,
19584    };
19585    if need > buflen { return NOSPACE; }
19586
19587    let mem = aligned as *mut *mut c_char;
19588    let mut mi = 0usize;
19589    m = fields[3];
19590    if *m != 0 {
19591        loop {
19592            *mem.add(mi) = m;
19593            mi += 1;
19594            while *m != 0 && *m != b',' as c_char { m = m.add(1); }
19595            if *m == 0 { break; }
19596            *m = 0;
19597            m = m.add(1);
19598        }
19599    }
19600    *mem.add(mi) = core::ptr::null_mut();
19601
19602    (*ent).gr_name = fields[0];
19603    (*ent).gr_passwd = fields[1];
19604    (*ent).gr_gid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
19605    (*ent).gr_mem = mem;
19606    OK
19607}
19608
19609unsafe fn getgr_r_inner(
19610    name: *const c_char,
19611    gid: Option<u32>,
19612    grp: *mut Group,
19613    buf: *mut c_char,
19614    buflen: usize,
19615    result: *mut *mut Group,
19616) -> c_int {
19617    if grp.is_null() || buf.is_null() || result.is_null() || (gid.is_none() && name.is_null()) {
19618        return EINVAL;
19619    }
19620    *result = core::ptr::null_mut();
19621    let f = crate::fopen(b"/etc/group\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19622    if f.is_null() { return ERRNO!(); }
19623    let mut line: *mut c_char = core::ptr::null_mut();
19624    let mut cap: usize = 0;
19625    let mut err = 0;
19626    loop {
19627        let n = crate::getline(&raw mut line, &raw mut cap, f);
19628        if n < 0 { break; }
19629        if n > 0 && *line.add(n as usize - 1) == b'\n' as c_char {
19630            *line.add(n as usize - 1) = 0;
19631        }
19632        let r = parse_group_r(line, grp, buf, buflen);
19633        if r == -2 {
19634            err = ERANGE;
19635            break;
19636        }
19637        if r == 0 {
19638            let hit = if let Some(gid) = gid {
19639                (*grp).gr_gid == gid
19640            } else {
19641                crate::strcmp((*grp).gr_name as *const u8, name as *const u8) == 0
19642            };
19643            if hit {
19644                *result = grp;
19645                break;
19646            }
19647        }
19648    }
19649    crate::free(line as *mut c_void);
19650    crate::fclose(f);
19651    err
19652}
19653
19654#[no_mangle]
19655pub 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 {
19656    getgr_r_inner(name, None, grp, buf, buflen, result)
19657}
19658
19659#[no_mangle]
19660pub unsafe extern "C" fn getgrgid_r(gid: u32, grp: *mut Group, buf: *mut c_char, buflen: usize, result: *mut *mut Group) -> c_int {
19661    getgr_r_inner(core::ptr::null(), Some(gid), grp, buf, buflen, result)
19662}
19663
19664#[no_mangle]
19665pub unsafe extern "C" fn fgetgrent(f: *mut FILE) -> *mut Group {
19666    if f.is_null() { return core::ptr::null_mut(); }
19667    loop {
19668        let n = crate::getline(&raw mut GRP_LINE, &raw mut GRP_LINE_CAP, f);
19669        if n < 0 { return core::ptr::null_mut(); }
19670        let mut len = n as usize;
19671        if len > 0 && *GRP_LINE.add(len - 1) == b'\n' as c_char {
19672            *GRP_LINE.add(len - 1) = 0;
19673            len -= 1;
19674        }
19675        let need = len + 1;
19676        if !ensure_grp_buf(need) { return core::ptr::null_mut(); }
19677        if parse_group(GRP_LINE, &raw mut GRP_ENT, GRP_BUF, need) {
19678            return &raw mut GRP_ENT;
19679        }
19680    }
19681}
19682
19683#[no_mangle]
19684pub unsafe extern "C" fn putgrent(f: *mut FILE, g: *const Group) -> c_int {
19685    if f.is_null() || g.is_null() { return -1; }
19686    crate::fprintf(f, b"%s:%s:%u:\0".as_ptr() as *const c_char, (*g).gr_name, (*g).gr_passwd, (*g).gr_gid);
19687    if !(*g).gr_mem.is_null() {
19688        let mut i = 0;
19689        while !(*(*g).gr_mem.add(i)).is_null() {
19690            if i > 0 { crate::fputc(b',' as c_int, f); }
19691            crate::fputs(*(*g).gr_mem.add(i), f);
19692            i += 1;
19693        }
19694    }
19695    crate::fputc(b'\n' as c_int, f);
19696    0
19697}
19698
19699// ============================================================
19700// User/group functions
19701// ============================================================
19702
19703#[no_mangle]
19704pub unsafe extern "C" fn setgroups(ngroups: usize, gidset: *const u32) -> i32 {
19705    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETGROUPS, ngroups as i64, gidset as i64)) as i32
19706}
19707
19708#[no_mangle]
19709pub unsafe extern "C" fn setresuid(ruid: u32, euid: u32, suid: u32) -> i32 {
19710    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETRESUID, ruid as i64, euid as i64, suid as i64)) as i32
19711}
19712
19713#[no_mangle]
19714pub unsafe extern "C" fn setresgid(rgid: u32, egid: u32, sgid: u32) -> i32 {
19715    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETRESGID, rgid as i64, egid as i64, sgid as i64)) as i32
19716}
19717
19718#[no_mangle]
19719pub unsafe extern "C" fn getresuid(ruid: *mut u32, euid: *mut u32, suid: *mut u32) -> i32 {
19720    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETRESUID, ruid as i64, euid as i64, suid as i64)) as i32
19721}
19722
19723#[no_mangle]
19724pub unsafe extern "C" fn getresgid(rgid: *mut u32, egid: *mut u32, sgid: *mut u32) -> i32 {
19725    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETRESGID, rgid as i64, egid as i64, sgid as i64)) as i32
19726}
19727
19728// ============================================================
19729// Socket functions
19730// ============================================================
19731
19732// musl's public struct msghdr uses 32-bit msg_iovlen/msg_controllen followed
19733// by padding on 64-bit little-endian. The kernel reads 64-bit fields, so the
19734// padding must be zero; callers (nginx, for example) do not initialize it.
19735#[repr(C)]
19736struct KernelMsgHdr {
19737    msg_name: *mut c_void,
19738    msg_namelen: u32,
19739    __pad0: u32,
19740    msg_iov: *mut c_void,
19741    msg_iovlen: u64,
19742    msg_control: *mut c_void,
19743    msg_controllen: u64,
19744    msg_flags: u32,
19745    __pad1: u32,
19746}
19747
19748#[repr(C)]
19749struct UserMsgHdr {
19750    msg_name: *mut c_void,
19751    msg_namelen: u32,
19752    msg_iov: *mut c_void,
19753    msg_iovlen: i32,
19754    __pad1: i32,
19755    msg_control: *mut c_void,
19756    msg_controllen: u32,
19757    __pad2: i32,
19758    msg_flags: i32,
19759}
19760
19761unsafe fn msg_to_kernel(msg: *const UserMsgHdr, out: &mut KernelMsgHdr) {
19762    *out = KernelMsgHdr {
19763        msg_name: (*msg).msg_name,
19764        msg_namelen: (*msg).msg_namelen,
19765        __pad0: 0,
19766        msg_iov: (*msg).msg_iov,
19767        msg_iovlen: (*msg).msg_iovlen as u32 as u64,
19768        msg_control: (*msg).msg_control,
19769        msg_controllen: (*msg).msg_controllen as u64,
19770        msg_flags: (*msg).msg_flags as u32,
19771        __pad1: 0,
19772    };
19773}
19774
19775#[no_mangle]
19776pub unsafe extern "C" fn sendmsg(fd: i32, msg: *const core::ffi::c_void, flags: i32) -> isize {
19777    if msg.is_null() {
19778        ERRNO!() = EINVAL;
19779        return -1;
19780    }
19781    let mut k: KernelMsgHdr = core::mem::zeroed();
19782    msg_to_kernel(msg as *const UserMsgHdr, &mut k);
19783    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SENDMSG, fd as i64, &k as *const KernelMsgHdr as i64, flags as i64)) as isize
19784}
19785
19786#[no_mangle]
19787pub unsafe extern "C" fn recvmsg(fd: i32, msg: *mut core::ffi::c_void, flags: i32) -> isize {
19788    if msg.is_null() {
19789        ERRNO!() = EINVAL;
19790        return -1;
19791    }
19792    let user = msg as *mut UserMsgHdr;
19793    let mut k: KernelMsgHdr = core::mem::zeroed();
19794    msg_to_kernel(user, &mut k);
19795    let r = syscall_ret(<Arch as Syscalls>::syscall3(SYS_RECVMSG, fd as i64, &mut k as *mut KernelMsgHdr as i64, flags as i64));
19796    (*user).msg_flags = k.msg_flags as i32;
19797    (*user).msg_controllen = k.msg_controllen as u32;
19798    r as isize
19799}
19800
19801#[no_mangle]
19802pub unsafe extern "C" fn sendmmsg(fd: i32, msgvec: *mut core::ffi::c_void, vlen: u32, flags: i32) -> i32 {
19803    syscall_ret(<Arch as Syscalls>::syscall4(sysno(307, 269), fd as i64, msgvec as i64, vlen as i64, flags as i64)) as i32
19804}
19805
19806#[no_mangle]
19807pub unsafe extern "C" fn recvmmsg(fd: i32, msgvec: *mut core::ffi::c_void, vlen: u32, flags: i32, timeout: *mut core::ffi::c_void) -> i32 {
19808    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
19809}
19810
19811#[no_mangle]
19812pub unsafe extern "C" fn getpeername(fd: i32, addr: *mut core::ffi::c_void, addrlen: *mut u32) -> i32 {
19813    syscall_ret(<Arch as Syscalls>::syscall3(sysno(52, 205), fd as i64, addr as i64, addrlen as i64)) as i32
19814}
19815
19816#[no_mangle]
19817pub unsafe extern "C" fn getsockopt(fd: i32, level: i32, optname: i32, optval: *mut core::ffi::c_void, optlen: *mut u32) -> i32 {
19818    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
19819}
19820
19821// ============================================================
19822// stdio unlocked functions
19823// ============================================================
19824
19825#[no_mangle]
19826pub unsafe extern "C" fn ftrylockfile(file: *mut FILE) -> i32 {
19827    if file.is_null() { return EINVAL; }
19828    if (*file).lock < 0 { return 0; }
19829    let tid = sys_gettid() as c_int;
19830    let v = a_load(&raw const (*file).lock);
19831    if v == tid {
19832        (*file).lockcount += 1;
19833        return 0;
19834    }
19835    if v == 0 && a_cas(&raw mut (*file).lock, 0, tid) == 0 {
19836        (*file).lockcount = 1;
19837        return 0;
19838    }
19839    EBUSY
19840}
19841
19842#[no_mangle]
19843pub unsafe extern "C" fn getc_unlocked(file: *mut core::ffi::c_char) -> i32 {
19844    getc(file as *mut FILE)
19845}
19846
19847#[no_mangle]
19848pub unsafe extern "C" fn getchar_unlocked() -> i32 {
19849    getchar()
19850}
19851
19852#[no_mangle]
19853pub unsafe extern "C" fn putc_unlocked(c: i32, file: *mut core::ffi::c_char) -> i32 {
19854    putc(c, file as *mut FILE)
19855}
19856
19857#[no_mangle]
19858pub unsafe extern "C" fn putchar_unlocked(c: i32) -> i32 {
19859    putchar(c)
19860}
19861
19862// ============================================================
19863// getopt functions
19864// ============================================================
19865
19866#[no_mangle] pub static mut optarg: *mut core::ffi::c_char = core::ptr::null_mut();
19867#[no_mangle] pub static mut optind: i32 = 1;
19868#[no_mangle] pub static mut opterr: i32 = 1;
19869#[no_mangle] pub static mut optopt: i32 = '?' as i32;
19870#[no_mangle] pub static mut optreset: i32 = 0;
19871
19872// ============================================================
19873// Timer functions
19874// ============================================================
19875
19876#[no_mangle]
19877pub unsafe extern "C" fn getitimer(which: i32, curr_value: *mut core::ffi::c_void) -> i32 {
19878    syscall_ret(<Arch as Syscalls>::syscall2(sysno(36, 102), which as i64, curr_value as i64)) as i32
19879}
19880
19881#[no_mangle]
19882pub unsafe extern "C" fn setitimer(which: i32, new_value: *const core::ffi::c_void, old_value: *mut core::ffi::c_void) -> i32 {
19883    syscall_ret(<Arch as Syscalls>::syscall3(sysno(38, 103), which as i64, new_value as i64, old_value as i64)) as i32
19884}
19885
19886// ============================================================
19887// System info functions
19888// ============================================================
19889
19890#[no_mangle]
19891pub unsafe extern "C" fn getloadavg(loadavg: *mut f64, nelem: i32) -> i32 {
19892    let fd = crate::open(b"/proc/loadavg\0".as_ptr() as *const core::ffi::c_char, 0, 0);
19893    if fd < 0 { return -1; }
19894    let mut buf: [u8; 64] = [0; 64];
19895    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
19896    crate::close(fd);
19897    if n <= 0 { return -1; }
19898    buf[n as usize] = 0;
19899    if loadavg.is_null() || nelem <= 0 { return -1; }
19900    let mut p = buf.as_ptr() as *const core::ffi::c_char;
19901    let mut i = 0usize;
19902    while i < nelem as usize && i < 3 {
19903        let mut end: *mut core::ffi::c_char = core::ptr::null_mut();
19904        let val = crate::strtod(p, &mut end);
19905        if end as *const core::ffi::c_char == p { break; }
19906        *loadavg.add(i) = val;
19907        i += 1;
19908        p = end;
19909        while *p == b' ' as c_char || *p == b'\t' as c_char || *p == b'\n' as c_char {
19910            p = p.add(1);
19911        }
19912    }
19913    i as i32
19914}
19915
19916#[no_mangle]
19917pub unsafe extern "C" fn get_nprocs() -> i32 {
19918    sysconf(84) as i32 // _SC_NPROCESSORS_ONLN
19919}
19920
19921#[no_mangle]
19922pub unsafe extern "C" fn get_nprocs_conf() -> i32 {
19923    sysconf(83) as i32 // _SC_NPROCESSORS_CONF
19924}
19925
19926#[no_mangle]
19927pub unsafe extern "C" fn get_avphys_pages() -> i64 {
19928    sysconf(86) // _SC_AVPHYS_PAGES
19929}
19930
19931#[no_mangle]
19932pub unsafe extern "C" fn get_phys_pages() -> i64 {
19933    sysconf(85) // _SC_PHYS_PAGES
19934}
19935
19936// ============================================================
19937// Capability functions
19938// ============================================================
19939
19940#[no_mangle]
19941pub unsafe extern "C" fn capget(header: *mut core::ffi::c_void, data: *mut core::ffi::c_void) -> i32 {
19942    syscall_ret(<Arch as Syscalls>::syscall2(SYS_CAPGET, header as i64, data as i64)) as i32
19943}
19944
19945#[no_mangle]
19946pub unsafe extern "C" fn capset(header: *const core::ffi::c_void, data: *const core::ffi::c_void) -> i32 {
19947    syscall_ret(<Arch as Syscalls>::syscall2(SYS_CAPSET, header as i64, data as i64)) as i32
19948}
19949
19950#[no_mangle]
19951pub unsafe extern "C" fn arch_prctl(code: i32, addr: u64) -> i32 {
19952    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 }
19953}
19954
19955// ============================================================
19956// termios functions
19957// ============================================================
19958
19959#[no_mangle]
19960pub unsafe extern "C" fn cfgetospeed(termios_p: *const core::ffi::c_void) -> u32 {
19961    unsafe { *(termios_p as *const u32).add(1) }
19962}
19963
19964#[no_mangle]
19965pub unsafe extern "C" fn cfgetispeed(termios_p: *const core::ffi::c_void) -> u32 {
19966    unsafe { *(termios_p as *const u32).add(2) }
19967}
19968
19969#[no_mangle]
19970pub unsafe extern "C" fn cfsetospeed(termios_p: *mut core::ffi::c_void, speed: u32) -> i32 {
19971    unsafe { *(termios_p as *mut u32).add(1) = speed; }
19972    0
19973}
19974
19975#[no_mangle]
19976pub unsafe extern "C" fn cfsetispeed(termios_p: *mut core::ffi::c_void, speed: u32) -> i32 {
19977    unsafe { *(termios_p as *mut u32).add(2) = speed; }
19978    0
19979}
19980
19981#[no_mangle]
19982pub unsafe extern "C" fn cfmakeraw(termios_p: *mut core::ffi::c_void) {
19983    unsafe {
19984        let p = termios_p as *mut u32;
19985        *p.add(0) &= !0o37;
19986        *p.add(0) &= !(0o4000 | 0o2000 | 0o10000 | 0o20);
19987        *p.add(0) |= 0o60;
19988        *p.add(3) &= !0o17;
19989        *p.add(3) &= !(0o1000 | 0o40000000);
19990        *p.add(1) = 1;
19991        *p.add(2) = 0;
19992    }
19993}
19994
19995// ============================================================
19996// Resource functions
19997// ============================================================
19998
19999#[no_mangle]
20000pub unsafe extern "C" fn getrusage(who: i32, usage: *mut core::ffi::c_void) -> i32 {
20001    syscall_ret(<Arch as Syscalls>::syscall2(sysno(98, 165), who as i64, usage as i64)) as i32
20002}
20003
20004#[no_mangle]
20005pub unsafe extern "C" fn getpriority(which: i32, who: u32) -> i32 {
20006    // The kernel encodes nice as 20 - nice; musl converts it back.
20007    let r = <Arch as Syscalls>::syscall2(SYS_GETPRIORITY, which as i64, who as i64);
20008    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
20009    20 - r as i32
20010}
20011
20012#[no_mangle]
20013pub unsafe extern "C" fn setpriority(which: i32, who: u32, prio: i32) -> i32 {
20014    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETPRIORITY, which as i64, who as i64, prio as i64)) as i32
20015}
20016
20017#[no_mangle]
20018pub unsafe extern "C" fn prlimit(pid: u32, resource: i32, new_limit: *const core::ffi::c_void, old_limit: *mut core::ffi::c_void) -> i32 {
20019    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
20020}
20021
20022// ============================================================
20023// fork/clone functions
20024// ============================================================
20025
20026#[no_mangle]
20027pub unsafe extern "C" fn clone(
20028    func: usize,
20029    stack: *mut u8,
20030    flags: c_int,
20031    arg: *mut c_void,
20032    mut args: ...
20033) -> c_int {
20034    // musl-compatible signature: clone(fn, stack, flags, arg, ptid, tls, ctid).
20035    const CLONE_PIDFD_C: c_int = 0x00001000;
20036    const CLONE_VM_C: c_int = 0x00000100;
20037    const CLONE_THREAD_C: c_int = 0x00010000;
20038    const CLONE_SETTLS_C: c_int = 0x00080000;
20039    const CLONE_PARENT_SETTID_C: c_int = 0x00100000;
20040    const CLONE_CHILD_SETTID_C: c_int = 0x01000000;
20041    const CLONE_CHILD_CLEARTID_C: c_int = 0x00200000;
20042    let _ = CLONE_VM_C;
20043    if flags & (CLONE_THREAD_C | CLONE_SETTLS_C | CLONE_CHILD_CLEARTID_C) != 0
20044        || stack.is_null()
20045    {
20046        ERRNO!() = EINVAL;
20047        return -1;
20048    }
20049    let mut ptid: *mut c_int = core::ptr::null_mut();
20050    let mut tls: c_ulong = 0;
20051    let mut ctid: *mut c_int = core::ptr::null_mut();
20052    if flags & (CLONE_PIDFD_C | CLONE_PARENT_SETTID_C | CLONE_CHILD_SETTID_C) != 0 {
20053        ptid = args.next_arg::<*mut c_int>();
20054    }
20055    if flags & CLONE_CHILD_SETTID_C != 0 {
20056        tls = args.next_arg::<c_ulong>();
20057        ctid = args.next_arg::<*mut c_int>();
20058    }
20059    let r = __keel_clone(func, stack, flags as c_ulong, arg, ptid, tls, ctid);
20060    syscall_ret(r) as c_int
20061}
20062
20063#[no_mangle]
20064pub unsafe extern "C" fn _Fork() -> i32 {
20065    crate::fork()
20066}
20067
20068#[no_mangle]
20069pub 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 {
20070    let mut master: i32 = 0;
20071    let mut slave: i32 = 0;
20072    if openpty(&mut master, &mut slave, name, termp, winp) < 0 { return -1; }
20073    let pid = crate::fork();
20074    if pid < 0 { crate::close(master); crate::close(slave); return -1; }
20075    if pid == 0 {
20076        crate::close(master);
20077        crate::setsid();
20078        crate::dup2(slave, 0);
20079        crate::dup2(slave, 1);
20080        crate::dup2(slave, 2);
20081    } else {
20082        crate::close(slave);
20083        if !amaster.is_null() { *amaster = master; }
20084    }
20085    pid
20086}
20087
20088#[no_mangle]
20089pub 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 {
20090    let master = crate::open(b"/dev/ptmx\0".as_ptr() as *const core::ffi::c_char, 0o2000, 0);
20091    if master < 0 { return -1; }
20092    grantpt(master);
20093    unlockpt(master);
20094    let slave_name = ptsname(master);
20095    if slave_name.is_null() { crate::close(master); return -1; }
20096    let slave = crate::open(slave_name, 0o2000, 0);
20097    if slave < 0 { crate::close(master); return -1; }
20098    if !amaster.is_null() { *amaster = master; }
20099    if !aslave.is_null() { *aslave = slave; }
20100    if !name.is_null() { crate::strcpy(name as *mut u8, slave_name as *const u8); }
20101    0
20102}
20103
20104#[no_mangle]
20105pub unsafe extern "C" fn login_tty(fd: i32) -> i32 {
20106    crate::setsid();
20107    crate::dup2(fd, 0);
20108    crate::dup2(fd, 1);
20109    crate::dup2(fd, 2);
20110    0
20111}
20112
20113// ============================================================
20114// dl functions
20115// ============================================================
20116
20117#[no_mangle]
20118pub unsafe extern "C" fn __dls2b() {}
20119#[no_mangle]
20120pub unsafe extern "C" fn __dls3() {}
20121#[no_mangle]
20122pub unsafe extern "C" fn _dlstart() {}
20123
20124// ============================================================
20125// string functions
20126// ============================================================
20127
20128#[no_mangle]
20129pub unsafe extern "C" fn index(s: *const core::ffi::c_char, c: i32) -> *mut core::ffi::c_char {
20130    let mut i = 0;
20131    loop {
20132        let ch = *s.add(i);
20133        if ch == c as core::ffi::c_char { return s.add(i) as *mut core::ffi::c_char; }
20134        if ch == 0 { return core::ptr::null_mut(); }
20135        i += 1;
20136    }
20137}
20138
20139#[no_mangle]
20140pub unsafe extern "C" fn rindex(s: *const core::ffi::c_char, c: i32) -> *mut core::ffi::c_char {
20141    let mut last = core::ptr::null_mut();
20142    let mut i = 0;
20143    loop {
20144        let ch = *s.add(i);
20145        if ch == 0 { return last; }
20146        if ch == c as core::ffi::c_char { last = s.add(i) as *mut core::ffi::c_char; }
20147        i += 1;
20148    }
20149}
20150
20151// ============================================================
20152// intmax functions
20153// ============================================================
20154
20155#[no_mangle]
20156pub unsafe extern "C" fn imaxabs(j: i64) -> i64 {
20157    j.abs()
20158}
20159
20160#[no_mangle]
20161pub unsafe extern "C" fn imaxdiv(numer: i64, denom: i64) -> (i64, i64) {
20162    (numer / denom, numer % denom)
20163}
20164
20165// ============================================================
20166// herror functions
20167// ============================================================
20168
20169#[no_mangle]
20170pub static mut h_errno: i32 = 0;
20171
20172#[no_mangle]
20173pub unsafe extern "C" fn __h_errno_location() -> *mut i32 {
20174    h_errno_ptr()
20175}
20176
20177#[no_mangle]
20178pub unsafe extern "C" fn herror(s: *const core::ffi::c_char) {
20179    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
20180    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20181    let msg = hstrerror(*__h_errno_location());
20182    crate::write(2, msg as *const core::ffi::c_void, crate::strlen(msg));
20183    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20184}
20185
20186#[no_mangle]
20187pub unsafe extern "C" fn hstrerror(err: i32) -> *const core::ffi::c_char {
20188    let msg: &[u8] = match err {
20189        1 => b"Host not found\0",
20190        2 => b"Try again\0",
20191        3 => b"Non-recoverable error\0",
20192        4 => b"Address not available\0",
20193        _ => b"Unknown error\0",
20194    };
20195    msg.as_ptr() as *const core::ffi::c_char
20196}
20197
20198// ============================================================
20199// gettid function
20200// ============================================================
20201
20202#[no_mangle]
20203pub unsafe extern "C" fn gettid() -> i32 {
20204    syscall_ret(<Arch as Syscalls>::syscall0(SYS_GETTID)) as i32
20205}
20206
20207// ============================================================
20208// ioctl functions
20209// ============================================================
20210
20211#[no_mangle]
20212pub unsafe extern "C" fn ioctl(fd: i32, request: u32, mut args: ...) -> i32 {
20213    let arg = args.next_arg::<i64>();
20214    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg)) as i32
20215}
20216
20217#[no_mangle]
20218pub unsafe extern "C" fn ioperm(from: u64, num: u64, turn_on: i32) -> i32 {
20219    #[cfg(target_arch = "x86_64")]
20220    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOPERM, from as i64, num as i64, turn_on as i64)) as i32 }
20221    #[cfg(not(target_arch = "x86_64"))]
20222    {
20223        let _ = (from, num, turn_on);
20224        ERRNO!() = ENOSYS;
20225        -1
20226    }
20227}
20228
20229#[no_mangle]
20230pub unsafe extern "C" fn iopl(level: i32) -> i32 {
20231    #[cfg(target_arch = "x86_64")]
20232    { syscall_ret(<Arch as Syscalls>::syscall1(SYS_IOPL, level as i64)) as i32 }
20233    #[cfg(not(target_arch = "x86_64"))]
20234    {
20235        let _ = level;
20236        ERRNO!() = ENOSYS;
20237        -1
20238    }
20239}
20240
20241// ============================================================
20242// xattr functions
20243// ============================================================
20244
20245#[no_mangle]
20246pub unsafe extern "C" fn getxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
20247    syscall_ret(<Arch as Syscalls>::syscall4(sysno(191, 8), path as i64, name as i64, value as i64, size as i64)) as isize
20248}
20249
20250#[no_mangle]
20251pub unsafe extern "C" fn lgetxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
20252    syscall_ret(<Arch as Syscalls>::syscall4(sysno(192, 9), path as i64, name as i64, value as i64, size as i64)) as isize
20253}
20254
20255#[no_mangle]
20256pub unsafe extern "C" fn fgetxattr(fd: i32, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
20257    syscall_ret(<Arch as Syscalls>::syscall4(sysno(193, 10), fd as i64, name as i64, value as i64, size as i64)) as isize
20258}
20259
20260#[no_mangle]
20261pub unsafe extern "C" fn listxattr(path: *const core::ffi::c_char, list: *mut u8, size: usize) -> isize {
20262    syscall_ret(<Arch as Syscalls>::syscall3(sysno(194, 11), path as i64, list as i64, size as i64)) as isize
20263}
20264
20265#[no_mangle]
20266pub unsafe extern "C" fn llistxattr(path: *const core::ffi::c_char, list: *mut u8, size: usize) -> isize {
20267    syscall_ret(<Arch as Syscalls>::syscall3(sysno(195, 12), path as i64, list as i64, size as i64)) as isize
20268}
20269
20270#[no_mangle]
20271pub unsafe extern "C" fn flistxattr(fd: i32, list: *mut u8, size: usize) -> isize {
20272    syscall_ret(<Arch as Syscalls>::syscall3(sysno(196, 13), fd as i64, list as i64, size as i64)) as isize
20273}
20274
20275#[no_mangle]
20276pub 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 {
20277    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
20278}
20279
20280#[no_mangle]
20281pub 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 {
20282    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
20283}
20284
20285#[no_mangle]
20286pub unsafe extern "C" fn fsetxattr(fd: i32, name: *const core::ffi::c_char, value: *const u8, size: usize, flags: i32) -> i32 {
20287    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
20288}
20289
20290#[no_mangle]
20291pub unsafe extern "C" fn removexattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char) -> i32 {
20292    syscall_ret(<Arch as Syscalls>::syscall2(sysno(197, 14), path as i64, name as i64)) as i32
20293}
20294
20295#[no_mangle]
20296pub unsafe extern "C" fn lremovexattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char) -> i32 {
20297    syscall_ret(<Arch as Syscalls>::syscall2(sysno(198, 15), path as i64, name as i64)) as i32
20298}
20299
20300#[no_mangle]
20301pub unsafe extern "C" fn fremovexattr(fd: i32, name: *const core::ffi::c_char) -> i32 {
20302    syscall_ret(<Arch as Syscalls>::syscall2(sysno(199, 16), fd as i64, name as i64)) as i32
20303}
20304
20305// ============================================================
20306// adjtime functions
20307// ============================================================
20308
20309#[repr(C)]
20310struct TimexBuf {
20311    modes: c_uint,
20312    offset: c_long,
20313    freq: c_long,
20314    maxerror: c_long,
20315    esterror: c_long,
20316    status: c_int,
20317    constant: c_long,
20318    precision: c_long,
20319    tolerance: c_long,
20320    time: timeval,
20321    tick: c_long,
20322    ppsfreq: c_long,
20323    jitter: c_long,
20324    shift: c_int,
20325    stabil: c_long,
20326    jitcnt: c_long,
20327    calcnt: c_long,
20328    errcnt: c_long,
20329    stbcnt: c_long,
20330    tai: c_int,
20331    padding: [c_int; 11],
20332}
20333
20334#[no_mangle]
20335pub unsafe extern "C" fn adjtime(delta: *const timeval, olddelta: *mut timeval) -> i32 {
20336    // Port of musl's linux/adjtime.c.
20337    let mut tx: TimexBuf = core::mem::zeroed();
20338    if !delta.is_null() {
20339        if (*delta).tv_sec > 1000 || (*delta).tv_usec > 1_000_000_000 {
20340            ERRNO!() = EINVAL;
20341            return -1;
20342        }
20343        tx.offset = (*delta).tv_sec * 1_000_000 + (*delta).tv_usec;
20344        tx.modes = 0x8001; // ADJ_OFFSET_SINGLESHOT
20345    }
20346    let r = <Arch as Syscalls>::syscall1(SYS_ADJTIMEX, &mut tx as *mut TimexBuf as i64);
20347    if r < 0 {
20348        ERRNO!() = (-r) as c_int;
20349        return -1;
20350    }
20351    if !olddelta.is_null() {
20352        let mut sec = tx.offset / 1_000_000;
20353        let mut usec = tx.offset % 1_000_000;
20354        if usec < 0 {
20355            sec -= 1;
20356            usec += 1_000_000;
20357        }
20358        (*olddelta).tv_sec = sec;
20359        (*olddelta).tv_usec = usec;
20360    }
20361    0
20362}
20363
20364#[no_mangle]
20365pub unsafe extern "C" fn adjtimex(buf: *mut core::ffi::c_void) -> i32 {
20366    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ADJTIMEX, buf as i64)) as i32
20367}
20368
20369// ============================================================
20370// pty functions
20371// ============================================================
20372
20373// Linux devpts ioctls (asm-generic/ioctls.h): TIOCGPTN = _IOR('T', 0x30, int),
20374// TIOCSPTLCK = _IOW('T', 0x31, int). The old 0x541x values are the window-size
20375// and process-group requests, which both return the wrong data and write more
20376// bytes than the int the caller supplied.
20377const TIOCGPTN: i64 = 0x80045430;
20378const TIOCSPTLCK: i64 = 0x40045431;
20379
20380#[no_mangle]
20381pub unsafe extern "C" fn grantpt(_fd: i32) -> i32 {
20382    // devpts creates the slave already owned by the caller.
20383    0
20384}
20385
20386#[no_mangle]
20387pub unsafe extern "C" fn unlockpt(fd: i32) -> i32 {
20388    let mut unlock: i32 = 0;
20389    let r = <Arch as Syscalls>::syscall3(
20390        SYS_IOCTL,
20391        fd as i64,
20392        TIOCSPTLCK,
20393        &mut unlock as *mut i32 as i64,
20394    );
20395    syscall_ret(r) as c_int
20396}
20397
20398#[no_mangle]
20399pub unsafe extern "C" fn ptsname(fd: i32) -> *mut core::ffi::c_char {
20400    static mut BUF: [core::ffi::c_char; 32] = [0; 32];
20401    let mut pty_nr: i32 = 0;
20402    if <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, TIOCGPTN, &mut pty_nr as *mut i32 as i64) < 0 {
20403        return core::ptr::null_mut();
20404    }
20405    // Format /dev/pts/N
20406    BUF[0] = '/' as c_char; BUF[1] = 'd' as c_char; BUF[2] = 'e' as c_char; BUF[3] = 'v' as c_char;
20407    BUF[4] = '/' as c_char; BUF[5] = 'p' as c_char; BUF[6] = 't' as c_char; BUF[7] = 's' as c_char;
20408    BUF[8] = '/' as c_char;
20409    let i = 9 + write_decimal(BUF.as_mut_ptr().add(9), pty_nr as usize);
20410    if i >= BUF.len() { return core::ptr::null_mut(); }
20411    BUF[i] = 0;
20412    BUF.as_mut_ptr()
20413}
20414
20415// ============================================================
20416// fpclassify functions
20417// ============================================================
20418
20419#[no_mangle]
20420pub unsafe extern "C" fn finite(x: f64) -> i32 {
20421    (!x.is_nan() && !x.is_infinite()) as i32
20422}
20423
20424#[no_mangle]
20425pub unsafe extern "C" fn finitef(x: f32) -> i32 {
20426    (!x.is_nan() && !x.is_infinite()) as i32
20427}
20428
20429#[no_mangle]
20430pub unsafe extern "C" fn __fpclassifyl(x: f64) -> i32 {
20431    __fpclassify(x)
20432}
20433
20434#[no_mangle]
20435pub unsafe extern "C" fn __signbitl(x: f64) -> i32 {
20436    __signbit(x)
20437}
20438
20439// ============================================================
20440// ftw functions
20441// ============================================================
20442
20443// ============================================================
20444// Bessel functions
20445// ============================================================
20446
20447#[no_mangle]
20448pub unsafe extern "C" fn j0(x: f64) -> f64 {
20449    j0_impl(x)
20450}
20451
20452#[no_mangle]
20453pub unsafe extern "C" fn j0f(x: f32) -> f32 {
20454    libm::j0f(x)
20455}
20456
20457#[no_mangle]
20458pub unsafe extern "C" fn j1(x: f64) -> f64 {
20459    libm::j1(x)
20460}
20461
20462#[no_mangle]
20463pub unsafe extern "C" fn j1f(x: f32) -> f32 {
20464    libm::j1f(x)
20465}
20466
20467#[no_mangle]
20468pub unsafe extern "C" fn jn(n: i32, x: f64) -> f64 {
20469    libm::jn(n, x)
20470}
20471
20472#[no_mangle]
20473pub unsafe extern "C" fn jnf(n: i32, x: f32) -> f32 {
20474    libm::jnf(n, x)
20475}
20476
20477#[no_mangle]
20478pub unsafe extern "C" fn y0(x: f64) -> f64 {
20479    y0_impl(x)
20480}
20481
20482#[no_mangle]
20483pub unsafe extern "C" fn y0f(x: f32) -> f32 {
20484    if x.is_nan() { return x; }
20485    if x < 0.0 { return __math_invalidf(x); }
20486    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f32::NEG_INFINITY; }
20487    libm::y0f(x)
20488}
20489
20490#[no_mangle]
20491pub unsafe extern "C" fn y1(x: f64) -> f64 {
20492    if x.is_nan() { return x; }
20493    if x < 0.0 { return __math_invalid(x); }
20494    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f64::NEG_INFINITY; }
20495    libm::y1(x)
20496}
20497
20498#[no_mangle]
20499pub unsafe extern "C" fn y1f(x: f32) -> f32 {
20500    if x.is_nan() { return x; }
20501    if x < 0.0 { return __math_invalidf(x); }
20502    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f32::NEG_INFINITY; }
20503    libm::y1f(x)
20504}
20505
20506#[no_mangle]
20507pub unsafe extern "C" fn yn(n: i32, x: f64) -> f64 {
20508    if x.is_nan() { return x; }
20509    if x < 0.0 { return __math_invalid(x); }
20510    if x == 0.0 {
20511        feraiseexcept(FE_DIVBYZERO);
20512        if n >= 0 { return f64::NEG_INFINITY; }
20513    }
20514    libm::yn(n, x)
20515}
20516
20517#[no_mangle]
20518pub unsafe extern "C" fn ynf(n: i32, x: f32) -> f32 {
20519    if x.is_nan() { return x; }
20520    if x < 0.0 { return __math_invalidf(x); }
20521    if x == 0.0 {
20522        feraiseexcept(FE_DIVBYZERO);
20523        if n >= 0 { return f32::NEG_INFINITY; }
20524    }
20525    libm::ynf(n, x)
20526}
20527
20528// ============================================================
20529// ctype locale functions
20530// ============================================================
20531
20532#[no_mangle]
20533pub unsafe extern "C" fn __isalnum_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20534    (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
20535}
20536
20537#[no_mangle]
20538pub unsafe extern "C" fn __isalpha_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20539    (c >= 'A' as i32 && c <= 'Z' as i32 || c >= 'a' as i32 && c <= 'z' as i32) as i32
20540}
20541
20542#[no_mangle]
20543pub unsafe extern "C" fn __isblank_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20544    (c == ' ' as i32 || c == '\t' as i32) as i32
20545}
20546
20547#[no_mangle]
20548pub unsafe extern "C" fn __iscntrl_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20549    (c < 0x20 || c == 0x7f) as i32
20550}
20551
20552#[no_mangle]
20553pub unsafe extern "C" fn __isdigit_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20554    (c >= '0' as i32 && c <= '9' as i32) as i32
20555}
20556
20557#[no_mangle]
20558pub unsafe extern "C" fn __isgraph_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20559    (c > 0x20 && c < 0x7f) as i32
20560}
20561
20562#[no_mangle]
20563pub unsafe extern "C" fn __islower_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20564    (c >= 'a' as i32 && c <= 'z' as i32) as i32
20565}
20566
20567#[no_mangle]
20568pub unsafe extern "C" fn __isprint_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20569    (c >= 0x20 && c < 0x7f) as i32
20570}
20571
20572#[no_mangle]
20573pub unsafe extern "C" fn __ispunct_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20574    (c >= 0x21 && c <= 0x2f || c >= 0x3a && c <= 0x40 || c >= 0x5b && c <= 0x60 || c >= 0x7b && c <= 0x7e) as i32
20575}
20576
20577#[no_mangle]
20578pub unsafe extern "C" fn __isspace_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20579    (c == ' ' as i32 || c >= 0x09 && c <= 0x0d) as i32
20580}
20581
20582#[no_mangle]
20583pub unsafe extern "C" fn __isupper_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20584    (c >= 'A' as i32 && c <= 'Z' as i32) as i32
20585}
20586
20587#[no_mangle]
20588pub unsafe extern "C" fn __isxdigit_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20589    (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
20590}
20591
20592// ============================================================
20593// wide char locale functions
20594// ============================================================
20595
20596#[no_mangle]
20597pub unsafe extern "C" fn __iswalnum_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20598    (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
20599}
20600
20601#[no_mangle]
20602pub unsafe extern "C" fn __iswalpha_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20603    (c >= 'A' as u32 && c <= 'Z' as u32 || c >= 'a' as u32 && c <= 'z' as u32) as i32
20604}
20605
20606#[no_mangle]
20607pub unsafe extern "C" fn __iswblank_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20608    (c == ' ' as u32 || c == '\t' as u32) as i32
20609}
20610
20611#[no_mangle]
20612pub unsafe extern "C" fn __iswcntrl_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20613    (c < 0x20 || c == 0x7f) as i32
20614}
20615
20616#[no_mangle]
20617pub unsafe extern "C" fn __iswdigit_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20618    (c >= '0' as u32 && c <= '9' as u32) as i32
20619}
20620
20621#[no_mangle]
20622pub unsafe extern "C" fn __iswgraph_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20623    (c > 0x20 && c < 0x7f) as i32
20624}
20625
20626#[no_mangle]
20627pub unsafe extern "C" fn __iswlower_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20628    (c >= 'a' as u32 && c <= 'z' as u32) as i32
20629}
20630
20631#[no_mangle]
20632pub unsafe extern "C" fn __iswprint_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20633    (c >= 0x20 && c < 0x7f) as i32
20634}
20635
20636#[no_mangle]
20637pub unsafe extern "C" fn __iswpunct_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20638    (c >= 0x21 && c <= 0x2f || c >= 0x3a && c <= 0x40 || c >= 0x5b && c <= 0x60 || c >= 0x7b && c <= 0x7e) as i32
20639}
20640
20641#[no_mangle]
20642pub unsafe extern "C" fn __iswspace_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20643    (c == ' ' as u32 || c >= 0x09 && c <= 0x0d) as i32
20644}
20645
20646#[no_mangle]
20647pub unsafe extern "C" fn __iswupper_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20648    (c >= 'A' as u32 && c <= 'Z' as u32) as i32
20649}
20650
20651#[no_mangle]
20652pub unsafe extern "C" fn __iswxdigit_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20653    (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
20654}
20655
20656#[no_mangle]
20657pub unsafe extern "C" fn __iswctype_l(c: u32, ctype: u32, _loc: *mut core::ffi::c_void) -> i32 {
20658    crate::iswctype(c as wint_t, ctype as wctype_t)
20659}
20660
20661#[no_mangle]
20662pub unsafe extern "C" fn __towlower_l(c: u32, _loc: *mut core::ffi::c_void) -> u32 {
20663    crate::towlower(c)
20664}
20665
20666#[no_mangle]
20667pub unsafe extern "C" fn __towupper_l(c: u32, _loc: *mut core::ffi::c_void) -> u32 {
20668    crate::towupper(c)
20669}
20670
20671#[no_mangle]
20672pub unsafe extern "C" fn __towctrans_l(c: u32, _trans: u32, _loc: *mut core::ffi::c_void) -> u32 {
20673    c
20674}
20675
20676// ============================================================
20677// _r functions
20678// ============================================================
20679
20680// ============================================================
20681// stdio internal functions
20682// ============================================================
20683
20684// ============================================================
20685// Misc functions
20686// ============================================================
20687
20688#[no_mangle]
20689pub 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) {
20690    crate::write(2, b"Assertion failed: ".as_ptr() as *const core::ffi::c_void, 18);
20691    if !expr.is_null() { crate::write(2, expr as *const core::ffi::c_void, crate::strlen(expr)); }
20692    crate::write(2, b" (".as_ptr() as *const core::ffi::c_void, 2);
20693    if !file.is_null() { crate::write(2, file as *const core::ffi::c_void, crate::strlen(file)); }
20694    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20695    let mut n = line as usize;
20696    let mut digits: [u8; 32] = [0; 32];
20697    let mut di = 0;
20698    if n == 0 { digits[0] = 0; di = 1; }
20699    while n > 0 && di < 32 { digits[di] = (n % 10) as u8; n /= 10; di += 1; }
20700    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); }
20701    crate::write(2, b")".as_ptr() as *const core::ffi::c_void, 1);
20702    if !func.is_null() { crate::write(2, func as *const core::ffi::c_void, crate::strlen(func)); }
20703    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20704    crate::abort()
20705}
20706
20707const QUICK_EXIT_MAX: usize = 32;
20708static mut QUICK_EXIT_FNS: [Option<unsafe extern "C" fn()>; QUICK_EXIT_MAX] =
20709    [None; QUICK_EXIT_MAX];
20710static mut QUICK_EXIT_COUNT: usize = 0;
20711
20712#[no_mangle]
20713pub unsafe extern "C" fn at_quick_exit(func: Option<unsafe extern "C" fn()>) -> i32 {
20714    let Some(func) = func else { return -1; };
20715    if QUICK_EXIT_COUNT >= QUICK_EXIT_MAX {
20716        return -1;
20717    }
20718    QUICK_EXIT_FNS[QUICK_EXIT_COUNT] = Some(func);
20719    QUICK_EXIT_COUNT += 1;
20720    0
20721}
20722
20723#[no_mangle]
20724pub unsafe extern "C" fn brk(addr: *mut u8) -> i32 {
20725    syscall_ret(<Arch as Syscalls>::syscall1(sysno(12, 214), addr as i64)) as i32
20726}
20727
20728#[no_mangle]
20729pub 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 {
20730    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
20731}
20732
20733#[no_mangle]
20734pub unsafe extern "C" fn ctermid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
20735    static mut BUF: [core::ffi::c_char; 20] = [0; 20];
20736    let dst = if s.is_null() { BUF.as_mut_ptr() } else { s };
20737    let src = b"/dev/tty\0".as_ptr() as *const core::ffi::c_char;
20738    let mut i = 0;
20739    while i < 9 { *dst.add(i) = *src.add(i); i += 1; }
20740    dst
20741}
20742
20743#[no_mangle]
20744pub unsafe extern "C" fn delete_module(name: *const core::ffi::c_char, flags: u32) -> i32 {
20745    syscall_ret(<Arch as Syscalls>::syscall2(SYS_DELETE_MODULE, name as i64, flags as i64)) as i32
20746}
20747
20748
20749
20750
20751
20752#[no_mangle]
20753pub unsafe extern "C" fn __duplocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
20754    loc
20755}
20756
20757#[no_mangle]
20758pub unsafe extern "C" fn euidaccess(pathname: *const core::ffi::c_char, mode: i32) -> i32 {
20759    faccessat(AT_FDCWD, pathname, mode, 0x200)
20760}
20761
20762#[no_mangle]
20763pub unsafe extern "C" fn fgetln(f: *mut core::ffi::c_void, lenp: *mut usize) -> *mut core::ffi::c_char {
20764    static mut BUF: *mut core::ffi::c_char = core::ptr::null_mut();
20765    static mut CAP: usize = 0;
20766    let n = getline(&raw mut BUF, &raw mut CAP, f as *mut FILE);
20767    if n <= 0 {
20768        if !lenp.is_null() { *lenp = 0; }
20769        return core::ptr::null_mut();
20770    }
20771    if !lenp.is_null() { *lenp = n as usize; }
20772    BUF
20773}
20774
20775#[no_mangle]
20776pub unsafe extern "C" fn fgetws(ws: *mut u32, n: i32, f: *mut core::ffi::c_void) -> *mut u32 {
20777    let mut i = 0;
20778    while i < n - 1 {
20779        let c = getwc(f as *mut core::ffi::c_void);
20780        if c == 0 { break; }
20781        *ws.add(i as usize) = c;
20782        i += 1;
20783        if c == '\n' as u32 { break; }
20784    }
20785    *ws.add(i as usize) = 0;
20786    if i == 0 { core::ptr::null_mut() } else { ws }
20787}
20788
20789#[no_mangle]
20790pub 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 {
20791    if !label.is_null() { crate::write(2, label as *const core::ffi::c_void, crate::strlen(label)); }
20792    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20793    if !text.is_null() { crate::write(2, text as *const core::ffi::c_void, crate::strlen(text)); }
20794    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20795    0
20796}
20797
20798#[no_mangle]
20799pub unsafe extern "C" fn ftime(tp: *mut core::ffi::c_void) -> i32 {
20800    let mut tv: timeval = core::mem::zeroed();
20801    if gettimeofday(&mut tv, core::ptr::null_mut()) == 0 {
20802        let tb = tp as *mut Timeb;
20803        (*tb).time = tv.tv_sec;
20804        (*tb).millitm = (tv.tv_usec / 1000) as u16;
20805        (*tb).timezone = 0;
20806        (*tb).dstflag = 0;
20807        0
20808    } else {
20809        -1
20810    }
20811}
20812
20813#[no_mangle]
20814pub unsafe extern "C" fn getdents(fd: i32, dirp: *mut u8, count: usize) -> isize {
20815    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, dirp as i64, count as i64)) as isize
20816}
20817
20818#[no_mangle]
20819pub unsafe extern "C" fn gethostid() -> i64 {
20820    // Read from /proc/sys/kernel/random/boot_id or similar
20821    let fd = crate::open(b"/proc/sys/kernel/random/boot_id\0".as_ptr() as *const core::ffi::c_char, 0, 0);
20822    if fd < 0 { return 0; }
20823    let mut buf: [u8; 64] = [0; 64];
20824    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
20825    crate::close(fd);
20826    if n <= 0 { return 0; }
20827    buf[n as usize] = 0;
20828    crate::strtol(buf.as_ptr() as *const core::ffi::c_char, core::ptr::null_mut(), 16)
20829}
20830
20831#[repr(C)]
20832#[derive(Copy, Clone)]
20833struct TermiosBuf {
20834    c_iflag: u32,
20835    c_oflag: u32,
20836    c_cflag: u32,
20837    c_lflag: u32,
20838    c_line: u8,
20839    c_cc: [u8; 32],
20840    c_ispeed: u32,
20841    c_ospeed: u32,
20842}
20843
20844#[no_mangle]
20845pub unsafe extern "C" fn getpass(prompt: *const core::ffi::c_char) -> *mut core::ffi::c_char {
20846    static mut BUF: [core::ffi::c_char; 256] = [0; 256];
20847    if prompt.is_null() { return core::ptr::null_mut(); }
20848    const O_NOCTTY_V: i32 = 0x100;
20849    const ECHO_V: u32 = 0o10;
20850    const ISIG_V: u32 = 0o1;
20851    const ICANON_V: u32 = 0o2;
20852    const INLCR_V: u32 = 0o100;
20853    const IGNCR_V: u32 = 0o200;
20854    const ICRNL_V: u32 = 0o400;
20855    const TCSAFLUSH_V: i32 = 2;
20856
20857    let fd = crate::open(
20858        b"/dev/tty\0".as_ptr() as *const core::ffi::c_char,
20859        O_RDWR | O_NOCTTY_V | O_CLOEXEC,
20860        0,
20861    );
20862    if fd < 0 { return core::ptr::null_mut(); }
20863    let mut t: TermiosBuf = core::mem::zeroed();
20864    if tcgetattr(fd, &mut t as *mut TermiosBuf as *mut core::ffi::c_void) < 0 {
20865        crate::close(fd);
20866        return core::ptr::null_mut();
20867    }
20868    let old = t;
20869    t.c_lflag &= !(ECHO_V | ISIG_V);
20870    t.c_lflag |= ICANON_V;
20871    t.c_iflag &= !(INLCR_V | IGNCR_V);
20872    t.c_iflag |= ICRNL_V;
20873    tcsetattr(fd, TCSAFLUSH_V, &t as *const TermiosBuf as *const core::ffi::c_void);
20874    tcdrain(fd);
20875    dprintf(fd, b"%s\0".as_ptr() as *const core::ffi::c_char, prompt);
20876    let n = crate::read(fd, BUF.as_mut_ptr() as *mut core::ffi::c_void, BUF.len() - 1);
20877    let ok = n >= 0;
20878    if ok {
20879        let mut len = n as usize;
20880        if (len > 0 && BUF[len - 1] == b'\n' as core::ffi::c_char) || len == BUF.len() - 1 {
20881            len -= 1;
20882        }
20883        BUF[len] = 0;
20884    }
20885    tcsetattr(fd, TCSAFLUSH_V, &old as *const TermiosBuf as *const core::ffi::c_void);
20886    dprintf(fd, b"\n\0".as_ptr() as *const core::ffi::c_char);
20887    crate::close(fd);
20888    if ok { BUF.as_mut_ptr() } else { core::ptr::null_mut() }
20889}
20890
20891#[no_mangle]
20892pub 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 {
20893    let s = *optionp;
20894    if s.is_null() { return -1; }
20895    // Find end of suboption
20896    let mut end = s;
20897    while *end != 0 && *end != ',' as c_char && *end != '=' as c_char { end = end.add(1); }
20898    let eq = *end == '=' as c_char;
20899    if eq { *end = 0; *valuep = end.add(1); }
20900    // Find matching token
20901    let mut i = 0;
20902    loop {
20903        let tok = *tokens.add(i);
20904        if tok.is_null() { break; }
20905        if crate::strcmp(s as *const u8, tok as *const u8) == 0 {
20906            // Skip to next option
20907    while *end != 0 && *end != ',' as c_char { end = end.add(1); }
20908            if *end == ',' as c_char { end = end.add(1); }
20909            *optionp = end;
20910            return i as i32;
20911        }
20912        i += 1;
20913    }
20914    -1
20915}
20916
20917#[no_mangle]
20918pub unsafe extern "C" fn getw(f: *mut core::ffi::c_void) -> i32 {
20919    let c0 = getc(f as *mut FILE);
20920    if c0 < 0 { return -1; }
20921    let c1 = getc(f as *mut FILE);
20922    if c1 < 0 { return -1; }
20923    let c2 = getc(f as *mut FILE);
20924    if c2 < 0 { return -1; }
20925    let c3 = getc(f as *mut FILE);
20926    if c3 < 0 { return -1; }
20927    (c0 | (c1 << 8) | (c2 << 16) | (c3 << 24)) as i32
20928}
20929
20930#[no_mangle]
20931pub unsafe extern "C" fn getwc(f: *mut core::ffi::c_void) -> u32 {
20932    getc(f as *mut FILE) as u32
20933}
20934
20935#[no_mangle]
20936pub unsafe extern "C" fn init_module(module_image: *mut u8, len: usize, param_values: *const core::ffi::c_char) -> i32 {
20937    syscall_ret(<Arch as Syscalls>::syscall3(SYS_INIT_MODULE, module_image as i64, len as i64, param_values as i64)) as i32
20938}
20939
20940
20941
20942#[no_mangle]
20943pub unsafe extern "C" fn issetugid() -> i32 {
20944    let ruid = crate::getuid();
20945    let euid = crate::geteuid();
20946    let rgid = crate::getgid();
20947    let egid = crate::getegid();
20948    (ruid != euid || rgid != egid) as i32
20949}
20950
20951// ============================================================
20952// poll functions
20953// ============================================================
20954
20955#[repr(C)]
20956struct PollTimespec {
20957    tv_sec: i64,
20958    tv_nsec: i64,
20959}
20960
20961#[no_mangle]
20962pub unsafe extern "C" fn poll(fds: *mut core::ffi::c_void, nfds: u32, timeout: i32) -> i32 {
20963    #[cfg(target_arch = "x86_64")]
20964    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_POLL, fds as i64, nfds as i64, timeout as i64)) as i32 }
20965    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
20966    {
20967        // poll(2) does not exist on these architectures.  ppoll(2) takes a
20968        // struct timespec, not a millisecond count; passing the integer
20969        // directly made poll(..., 0) wait forever.
20970        let mut ts = PollTimespec { tv_sec: 0, tv_nsec: 0 };
20971        let ts_ptr = if timeout < 0 {
20972            core::ptr::null()
20973        } else {
20974            ts.tv_sec = (timeout / 1000) as i64;
20975            ts.tv_nsec = ((timeout % 1000) as i64) * 1_000_000;
20976            &ts as *const PollTimespec as *const core::ffi::c_void
20977        };
20978        syscall_ret(<Arch as Syscalls>::syscall5(
20979            SYS_PPOLL,
20980            fds as i64,
20981            nfds as i64,
20982            ts_ptr as i64,
20983            0,
20984            8,
20985        )) as i32
20986    }
20987}
20988
20989#[no_mangle]
20990pub unsafe extern "C" fn ppoll(fds: *mut core::ffi::c_void, nfds: u32, timeout: *const core::ffi::c_void, sigmask: *const u64) -> i32 {
20991    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PPOLL, fds as i64, nfds as i64, timeout as i64, sigmask as i64, 8)) as i32
20992}
20993
20994#[repr(C)]
20995struct PselectSigmask {
20996    ss: *const u64,
20997    ss_len: usize,
20998}
20999
21000#[no_mangle]
21001pub 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 {
21002    // pselect6 takes a { sigset_t *, size_t } pair, not the sigset pointer.
21003    // GNU make blocks SIGCHLD and depends on this temporary mask, so passing
21004    // the pointer directly deadlocks parallel builds.
21005    let arg = PselectSigmask {
21006        ss: sigmask,
21007        ss_len: core::mem::size_of::<SigSetT>(),
21008    };
21009    let arg_ptr = if sigmask.is_null() {
21010        0
21011    } else {
21012        &arg as *const PselectSigmask as i64
21013    };
21014    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
21015}
21016
21017// ============================================================
21018// realpath function
21019// ============================================================
21020
21021// ============================================================
21022// quick_exit function
21023// ============================================================
21024
21025#[no_mangle]
21026pub unsafe extern "C" fn quick_exit(status: i32) -> ! {
21027    // Run handlers in reverse registration order, like atexit.
21028    while QUICK_EXIT_COUNT > 0 {
21029        QUICK_EXIT_COUNT -= 1;
21030        if let Some(func) = QUICK_EXIT_FNS[QUICK_EXIT_COUNT] {
21031            func();
21032        }
21033    }
21034    crate::_exit(status)
21035}
21036
21037// ============================================================
21038// stat functions
21039// ============================================================
21040
21041#[no_mangle]
21042pub unsafe extern "C" fn lstat(path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
21043    let r = <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, buf as i64, 0x100);
21044    syscall_ret(r) as c_int
21045}
21046
21047#[no_mangle]
21048pub unsafe extern "C" fn __xstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
21049    crate::stat(path, buf as *mut Stat)
21050}
21051
21052#[no_mangle]
21053pub unsafe extern "C" fn __lxstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
21054    crate::lstat(path, buf)
21055}
21056
21057#[no_mangle]
21058pub unsafe extern "C" fn __fxstat(_ver: i32, fd: i32, buf: *mut core::ffi::c_void) -> i32 {
21059    crate::fstat(fd, buf as *mut Stat)
21060}
21061
21062#[no_mangle]
21063pub unsafe extern "C" fn __fxstatat(_ver: i32, dirfd: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void, flags: i32) -> i32 {
21064    crate::fstatat(dirfd, path, buf as *mut Stat, flags)
21065}
21066
21067// ============================================================
21068// mempcpy function
21069// ============================================================
21070
21071#[no_mangle]
21072pub unsafe extern "C" fn mempcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8 {
21073    core::ptr::copy_nonoverlapping(src, dest, n);
21074    dest.add(n)
21075}
21076
21077// ============================================================
21078// mktemp functions
21079// ============================================================
21080
21081#[no_mangle]
21082pub unsafe extern "C" fn mkostemp(template: *mut core::ffi::c_char, flags: i32) -> i32 {
21083    mkstemps_flags(template, 0, flags)
21084}
21085
21086#[no_mangle]
21087pub unsafe extern "C" fn mkstemps(template: *mut core::ffi::c_char, suffixlen: i32) -> i32 {
21088    mkstemps_impl(template, suffixlen)
21089}
21090
21091// ============================================================
21092// system functions
21093// ============================================================
21094
21095#[no_mangle]
21096pub unsafe extern "C" fn ptrace(request: i32, mut args: ...) -> i64 {
21097    let pid = args.next_arg::<c_long>();
21098    let addr = args.next_arg::<c_long>();
21099    let data = args.next_arg::<c_long>();
21100    // PEEKTEXT/PEEKDATA/PEEKUSER write the result through the data pointer
21101    // (the kernel returns EFAULT for a NULL pointer), so supply a local slot.
21102    if (1..=3).contains(&request) {
21103        let mut result: c_long = 0;
21104        let r = <Arch as Syscalls>::syscall4(
21105            sysno(101, 117),
21106            request as i64,
21107            pid,
21108            addr,
21109            &mut result as *mut c_long as i64,
21110        );
21111        if r < 0 {
21112            ERRNO!() = (-r) as c_int;
21113            return -1;
21114        }
21115        return result;
21116    }
21117    syscall_ret(<Arch as Syscalls>::syscall4(sysno(101, 117), request as i64, pid, addr, data))
21118}
21119
21120#[no_mangle]
21121pub unsafe extern "C" fn personality(persona: u64) -> i64 {
21122    <Arch as Syscalls>::syscall1(sysno(135, 92), persona as i64)
21123}
21124
21125#[no_mangle]
21126pub unsafe extern "C" fn reboot(cmd: c_int) -> i32 {
21127    // musl's public API is reboot(cmd), not the four-argument syscall.
21128    syscall_ret(<Arch as Syscalls>::syscall3(
21129        SYS_REBOOT,
21130        0xfee1dead,
21131        672274793,
21132        cmd as i64,
21133    )) as i32
21134}
21135
21136#[no_mangle]
21137pub unsafe extern "C" fn pivot_root(new_root: *const core::ffi::c_char, put_old: *const core::ffi::c_char) -> i32 {
21138    syscall_ret(<Arch as Syscalls>::syscall2(SYS_PIVOT_ROOT, new_root as i64, put_old as i64)) as i32
21139}
21140
21141#[no_mangle]
21142pub 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 {
21143    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
21144}
21145
21146#[no_mangle]
21147pub unsafe extern "C" fn umount(target: *const core::ffi::c_char) -> i32 {
21148    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, 0)) as i32
21149}
21150
21151#[no_mangle]
21152pub unsafe extern "C" fn umount2(target: *const core::ffi::c_char, flags: i32) -> i32 {
21153    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, flags as i64)) as i32
21154}
21155
21156// ============================================================
21157// resolver functions
21158// ============================================================
21159
21160
21161// ============================================================
21162// signal/error functions
21163// ============================================================
21164
21165#[no_mangle]
21166pub unsafe extern "C" fn psiginfo(_pinfo: *const core::ffi::c_void, s: *const core::ffi::c_char) {
21167    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
21168    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
21169}
21170
21171#[no_mangle]
21172pub unsafe extern "C" fn psignal(sig: i32, s: *const core::ffi::c_char) {
21173    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
21174    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
21175    let msg = strsignal(sig);
21176    crate::write(2, msg as *const core::ffi::c_void, crate::strlen(msg));
21177    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
21178}
21179
21180#[no_mangle]
21181pub unsafe extern "C" fn strsignal(sig: c_int) -> *const c_char {
21182    static NAMES: [&[u8]; 32] = [
21183        b"Unknown signal\0",
21184        b"Hangup\0",
21185        b"Interrupt\0",
21186        b"Quit\0",
21187        b"Illegal instruction\0",
21188        b"Trace/breakpoint trap\0",
21189        b"Aborted\0",
21190        b"Bus error\0",
21191        b"Floating point exception\0",
21192        b"Killed\0",
21193        b"User defined signal 1\0",
21194        b"Segmentation fault\0",
21195        b"User defined signal 2\0",
21196        b"Broken pipe\0",
21197        b"Alarm clock\0",
21198        b"Terminated\0",
21199        b"Stack fault\0",
21200        b"Child process status\0",
21201        b"Continued\0",
21202        b"Stopped (signal)\0",
21203        b"Stopped\0",
21204        b"Stopped (tty input)\0",
21205        b"Stopped (tty output)\0",
21206        b"Urgent I/O condition\0",
21207        b"CPU time limit exceeded\0",
21208        b"File size limit exceeded\0",
21209        b"Virtual timer expired\0",
21210        b"Profiling timer expired\0",
21211        b"Window changed\0",
21212        b"I/O possible\0",
21213        b"Power failure\0",
21214        b"Bad system call\0",
21215    ];
21216    static mut RT_BUF: [c_char; 32] = [0; 32];
21217    if sig > 0 && sig < 32 {
21218        return NAMES[sig as usize].as_ptr() as *const c_char;
21219    }
21220    if sig >= 32 && sig < 65 {
21221        let mut o = 0usize;
21222        for &c in b"Real-time signal \0" {
21223            if c == 0 { break; }
21224            RT_BUF[o] = c as c_char;
21225            o += 1;
21226        }
21227        let mut v = (sig - 32) as u32;
21228        let mut digits = [0u8; 10];
21229        let mut d = 0usize;
21230        if v == 0 { digits[0] = b'0'; d = 1; }
21231        while v > 0 { digits[d] = b'0' + (v % 10) as u8; v /= 10; d += 1; }
21232        while d > 0 { d -= 1; RT_BUF[o] = digits[d] as c_char; o += 1; }
21233        RT_BUF[o] = 0;
21234        return RT_BUF.as_ptr();
21235    }
21236    b"Unknown signal\0".as_ptr() as *const c_char
21237}
21238
21239#[no_mangle]
21240pub unsafe extern "C" fn __strerror_l(errnum: i32, _loc: *mut core::ffi::c_void) -> *const core::ffi::c_char {
21241    crate::strerror(errnum)
21242}
21243
21244// ============================================================
21245// preadv functions
21246// ============================================================
21247
21248#[no_mangle]
21249pub unsafe extern "C" fn preadv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
21250    // preadv takes a 64-bit offset split into pos_l/pos_h on x86_64 and the
21251    // generic ABI; passing only pos_l leaves the high half undefined.
21252    syscall_ret(<Arch as Syscalls>::syscall5(
21253        sysno(295, 69),
21254        fd as i64,
21255        iov as i64,
21256        iovcnt as i64,
21257        offset,
21258        offset >> 32,
21259    )) as isize
21260}
21261
21262#[no_mangle]
21263pub unsafe extern "C" fn pwritev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
21264    syscall_ret(<Arch as Syscalls>::syscall5(
21265        sysno(296, 70),
21266        fd as i64,
21267        iov as i64,
21268        iovcnt as i64,
21269        offset,
21270        offset >> 32,
21271    )) as isize
21272}
21273
21274#[no_mangle]
21275pub unsafe extern "C" fn preadv2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
21276    // x86_64/generic preadv2 split the 64-bit offset into pos_l/pos_h and
21277    // take the flags as the sixth argument.
21278    syscall_ret(<Arch as Syscalls>::syscall6(
21279        sysno(327, 286),
21280        fd as i64,
21281        iov as i64,
21282        iovcnt as i64,
21283        offset,
21284        offset >> 32,
21285        flags as i64,
21286    )) as isize
21287}
21288
21289#[no_mangle]
21290pub unsafe extern "C" fn pwritev2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
21291    syscall_ret(<Arch as Syscalls>::syscall6(
21292        sysno(328, 287),
21293        fd as i64,
21294        iov as i64,
21295        iovcnt as i64,
21296        offset,
21297        offset >> 32,
21298        flags as i64,
21299    )) as isize
21300}
21301
21302// ============================================================
21303// nice function
21304// ============================================================
21305
21306#[no_mangle]
21307pub unsafe extern "C" fn nice(inc: i32) -> i32 {
21308    let mut prio = inc;
21309    if inc > -40 && inc < 40 {
21310        prio += getpriority(0, 0);
21311    }
21312    if prio > 19 { prio = 19; }
21313    if prio < -20 { prio = -20; }
21314    if setpriority(0, 0, prio) != 0 {
21315        if ERRNO!() == 13 { ERRNO!() = 1; } // EACCES -> EPERM, as musl does
21316        return -1;
21317    }
21318    prio
21319}
21320
21321// ============================================================
21322// misc functions
21323// ============================================================
21324
21325#[no_mangle]
21326pub unsafe extern "C" fn l64a(value: i64) -> *mut core::ffi::c_char {
21327    static mut BUF: [core::ffi::c_char; 7] = [0; 7];
21328    let mut v = value as u64;
21329    let mut i = 0;
21330    while v > 0 && i < 6 {
21331        let c = (v & 0x3f) as u8;
21332        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;
21333        v >>= 6;
21334        i += 1;
21335    }
21336    BUF[i] = 0;
21337    BUF.as_mut_ptr()
21338}
21339
21340#[no_mangle]
21341pub unsafe extern "C" fn lchmod(path: *const core::ffi::c_char, mode: u32) -> i32 {
21342    fchmodat(AT_FDCWD, path, mode, 0x100)
21343}
21344
21345#[no_mangle]
21346pub unsafe extern "C" fn lutimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
21347    utimensat(AT_FDCWD, filename, times as *const timespec, 0x100)
21348}
21349
21350#[no_mangle]
21351pub unsafe extern "C" fn mknod(pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
21352    #[cfg(target_arch = "x86_64")]
21353    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKNOD, pathname as i64, mode as i64, dev as i64)) as i32 }
21354    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
21355    {
21356        syscall_ret(<Arch as Syscalls>::syscall4(SYS_MKNODAT, AT_FDCWD as i64, pathname as i64, mode as i64, dev as i64)) as i32
21357    }
21358}
21359
21360#[no_mangle]
21361pub unsafe extern "C" fn memfd_create(name: *const core::ffi::c_char, flags: u32) -> i32 {
21362    syscall_ret(<Arch as Syscalls>::syscall2(sysno(319, 279), name as i64, flags as i64)) as i32
21363}
21364
21365#[no_mangle]
21366pub unsafe extern "C" fn mlock2(addr: *const core::ffi::c_void, len: usize, flags: u32) -> i32 {
21367    syscall_ret(<Arch as Syscalls>::syscall3(sysno(325, 284), addr as i64, len as i64, flags as i64)) as i32
21368}
21369
21370
21371
21372#[no_mangle]
21373pub unsafe extern "C" fn remap_file_pages(addr: *mut core::ffi::c_void, size: usize, prot: i32, pgoff: usize, flags: u32) -> i32 {
21374    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
21375}
21376
21377// ============================================================
21378// nan functions
21379// ============================================================
21380
21381#[no_mangle]
21382pub unsafe extern "C" fn nan(_tagp: *const core::ffi::c_char) -> f64 {
21383    f64::NAN
21384}
21385
21386#[no_mangle]
21387pub unsafe extern "C" fn nanf(_tagp: *const core::ffi::c_char) -> f32 {
21388    f32::NAN
21389}
21390
21391// ============================================================
21392// Remaining symbols - batch 1
21393// ============================================================
21394
21395#[no_mangle]
21396pub unsafe extern "C" fn __lgammal_r(x: f64, signgamp: *mut i32) -> f64 {
21397    *signgamp = 1;
21398    lgamma(x)
21399}
21400
21401#[no_mangle]
21402pub unsafe extern "C" fn __libc_current_sigrtmax() -> i32 {
21403    64
21404}
21405
21406#[no_mangle]
21407pub unsafe extern "C" fn _longjmp(env: *mut core::ffi::c_void, val: i32) {
21408    crate::longjmp(env as *mut u64, val)
21409}
21410
21411#[no_mangle]
21412pub unsafe extern "C" fn __newlocale(_mask: i32, _name: *const core::ffi::c_char, base: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
21413    base
21414}
21415
21416#[no_mangle]
21417pub unsafe extern "C" fn __nl_langinfo(_item: i32) -> *mut core::ffi::c_char {
21418    b"\0".as_ptr() as *mut core::ffi::c_char
21419}
21420
21421#[no_mangle]
21422pub unsafe extern "C" fn __nl_langinfo_l(_item: i32, _loc: *mut core::ffi::c_void) -> *mut core::ffi::c_char {
21423    b"\0".as_ptr() as *mut core::ffi::c_char
21424}
21425
21426#[no_mangle]
21427pub unsafe extern "C" fn ns_get16(cp: *const u8) -> u16 {
21428    ((*cp.add(0) as u16) << 8) | *cp.add(1) as u16
21429}
21430
21431#[no_mangle]
21432pub unsafe extern "C" fn ns_get32(cp: *const u8) -> u32 {
21433    ((*cp.add(0) as u32) << 24) | ((*cp.add(1) as u32) << 16) | ((*cp.add(2) as u32) << 8) | *cp.add(3) as u32
21434}
21435
21436#[no_mangle]
21437pub unsafe extern "C" fn ns_put16(s: u16, dst: *mut u8) {
21438    *dst.add(0) = (s >> 8) as u8;
21439    *dst.add(1) = (s & 0xff) as u8;
21440}
21441
21442#[no_mangle]
21443pub unsafe extern "C" fn ns_put32(l: u32, dst: *mut u8) {
21444    *dst.add(0) = (l >> 24) as u8;
21445    *dst.add(1) = ((l >> 16) & 0xff) as u8;
21446    *dst.add(2) = ((l >> 8) & 0xff) as u8;
21447    *dst.add(3) = (l & 0xff) as u8;
21448}
21449
21450#[no_mangle]
21451pub unsafe extern "C" fn posix_close(fd: i32) -> i32 {
21452    crate::close(fd)
21453}
21454
21455#[no_mangle]
21456pub unsafe extern "C" fn posix_openpt(flags: i32) -> i32 {
21457    crate::open(b"/dev/ptmx\0".as_ptr() as *const core::ffi::c_char, flags, 0)
21458}
21459
21460#[no_mangle]
21461pub unsafe extern "C" fn putw(w: i32, f: *mut core::ffi::c_void) {
21462    putc((w & 0xff) as i32, f as *mut FILE);
21463    putc(((w >> 8) & 0xff) as i32, f as *mut FILE);
21464    putc(((w >> 16) & 0xff) as i32, f as *mut FILE);
21465    putc(((w >> 24) & 0xff) as i32, f as *mut FILE);
21466}
21467
21468
21469
21470#[no_mangle]
21471pub unsafe extern "C" fn rand_r(seedp: *mut u32) -> i32 {
21472    let seed = (*seedp).wrapping_mul(1103515245).wrapping_add(12345);
21473    *seedp = seed;
21474    ((seed >> 16) & 0x7fff) as i32
21475}
21476
21477#[no_mangle]
21478pub unsafe extern "C" fn reallocarray(ptr: *mut core::ffi::c_void, nmemb: usize, size: usize) -> *mut core::ffi::c_void {
21479    let total = match nmemb.checked_mul(size) {
21480        Some(v) => v,
21481        None => { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
21482    };
21483    crate::realloc(ptr, total)
21484}
21485
21486#[no_mangle]
21487pub unsafe extern "C" fn __res_state() -> *mut core::ffi::c_void {
21488    static mut STATE: [u8; 512] = [0; 512];
21489    STATE.as_mut_ptr() as *mut core::ffi::c_void
21490}
21491
21492#[no_mangle]
21493pub unsafe extern "C" fn sbrk(increment: isize) -> *mut u8 {
21494    // musl does not support growing the break directly (malloc uses mmap);
21495    // sbrk(nonzero) always fails with ENOMEM.
21496    if increment != 0 {
21497        ERRNO!() = ENOMEM;
21498        return -1isize as usize as *mut u8;
21499    }
21500    <Arch as Syscalls>::syscall1(sysno(12, 214), 0) as *mut u8
21501}
21502
21503#[no_mangle]
21504pub unsafe extern "C" fn scalb(x: f64, exp: f64) -> f64 {
21505    if x.is_nan() || exp.is_nan() { return x * exp; }
21506    if !exp.is_finite() {
21507        let r = if exp > 0.0 { x * exp } else { x / (-exp) };
21508        if r.is_nan() && !x.is_nan() {
21509            feraiseexcept(FE_INVALID);
21510        }
21511        return r;
21512    }
21513    if libm::rint(exp) != exp {
21514        return __math_invalid(exp);
21515    }
21516    if exp > 65000.0 { return libm::scalbn(x, 65000); }
21517    if -exp > 65000.0 { return libm::scalbn(x, -65000); }
21518    libm::scalbn(x, exp as i32)
21519}
21520
21521#[no_mangle]
21522pub unsafe extern "C" fn scalbf(x: f32, exp: f32) -> f32 {
21523    if x.is_nan() || exp.is_nan() { return x * exp; }
21524    if !exp.is_finite() {
21525        let r = if exp > 0.0 { x * exp } else { x / (-exp) };
21526        if r.is_nan() && !x.is_nan() {
21527            feraiseexcept(FE_INVALID);
21528        }
21529        return r;
21530    }
21531    if libm::rintf(exp) != exp {
21532        return __math_invalidf(exp);
21533    }
21534    if exp > 65000.0 { return libm::scalbnf(x, 65000); }
21535    if -exp > 65000.0 { return libm::scalbnf(x, -65000); }
21536    libm::scalbnf(x, exp as i32)
21537}
21538
21539#[no_mangle]
21540pub unsafe extern "C" fn __sched_cpucount(setsize: usize, setp: *const u8) -> i32 {
21541    let mut count = 0;
21542    let mut i = 0;
21543    while i < setsize * 8 {
21544        if (*setp.add(i / 8) >> (i % 8)) & 1 != 0 { count += 1; }
21545        i += 1;
21546    }
21547    count
21548}
21549
21550
21551
21552#[no_mangle]
21553pub unsafe extern "C" fn select(nfds: i32, readfds: *mut u8, writefds: *mut u8, exceptfds: *mut u8, timeout: *mut core::ffi::c_void) -> i32 {
21554    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
21555}
21556
21557
21558
21559#[no_mangle]
21560pub unsafe extern "C" fn sendfile(out_fd: i32, in_fd: i32, offset: *mut i64, count: usize) -> isize {
21561    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
21562}
21563
21564
21565
21566
21567
21568#[no_mangle]
21569pub unsafe extern "C" fn __setjmp(env: *mut core::ffi::c_void) -> i32 {
21570    crate::setjmp(env as *mut u64)
21571}
21572
21573#[no_mangle]
21574pub unsafe extern "C" fn _setjmp(env: *mut core::ffi::c_void) -> i32 {
21575    crate::setjmp(env as *mut u64)
21576}
21577
21578#[no_mangle]
21579pub unsafe extern "C" fn setlinebuf(stream: *mut core::ffi::c_void) {
21580    setvbuf(stream as *mut FILE, core::ptr::null_mut(), 1, 0);
21581}
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597#[no_mangle]
21598pub unsafe extern "C" fn significand(x: f64) -> f64 {
21599    let bits = x.to_bits();
21600    let exp = ((bits >> 52) & 0x7ff) as i32;
21601    if exp == 0 || exp == 0x7ff { return x; }
21602    f64::from_bits((bits & 0x000fffffffffffff) | (1023u64 << 52))
21603}
21604
21605#[no_mangle]
21606pub unsafe extern "C" fn significandf(x: f32) -> f32 {
21607    let bits = x.to_bits();
21608    let exp = ((bits >> 23) & 0xff) as i32;
21609    if exp == 0 || exp == 0xff { return x; }
21610    f32::from_bits((bits & 0x007fffff) | (127u32 << 23))
21611}
21612
21613
21614
21615
21616
21617#[no_mangle]
21618pub unsafe extern "C" fn sigset(sig: i32, handler: usize) -> usize {
21619    // BSD/glibc-compatible sigset() is an alias for signal().
21620    signal(sig, handler)
21621}
21622
21623#[no_mangle]
21624pub unsafe extern "C" fn sincos(x: f64, sin: *mut f64, cos: *mut f64) {
21625    *sin = libm::sin(x);
21626    *cos = libm::cos(x);
21627}
21628
21629#[no_mangle]
21630pub unsafe extern "C" fn sincosf(x: f32, sin: *mut f32, cos: *mut f32) {
21631    *sin = libm::sinf(x);
21632    *cos = libm::cosf(x);
21633}
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643unsafe fn nd_ascii_lower(c: c_char) -> c_int {
21644    let b = c as u8;
21645    if b >= b'A' && b <= b'Z' { (b + 32) as c_int } else { b as c_int }
21646}
21647
21648unsafe fn nd_strncasecmp(s1: *const c_char, s2: *const c_char, n: usize) -> c_int {
21649    let mut i = 0usize;
21650    while i < n {
21651        let c1 = nd_ascii_lower(*s1.add(i));
21652        let c2 = nd_ascii_lower(*s2.add(i));
21653        if c1 != c2 || c1 == 0 { return c1 - c2; }
21654        i += 1;
21655    }
21656    0
21657}
21658
21659#[no_mangle]
21660pub unsafe extern "C" fn strcasecmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> i32 {
21661    nd_strncasecmp(s1, s2, usize::MAX)
21662}
21663
21664#[no_mangle]
21665pub 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 {
21666    nd_strncasecmp(s1, s2, usize::MAX)
21667}
21668
21669#[no_mangle]
21670pub unsafe extern "C" fn strcasestr(haystack: *const core::ffi::c_char, needle: *const core::ffi::c_char) -> *mut core::ffi::c_char {
21671    let nlen = crate::strlen(needle);
21672    if nlen == 0 { return haystack as *mut core::ffi::c_char; }
21673    let mut i = 0;
21674    loop {
21675        let h = haystack.add(i);
21676        if *h == 0 { return core::ptr::null_mut(); }
21677        if crate::strncasecmp(h, needle, nlen) == 0 { return h as *mut core::ffi::c_char; }
21678        i += 1;
21679    }
21680}
21681
21682#[no_mangle]
21683pub 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 {
21684    crate::strcmp(s1 as *const u8, s2 as *const u8)
21685}
21686
21687#[no_mangle]
21688pub unsafe extern "C" fn strncasecmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char, n: usize) -> i32 {
21689    nd_strncasecmp(s1, s2, n)
21690}
21691
21692#[no_mangle]
21693pub 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 {
21694    nd_strncasecmp(s1, s2, n)
21695}
21696
21697#[no_mangle]
21698pub unsafe extern "C" fn strsep(stringp: *mut *mut core::ffi::c_char, delim: *const core::ffi::c_char) -> *mut core::ffi::c_char {
21699    let s = *stringp;
21700    if s.is_null() { return core::ptr::null_mut(); }
21701    let mut p = s;
21702    while *p != 0 {
21703        let mut d = delim;
21704        while *d != 0 {
21705            if *p == *d { *p = 0; *stringp = p.add(1); return s; }
21706            d = d.add(1);
21707        }
21708        p = p.add(1);
21709    }
21710    *stringp = core::ptr::null_mut();
21711    s
21712}
21713
21714#[no_mangle]
21715pub unsafe extern "C" fn strtoimax(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, base: i32) -> i64 {
21716    crate::strtol(nptr, endptr, base)
21717}
21718
21719#[no_mangle]
21720pub 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 {
21721    let mut s = if s.is_null() { *saveptr } else { s };
21722    if s.is_null() { return core::ptr::null_mut(); }
21723    // Skip leading delimiters
21724    while *s != 0 {
21725        let mut d = delim;
21726        let mut found = false;
21727        while *d != 0 {
21728            if *s == *d { found = true; break; }
21729            d = d.add(1);
21730        }
21731        if !found { break; }
21732        s = s.add(1);
21733    }
21734    if *s == 0 { *saveptr = s; return core::ptr::null_mut(); }
21735    let start = s;
21736    // Find end of token
21737    while *s != 0 {
21738        let mut d = delim;
21739        while *d != 0 {
21740            if *s == *d { *s = 0; *saveptr = s.add(1); return start; }
21741            d = d.add(1);
21742        }
21743        s = s.add(1);
21744    }
21745    *saveptr = s;
21746    start
21747}
21748
21749#[no_mangle]
21750pub unsafe extern "C" fn strtoumax(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, base: i32) -> u64 {
21751    crate::strtoul(nptr, endptr, base) as u64
21752}
21753
21754#[no_mangle]
21755pub 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 {
21756    crate::strlcpy(dest as *mut u8, src as *const u8, n)
21757}
21758
21759#[no_mangle]
21760pub unsafe extern "C" fn swab(src: *const u8, dest: *mut u8, nbytes: isize) {
21761    let mut i = 0;
21762    while i + 1 < nbytes {
21763        let a = *src.add(i as usize);
21764        let b = *src.add(i as usize + 1);
21765        *dest.add(i as usize) = b;
21766        *dest.add(i as usize + 1) = a;
21767        i += 2;
21768    }
21769}
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781#[no_mangle]
21782pub unsafe extern "C" fn __tolower_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
21783    if c >= 'A' as i32 && c <= 'Z' as i32 { c + 32 } else { c }
21784}
21785
21786#[no_mangle]
21787pub unsafe extern "C" fn __toupper_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
21788    if c >= 'a' as i32 && c <= 'z' as i32 { c - 32 } else { c }
21789}
21790
21791#[no_mangle]
21792pub unsafe extern "C" fn ulimit(cmd: c_int, mut args: ...) -> c_long {
21793    let mut rl: Rlimit = core::mem::zeroed();
21794    if getrlimit(RLIMIT_FSIZE, &mut rl) != 0 { return -1; }
21795    if cmd == 2 {
21796        let val = args.next_arg::<c_long>();
21797        rl.rlim_cur = 512u64.wrapping_mul(val as u64);
21798        if setrlimit(RLIMIT_FSIZE, &rl) != 0 { return -1; }
21799    }
21800    (rl.rlim_cur / 512) as c_long
21801}
21802
21803#[repr(C)]
21804struct UtsName {
21805    sysname: [u8; 65],
21806    nodename: [u8; 65],
21807    release: [u8; 65],
21808    version: [u8; 65],
21809    machine: [u8; 65],
21810    domainname: [u8; 65],
21811}
21812
21813#[no_mangle]
21814pub unsafe extern "C" fn uname(buf: *mut c_void) -> c_int {
21815    // Let the kernel validate the user pointer: an invalid but non-null
21816    // address must produce EFAULT instead of a fault in a local copy.
21817    let r = <Arch as Syscalls>::syscall1(SYS_UNAME, buf as i64);
21818    syscall_ret(r) as c_int
21819}
21820
21821#[no_mangle]
21822pub unsafe extern "C" fn unshare(flags: i32) -> i32 {
21823    let r = <Arch as Syscalls>::syscall1(SYS_UNSHARE, flags as i64);
21824    syscall_ret(r) as c_int
21825}
21826
21827#[no_mangle]
21828pub unsafe extern "C" fn updwtmpx(wtmpx_file: *const core::ffi::c_char, utx: *const core::ffi::c_void) {
21829    updwtmp(wtmpx_file, utx)
21830}
21831
21832#[no_mangle]
21833pub unsafe extern "C" fn __uselocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
21834    loc
21835}
21836
21837#[repr(C)]
21838pub struct Utimbuf { actime: i64, modtime: i64 }
21839
21840#[no_mangle]
21841pub unsafe extern "C" fn utime(filename: *const c_char, times: *const Utimbuf) -> c_int {
21842    if times.is_null() {
21843        return utimensat(AT_FDCWD, filename, core::ptr::null(), 0);
21844    }
21845    let ts = [
21846        timespec { tv_sec: (*times).actime, tv_nsec: 0 },
21847        timespec { tv_sec: (*times).modtime, tv_nsec: 0 },
21848    ];
21849    utimensat(AT_FDCWD, filename, ts.as_ptr(), 0)
21850}
21851
21852#[no_mangle]
21853pub unsafe extern "C" fn vhangup() -> c_int {
21854    let r = <Arch as Syscalls>::syscall0(SYS_VHANGUP);
21855    syscall_ret(r) as c_int
21856}
21857
21858#[no_mangle]
21859pub unsafe extern "C" fn vmsplice(fd: i32, iov: *const c_void, nr_segs: usize, flags: u32) -> isize {
21860    let r = <Arch as Syscalls>::syscall4(SYS_VMSPLICE, fd as i64, iov as i64, nr_segs as i64, flags as i64);
21861    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
21862}
21863
21864
21865
21866#[no_mangle]
21867pub unsafe extern "C" fn wait4(pid: i32, wstatus: *mut i32, options: i32, rusage: *mut core::ffi::c_void) -> i32 {
21868    syscall_ret(<Arch as Syscalls>::syscall4(SYS_WAIT4, pid as i64, wstatus as i64, options as i64, rusage as i64)) as i32
21869}
21870
21871#[no_mangle]
21872pub unsafe extern "C" fn waitid(idtype: i32, id: u32, infop: *mut core::ffi::c_void, options: i32) -> i32 {
21873    // The kernel takes a fifth rusage pointer; it must be NULL, not whatever
21874    // happens to be in r10.
21875    syscall_ret(<Arch as Syscalls>::syscall5(
21876        sysno(247, 95),
21877        idtype as i64,
21878        id as i64,
21879        infop as i64,
21880        options as i64,
21881        0,
21882    )) as i32
21883}
21884
21885#[no_mangle]
21886pub unsafe extern "C" fn __wcscoll_l(s1: *const u32, s2: *const u32, _loc: *mut core::ffi::c_void) -> i32 {
21887    crate::wcscmp(s1 as *const i32, s2 as *const i32)
21888}
21889
21890#[no_mangle]
21891pub unsafe extern "C" fn __wcsxfrm_l(dest: *mut u32, src: *const u32, n: usize, _loc: *mut core::ffi::c_void) -> usize {
21892    wcsxfrm(dest as *mut wchar_t, src as *const wchar_t, n)
21893}
21894
21895#[inline]
21896fn wctable_width(table: &[u8], wc: u32) -> bool {
21897    let page = table[(wc >> 8) as usize] as usize;
21898    (table[page * 32 + ((wc & 255) >> 3) as usize] >> (wc & 7)) & 1 != 0
21899}
21900
21901#[no_mangle]
21902pub unsafe extern "C" fn wcwidth(c: u32) -> i32 {
21903    // Port of musl's wcwidth, using the nonspacing/wide tables.
21904    let wc = c;
21905    if wc < 0xff {
21906        return if ((wc + 1) & 0x7f) >= 0x21 {
21907            1
21908        } else if wc != 0 {
21909            -1
21910        } else {
21911            0
21912        };
21913    }
21914    if (wc & 0xfffe_ffff) < 0xfffe {
21915        if wctable_width(&WCTYPE_NONSPACING_TABLE, wc) {
21916            return 0;
21917        }
21918        if wctable_width(&WCTYPE_WIDE_TABLE, wc) {
21919            return 2;
21920        }
21921        return 1;
21922    }
21923    if (wc & 0xfffe) == 0xfffe {
21924        return -1;
21925    }
21926    if wc.wrapping_sub(0x20000) < 0x20000 {
21927        return 2;
21928    }
21929    if wc == 0xe0001 || wc.wrapping_sub(0xe0020) < 0x5f || wc.wrapping_sub(0xe0100) < 0xef {
21930        return 0;
21931    }
21932    1
21933}
21934
21935
21936
21937
21938
21939// ============================================================
21940// Final missing symbols
21941// ============================================================
21942
21943
21944
21945#[no_mangle]
21946pub 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 {
21947    crate::strtod(nptr, endptr)
21948}
21949
21950#[no_mangle]
21951pub 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 {
21952    crate::strtof(nptr, endptr)
21953}
21954
21955#[no_mangle]
21956pub 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 {
21957    crate::strtod(nptr, endptr)
21958}
21959
21960// ============================================================
21961// Directory operations - real implementations
21962// ============================================================
21963
21964#[repr(C)]
21965struct linux_dirent64 {
21966    d_ino: u64,
21967    d_off: i64,
21968    d_reclen: u16,
21969    d_type: u8,
21970    d_name: [u8; 0], // flexible array
21971}
21972
21973// Directory streams used to be a process-wide singleton, which broke any
21974// nested opendir/readdir sequence (git, find, glob, ...). Each DIR now owns
21975// its fd and read buffer, like musl's __dirstream.
21976const DIR_BUF_SIZE: usize = 4096;
21977
21978#[repr(C)]
21979struct DirStream {
21980    fd: i32,
21981    pos: usize,
21982    len: usize,
21983    last_off: i64,
21984    buf: [u8; DIR_BUF_SIZE],
21985}
21986
21987unsafe fn dir_stream_new(fd: i32) -> *mut core::ffi::c_void {
21988    let ds = malloc(core::mem::size_of::<DirStream>()) as *mut DirStream;
21989    if ds.is_null() {
21990        crate::close(fd);
21991        ERRNO!() = ENOMEM;
21992        return core::ptr::null_mut();
21993    }
21994    core::ptr::write_bytes(ds, 0, 1);
21995    (*ds).fd = fd;
21996    ds as *mut core::ffi::c_void
21997}
21998
21999#[no_mangle]
22000pub unsafe extern "C" fn opendir(dirname: *const core::ffi::c_char) -> *mut core::ffi::c_void {
22001    let fd = openat(AT_FDCWD, dirname, O_DIRECTORY, 0); // O_RDONLY | O_DIRECTORY
22002    if fd < 0 { return core::ptr::null_mut(); }
22003    dir_stream_new(fd)
22004}
22005
22006#[no_mangle]
22007pub unsafe extern "C" fn closedir(dirp: *mut core::ffi::c_void) -> i32 {
22008    if dirp.is_null() { ERRNO!() = 22; return -1; }
22009    let ds = dirp as *mut DirStream;
22010    let r = crate::close((*ds).fd);
22011    free(dirp);
22012    r
22013}
22014
22015#[no_mangle]
22016pub unsafe extern "C" fn readdir(dirp: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
22017    if dirp.is_null() { ERRNO!() = 22; return core::ptr::null_mut(); }
22018    let ds = &mut *(dirp as *mut DirStream);
22019
22020    loop {
22021        if ds.pos >= ds.len {
22022            let nread = syscall_ret(<Arch as Syscalls>::syscall3(
22023                SYS_GETDENTS64,
22024                ds.fd as i64,
22025                ds.buf.as_mut_ptr() as i64,
22026                DIR_BUF_SIZE as i64,
22027            )) as isize;
22028            if nread <= 0 { return core::ptr::null_mut(); }
22029            ds.len = nread as usize;
22030            ds.pos = 0;
22031        }
22032
22033        let ent = ds.buf.as_ptr().add(ds.pos) as *const linux_dirent64;
22034        let ent_ref = &*ent;
22035        if ent_ref.d_reclen as usize == 0 {
22036            ds.len = 0;
22037            return core::ptr::null_mut();
22038        }
22039        ds.pos += ent_ref.d_reclen as usize;
22040        ds.last_off = ent_ref.d_off;
22041
22042        // Return a pointer into this stream's buffer (valid until next call).
22043        return ent as *mut core::ffi::c_void;
22044    }
22045}
22046
22047#[repr(C)]
22048struct DirentCopy {
22049    d_ino: u64,
22050    d_off: i64,
22051    d_reclen: u16,
22052    d_type: u8,
22053    d_name: [core::ffi::c_char; 256],
22054}
22055
22056#[no_mangle]
22057pub 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 {
22058    if dirp.is_null() || entry.is_null() || result.is_null() {
22059        return EINVAL;
22060    }
22061    let ent = readdir(dirp);
22062    if ent.is_null() {
22063        *result = core::ptr::null_mut();
22064        return 0;
22065    }
22066    let reclen = (* (ent as *const linux_dirent64)).d_reclen as usize;
22067    let copy = reclen.min(core::mem::size_of::<DirentCopy>());
22068    core::ptr::copy_nonoverlapping(ent as *const u8, entry as *mut u8, copy);
22069    *result = entry;
22070    0
22071}
22072
22073#[no_mangle]
22074pub unsafe extern "C" fn seekdir(dirp: *mut core::ffi::c_void, loc: i64) {
22075    if dirp.is_null() { return; }
22076    let ds = &mut *(dirp as *mut DirStream);
22077    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, loc, 0);
22078    ds.pos = 0;
22079    ds.len = 0;
22080}
22081
22082#[no_mangle]
22083pub unsafe extern "C" fn telldir(dirp: *mut core::ffi::c_void) -> i64 {
22084    if dirp.is_null() { return -1; }
22085    (*(dirp as *mut DirStream)).last_off
22086}
22087
22088#[no_mangle]
22089pub unsafe extern "C" fn rewinddir(dirp: *mut core::ffi::c_void) {
22090    if dirp.is_null() { return; }
22091    let ds = &mut *(dirp as *mut DirStream);
22092    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, 0, 0);
22093    ds.pos = 0;
22094    ds.len = 0;
22095    ds.last_off = 0;
22096}
22097
22098#[no_mangle]
22099pub unsafe extern "C" fn dirfd(dirp: *mut core::ffi::c_void) -> i32 {
22100    if dirp.is_null() { ERRNO!() = 22; return -1; }
22101    (*(dirp as *mut DirStream)).fd
22102}
22103
22104// ============================================================
22105// Memory management - real implementations
22106// ============================================================
22107
22108#[no_mangle]
22109pub unsafe extern "C" fn mprotect(addr: *mut u8, len: usize, prot: i32) -> i32 {
22110    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MPROTECT, addr as i64, len as i64, prot as i64)) as i32
22111}
22112
22113#[no_mangle]
22114pub unsafe extern "C" fn msync(addr: *mut u8, len: usize, flags: i32) -> i32 {
22115    syscall_ret(<Arch as Syscalls>::syscall3(sysno(26, 227), addr as i64, len as i64, flags as i64)) as i32
22116}
22117
22118#[no_mangle]
22119pub unsafe extern "C" fn mlock(addr: *const u8, len: usize) -> i32 {
22120    syscall_ret(<Arch as Syscalls>::syscall2(sysno(149, 228), addr as i64, len as i64)) as i32
22121}
22122
22123#[no_mangle]
22124pub unsafe extern "C" fn munlock(addr: *const u8, len: usize) -> i32 {
22125    syscall_ret(<Arch as Syscalls>::syscall2(sysno(150, 229), addr as i64, len as i64)) as i32
22126}
22127
22128#[no_mangle]
22129pub unsafe extern "C" fn mlockall(flags: i32) -> i32 {
22130    syscall_ret(<Arch as Syscalls>::syscall1(sysno(151, 230), flags as i64)) as i32
22131}
22132
22133#[no_mangle]
22134pub unsafe extern "C" fn munlockall() -> i32 {
22135    syscall_ret(<Arch as Syscalls>::syscall0(sysno(152, 231))) as i32
22136}
22137
22138#[no_mangle]
22139pub unsafe extern "C" fn madvise(addr: *mut u8, len: usize, advice: i32) -> i32 {
22140    syscall_ret(<Arch as Syscalls>::syscall3(sysno(28, 233), addr as i64, len as i64, advice as i64)) as i32
22141}
22142
22143#[no_mangle]
22144pub unsafe extern "C" fn mincore(addr: *mut u8, len: usize, vec: *mut u8) -> i32 {
22145    syscall_ret(<Arch as Syscalls>::syscall3(sysno(27, 232), addr as i64, len as i64, vec as i64)) as i32
22146}
22147
22148// ============================================================
22149
22150// ============================================================
22151// Missing math functions
22152// ============================================================
22153
22154#[no_mangle]
22155pub unsafe extern "C" fn drem(x: f64, y: f64) -> f64 {
22156    remainder(x, y)
22157}
22158
22159#[no_mangle]
22160pub unsafe extern "C" fn dremf(x: f32, y: f32) -> f32 {
22161    remainderf(x, y)
22162}
22163
22164#[no_mangle]
22165pub unsafe extern "C" fn pow10(x: f64) -> f64 {
22166    libm::pow(10.0, x)
22167}
22168
22169#[no_mangle]
22170pub unsafe extern "C" fn pow10f(x: f32) -> f32 {
22171    libm::powf(10.0, x)
22172}
22173
22174#[no_mangle]
22175pub unsafe extern "C" fn pow10l(x: f64) -> f64 {
22176    libm::pow(10.0, x)
22177}
22178
22179#[no_mangle]
22180pub unsafe extern "C" fn isless(x: f64, y: f64) -> i32 {
22181    if x.is_nan() || y.is_nan() { 0 } else { (x < y) as i32 }
22182}
22183
22184#[no_mangle]
22185pub unsafe extern "C" fn islessf(x: f32, y: f32) -> i32 {
22186    if x.is_nan() || y.is_nan() { 0 } else { (x < y) as i32 }
22187}
22188
22189#[no_mangle]
22190pub unsafe extern "C" fn lgamma_r(x: f64, signgamp: *mut i32) -> f64 {
22191    lgamma_r_impl(x, signgamp)
22192}
22193
22194#[no_mangle]
22195pub unsafe extern "C" fn lgammaf_r(x: f32, signgamp: *mut i32) -> f32 {
22196    if x.is_nan() {
22197        if !signgamp.is_null() { *signgamp = 1; }
22198        return x;
22199    }
22200    if x == 0.0 {
22201        if !signgamp.is_null() { *signgamp = if x.is_sign_negative() { -1 } else { 1 }; }
22202        feraiseexcept(FE_DIVBYZERO);
22203        return f32::INFINITY;
22204    }
22205    let (r, sign) = libm::lgammaf_r(x);
22206    if !signgamp.is_null() { *signgamp = sign; }
22207    r
22208}
22209
22210#[no_mangle]
22211pub unsafe extern "C" fn lgammal_r(x: f64, signgamp: *mut i32) -> f64 {
22212    lgamma_r(x, signgamp)
22213}
22214
22215// ============================================================
22216// Comparison macros
22217// ============================================================
22218
22219#[no_mangle]
22220pub unsafe extern "C" fn islessequal(x: f64, y: f64) -> i32 {
22221    if x.is_nan() || y.is_nan() { 0 } else { (x <= y) as i32 }
22222}
22223
22224#[no_mangle]
22225pub unsafe extern "C" fn islessequalf(x: f32, y: f32) -> i32 {
22226    if x.is_nan() || y.is_nan() { 0 } else { (x <= y) as i32 }
22227}
22228
22229#[no_mangle]
22230pub unsafe extern "C" fn islessgreater(x: f64, y: f64) -> i32 {
22231    if x.is_nan() || y.is_nan() { 0 } else { (x < y || x > y) as i32 }
22232}
22233
22234#[no_mangle]
22235pub unsafe extern "C" fn islessgreaterf(x: f32, y: f32) -> i32 {
22236    if x.is_nan() || y.is_nan() { 0 } else { (x < y || x > y) as i32 }
22237}
22238
22239#[no_mangle]
22240pub unsafe extern "C" fn isgreater(x: f64, y: f64) -> i32 {
22241    if x.is_nan() || y.is_nan() { 0 } else { (x > y) as i32 }
22242}
22243
22244#[no_mangle]
22245pub unsafe extern "C" fn isgreaterf(x: f32, y: f32) -> i32 {
22246    if x.is_nan() || y.is_nan() { 0 } else { (x > y) as i32 }
22247}
22248
22249#[no_mangle]
22250pub unsafe extern "C" fn isgreaterequal(x: f64, y: f64) -> i32 {
22251    if x.is_nan() || y.is_nan() { 0 } else { (x >= y) as i32 }
22252}
22253
22254#[no_mangle]
22255pub unsafe extern "C" fn isgreaterequalf(x: f32, y: f32) -> i32 {
22256    if x.is_nan() || y.is_nan() { 0 } else { (x >= y) as i32 }
22257}
22258
22259// ============================================================
22260// musl ABI compatibility helpers
22261// ============================================================
22262
22263#[no_mangle]
22264pub unsafe extern "C" fn stpcpy(dest: *mut c_char, src: *const c_char) -> *mut c_char {
22265    let mut d = dest;
22266    let mut s = src;
22267    while *s != 0 {
22268        *d = *s;
22269        d = d.add(1);
22270        s = s.add(1);
22271    }
22272    *d = 0;
22273    d
22274}
22275
22276#[no_mangle]
22277pub unsafe extern "C" fn stpncpy(dest: *mut c_char, src: *const c_char, n: usize) -> *mut c_char {
22278    let mut i = 0;
22279    while i < n && *src.add(i) != 0 {
22280        *dest.add(i) = *src.add(i);
22281        i += 1;
22282    }
22283    let end = dest.add(i);
22284    while i < n {
22285        *dest.add(i) = 0;
22286        i += 1;
22287    }
22288    end
22289}
22290
22291#[no_mangle]
22292pub unsafe extern "C" fn strchrnul(s: *const c_char, c: c_int) -> *mut c_char {
22293    let mut p = s;
22294    while *p != 0 && *p as c_int != c {
22295        p = p.add(1);
22296    }
22297    p as *mut c_char
22298}
22299
22300#[no_mangle]
22301pub unsafe extern "C" fn fstatat(dirfd: c_int, path: *const c_char, buf: *mut Stat, flags: c_int) -> c_int {
22302    let r = sys_newfstatat(dirfd, path, buf as *mut u8, flags);
22303    syscall_ret(r) as c_int
22304}
22305
22306#[no_mangle]
22307pub unsafe extern "C" fn execvpe(
22308    file: *const c_char,
22309    argv: *const *const c_char,
22310    envp: *const *const c_char,
22311) -> c_int {
22312    ERRNO!() = ENOENT;
22313    if file.is_null() || *file == 0 {
22314        return -1;
22315    }
22316    let mut p = file;
22317    while *p != 0 {
22318        if *p == b'/' as c_char {
22319            return execve(file, argv, envp);
22320        }
22321        p = p.add(1);
22322    }
22323    let file_len = crate::strlen(file);
22324    let path = crate::getenv(b"PATH\0".as_ptr() as *const c_char);
22325    let default_path = b"/usr/local/bin:/bin:/usr/bin\0";
22326    let path = if path.is_null() { default_path.as_ptr() as *const c_char } else { path };
22327
22328    let mut seen_eacces = false;
22329    let mut buf = [0 as c_char; 4096];
22330    let mut dir = path;
22331    loop {
22332        let mut end = dir;
22333        while *end != 0 && *end != b':' as c_char { end = end.add(1); }
22334        let dlen = end.offset_from(dir) as usize;
22335        // An empty PATH component means the current directory (no slash).
22336        let need_slash = dlen > 0;
22337        let total = dlen + need_slash as usize + file_len;
22338        if total < buf.len() {
22339            let mut i = 0;
22340            while i < dlen { buf[i] = *dir.add(i); i += 1; }
22341            if need_slash { buf[i] = b'/' as c_char; i += 1; }
22342            let mut j = 0;
22343            while j < file_len { buf[i + j] = *file.add(j); j += 1; }
22344            buf[i + j] = 0;
22345            execve(buf.as_ptr(), argv, envp);
22346            match ERRNO!() {
22347                13 => seen_eacces = true, // EACCES
22348                2 | 20 => {}              // ENOENT, ENOTDIR: try next
22349                _ => return -1,
22350            }
22351        }
22352        if *end == 0 { break; }
22353        dir = end.add(1);
22354    }
22355    ERRNO!() = if seen_eacces { 13 } else { 2 };
22356    -1
22357}
22358
22359// Locale-aware entry points. keel currently has a single global locale,
22360// so these are source/ABI-compatible wrappers around the normal functions.
22361#[no_mangle]
22362pub unsafe extern "C" fn strcoll_l(s1: *const c_char, s2: *const c_char, _loc: locale_t) -> c_int {
22363    strcoll(s1, s2)
22364}
22365
22366#[no_mangle]
22367pub unsafe extern "C" fn strxfrm_l(dest: *mut c_char, src: *const c_char, n: usize, _loc: locale_t) -> usize {
22368    strxfrm(dest, src, n)
22369}
22370
22371#[no_mangle]
22372pub unsafe extern "C" fn strerror_l(errnum: c_int, _loc: locale_t) -> *mut c_char {
22373    strerror(errnum)
22374}
22375
22376#[no_mangle]
22377pub unsafe extern "C" fn strcasecmp_l(s1: *const c_char, s2: *const c_char, _loc: locale_t) -> c_int {
22378    strcasecmp(s1, s2)
22379}
22380
22381#[no_mangle]
22382pub unsafe extern "C" fn strncasecmp_l(s1: *const c_char, s2: *const c_char, n: usize, _loc: locale_t) -> c_int {
22383    strncasecmp(s1, s2, n)
22384}
22385
22386#[no_mangle]
22387pub unsafe extern "C" fn strftime_l(s: *mut c_char, max: usize, fmt: *const c_char, tm: *const tm, _loc: locale_t) -> usize {
22388    strftime(s, max, fmt, tm)
22389}
22390
22391#[no_mangle]
22392pub unsafe extern "C" fn nl_langinfo_l(item: c_int, _loc: locale_t) -> *mut c_char {
22393    nl_langinfo(item)
22394}
22395
22396#[no_mangle]
22397pub unsafe extern "C" fn wcscoll_l(s1: *const u32, s2: *const u32, _loc: locale_t) -> c_int {
22398    wcscoll(s1, s2)
22399}
22400
22401#[no_mangle]
22402pub unsafe extern "C" fn wcsxfrm_l(dst: *mut wchar_t, src: *const wchar_t, n: usize, _loc: locale_t) -> usize {
22403    wcsxfrm(dst, src, n)
22404}
22405
22406#[no_mangle]
22407pub unsafe extern "C" fn wcsftime_l(s: *mut u32, max: usize, fmt: *const u32, tm: *const c_void, _loc: locale_t) -> usize {
22408    wcsftime(s, max, fmt, tm)
22409}
22410
22411#[no_mangle]
22412pub unsafe extern "C" fn wctype_l(name: *const c_char, _loc: locale_t) -> wctype_t {
22413    wctype(name)
22414}
22415
22416#[no_mangle]
22417pub unsafe extern "C" fn wctrans_l(name: *const c_char, _loc: locale_t) -> wctrans_t {
22418    wctrans(name)
22419}
22420
22421#[no_mangle]
22422pub unsafe extern "C" fn towlower_l(c: wint_t, _loc: locale_t) -> wint_t {
22423    towlower(c)
22424}
22425
22426#[no_mangle]
22427pub unsafe extern "C" fn towupper_l(c: wint_t, _loc: locale_t) -> wint_t {
22428    towupper(c)
22429}
22430
22431#[no_mangle]
22432pub unsafe extern "C" fn towctrans_l(c: wint_t, desc: wctrans_t, _loc: locale_t) -> wint_t {
22433    towctrans(c, desc)
22434}
22435
22436#[no_mangle] pub unsafe extern "C" fn iswalnum_l(c: wint_t, _l: locale_t) -> c_int { iswalnum(c) }
22437#[no_mangle] pub unsafe extern "C" fn iswalpha_l(c: wint_t, _l: locale_t) -> c_int { iswalpha(c) }
22438#[no_mangle] pub unsafe extern "C" fn iswblank_l(c: wint_t, _l: locale_t) -> c_int { iswblank(c) }
22439#[no_mangle] pub unsafe extern "C" fn iswcntrl_l(c: wint_t, _l: locale_t) -> c_int { iswcntrl(c) }
22440#[no_mangle] pub unsafe extern "C" fn iswdigit_l(c: wint_t, _l: locale_t) -> c_int { iswdigit(c) }
22441#[no_mangle] pub unsafe extern "C" fn iswgraph_l(c: wint_t, _l: locale_t) -> c_int { iswgraph(c) }
22442#[no_mangle] pub unsafe extern "C" fn iswlower_l(c: wint_t, _l: locale_t) -> c_int { iswlower(c) }
22443#[no_mangle] pub unsafe extern "C" fn iswprint_l(c: wint_t, _l: locale_t) -> c_int { iswprint(c) }
22444#[no_mangle] pub unsafe extern "C" fn iswpunct_l(c: wint_t, _l: locale_t) -> c_int { iswpunct(c) }
22445#[no_mangle] pub unsafe extern "C" fn iswspace_l(c: wint_t, _l: locale_t) -> c_int { iswspace(c) }
22446#[no_mangle] pub unsafe extern "C" fn iswupper_l(c: wint_t, _l: locale_t) -> c_int { iswupper(c) }
22447#[no_mangle] pub unsafe extern "C" fn iswxdigit_l(c: wint_t, _l: locale_t) -> c_int { iswxdigit(c) }
22448#[no_mangle] pub unsafe extern "C" fn iswctype_l(c: wint_t, desc: wctype_t, _l: locale_t) -> c_int { iswctype(c, desc) }
22449
22450// ISO C99 scanf ABI aliases expected by musl binaries.
22451#[no_mangle] pub unsafe extern "C" fn __isoc99_scanf(fmt: *const c_char, args: ...) -> c_int { vfscanf(stdin, fmt, args) }
22452#[no_mangle] pub unsafe extern "C" fn __isoc99_fscanf(f: *mut FILE, fmt: *const c_char, args: ...) -> c_int { vfscanf(f, fmt, args) }
22453#[no_mangle] pub unsafe extern "C" fn __isoc99_sscanf(s: *const c_char, fmt: *const c_char, args: ...) -> c_int { vsscanf(s, fmt, args) }
22454#[no_mangle] pub unsafe extern "C" fn __isoc99_vscanf(fmt: *const c_char, args: VaList) -> c_int { vfscanf(stdin, fmt, args) }
22455#[no_mangle] pub unsafe extern "C" fn __isoc99_vfscanf(f: *mut FILE, fmt: *const c_char, args: VaList) -> c_int { vfscanf(f, fmt, args) }
22456#[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) }
22457#[no_mangle] pub unsafe extern "C" fn __isoc99_wscanf(fmt: *const wchar_t, args: ...) -> c_int { vfwscanf(stdin, fmt, args) }
22458#[no_mangle] pub unsafe extern "C" fn __isoc99_fwscanf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int { vfwscanf(f, fmt, args) }
22459#[no_mangle] pub unsafe extern "C" fn __isoc99_swscanf(s: *const wchar_t, fmt: *const wchar_t, args: ...) -> c_int { vswscanf(s, fmt, args) }
22460#[no_mangle] pub unsafe extern "C" fn __isoc99_vwscanf(fmt: *const wchar_t, args: VaList) -> c_int { vfwscanf(stdin, fmt, args) }
22461#[no_mangle] pub unsafe extern "C" fn __isoc99_vfwscanf(f: *mut FILE, fmt: *const wchar_t, args: VaList) -> c_int { vfwscanf(f, fmt, args) }
22462#[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) }
22463
22464// Unlocked stdio entry points.  keel's stdio does not take FILE locks
22465// internally (see docs/limitations.md), so these are aliases for the normal
22466// entry points.
22467#[no_mangle] pub unsafe extern "C" fn clearerr_unlocked(f: *mut FILE) { clearerr(f) }
22468#[no_mangle] pub unsafe extern "C" fn feof_unlocked(f: *mut FILE) -> c_int { feof(f) }
22469#[no_mangle] pub unsafe extern "C" fn ferror_unlocked(f: *mut FILE) -> c_int { ferror(f) }
22470#[no_mangle] pub unsafe extern "C" fn fileno_unlocked(f: *mut FILE) -> c_int { fileno(f) }
22471#[no_mangle] pub unsafe extern "C" fn fflush_unlocked(f: *mut FILE) -> c_int { fflush(f) }
22472#[no_mangle] pub unsafe extern "C" fn fgetc_unlocked(f: *mut FILE) -> c_int { fgetc(f) }
22473#[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) }
22474#[no_mangle] pub unsafe extern "C" fn fputc_unlocked(c: c_int, f: *mut FILE) -> c_int { fputc(c, f) }
22475#[no_mangle] pub unsafe extern "C" fn fputs_unlocked(s: *const c_char, f: *mut FILE) -> c_int { fputs(s, f) }
22476#[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) }
22477#[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) }
22478#[no_mangle] pub unsafe extern "C" fn fgetwc_unlocked(f: *mut FILE) -> wint_t { fgetwc(f) }
22479#[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) }
22480#[no_mangle] pub unsafe extern "C" fn fputwc_unlocked(c: wchar_t, f: *mut FILE) -> wint_t { fputwc(c, f) }
22481#[no_mangle] pub unsafe extern "C" fn fputws_unlocked(s: *const wchar_t, f: *mut FILE) -> c_int { fputws(s, f) }
22482#[no_mangle] pub unsafe extern "C" fn getwc_unlocked(f: *mut c_void) -> wint_t { getwc(f) }
22483#[no_mangle] pub unsafe extern "C" fn putwc_unlocked(c: u32, f: *mut c_void) -> wint_t { putwc(c, f) }
22484#[no_mangle] pub unsafe extern "C" fn getwchar_unlocked() -> wint_t { getwchar() }
22485#[no_mangle] pub unsafe extern "C" fn putwchar_unlocked(c: wchar_t) -> wint_t { putwchar(c) }
22486#[no_mangle] pub unsafe extern "C" fn fpurge(f: *mut FILE) { clearerr(f) }
22487#[no_mangle] pub unsafe extern "C" fn _IO_getc(f: *mut FILE) -> c_int { getc(f) }
22488#[no_mangle] pub unsafe extern "C" fn _IO_putc(c: c_int, f: *mut FILE) -> c_int { putc(c, f) }
22489#[no_mangle] pub unsafe extern "C" fn _IO_getc_unlocked(f: *mut FILE) -> c_int { getc(f) }
22490#[no_mangle] pub unsafe extern "C" fn _IO_putc_unlocked(c: c_int, f: *mut FILE) -> c_int { putc(c, f) }
22491#[no_mangle] pub unsafe extern "C" fn _IO_feof_unlocked(f: *mut FILE) -> c_int { feof(f) }
22492#[no_mangle] pub unsafe extern "C" fn _IO_ferror_unlocked(f: *mut FILE) -> c_int { ferror(f) }
22493
22494// ABI aliases used by musl and older C libraries.
22495#[no_mangle] pub unsafe extern "C" fn __getauxval(t: c_ulong) -> c_ulong { getauxval(t) }
22496#[no_mangle] pub unsafe extern "C" fn __longjmp(env: *const c_ulong, val: c_int) -> ! { longjmp(env, val) }
22497#[no_mangle] pub unsafe extern "C" fn bsd_signal(sig: c_int, handler: usize) -> usize { signal(sig, handler) }
22498#[no_mangle] pub unsafe extern "C" fn __sysv_signal(sig: c_int, handler: usize) -> usize { signal(sig, handler) }
22499#[no_mangle] pub unsafe extern "C" fn eaccess(path: *const c_char, mode: c_int) -> c_int { access(path, mode) }
22500#[no_mangle] pub unsafe extern "C" fn __xpg_basename(path: *mut c_char) -> *mut c_char { basename(path) }
22501#[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) }
22502#[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) }
22503
22504// ============================================================
22505// Remaining musl ABI entry points
22506// ============================================================
22507
22508#[no_mangle]
22509pub unsafe extern "C" fn cfsetspeed(termios_p: *mut c_void, speed: u32) -> c_int {
22510    let r = cfsetispeed(termios_p, speed);
22511    if r != 0 { return r; }
22512    cfsetospeed(termios_p, speed)
22513}
22514
22515#[no_mangle]
22516pub unsafe extern "C" fn futimesat(dirfd: c_int, path: *const c_char, times: *const timeval) -> c_int {
22517    if times.is_null() {
22518        return utimensat(dirfd, path, core::ptr::null(), 0);
22519    }
22520    let tv = times as *const [timeval; 2];
22521    let mut ts: [timespec; 2] = [
22522        timespec { tv_sec: (*tv)[0].tv_sec, tv_nsec: (*tv)[0].tv_usec * 1000 },
22523        timespec { tv_sec: (*tv)[1].tv_sec, tv_nsec: (*tv)[1].tv_usec * 1000 },
22524    ];
22525    for t in &mut ts {
22526        if t.tv_nsec < 0 || t.tv_nsec >= 1_000_000_000 {
22527            ERRNO!() = EINVAL;
22528            return -1;
22529        }
22530    }
22531    utimensat(dirfd, path, ts.as_ptr(), 0)
22532}
22533
22534#[no_mangle]
22535pub unsafe extern "C" fn membarrier(cmd: c_int, flags: c_int, cpu_id: c_int) -> c_int {
22536    <Arch as Syscalls>::syscall3(SYS_MEMBARRIER, cmd as i64, flags as i64, cpu_id as i64) as c_int
22537}
22538
22539#[no_mangle]
22540pub unsafe extern "C" fn mremap(
22541    old_address: *mut c_void,
22542    old_size: usize,
22543    new_size: usize,
22544    flags: c_int,
22545    mut args: ...
22546) -> *mut c_void {
22547    let new_address = if flags & 2 != 0 { args.next_arg::<*mut c_void>() } else { core::ptr::null_mut() };
22548    let r = <Arch as Syscalls>::syscall5(
22549        SYS_MREMAP,
22550        old_address as i64,
22551        old_size as i64,
22552        new_size as i64,
22553        flags as i64,
22554        new_address as i64,
22555    );
22556    if r < 0 {
22557        ERRNO!() = (-r) as c_int;
22558        return (-1isize) as *mut c_void;
22559    }
22560    r as *mut c_void
22561}
22562
22563#[no_mangle]
22564pub unsafe extern "C" fn ptsname_r(fd: c_int, buf: *mut c_char, buflen: usize) -> c_int {
22565    let name = ptsname(fd);
22566    if name.is_null() { return -1; }
22567    let n = crate::strlen(name);
22568    if n + 1 > buflen {
22569        ERRNO!() = ERANGE;
22570        return ERANGE;
22571    }
22572    core::ptr::copy_nonoverlapping(name, buf, n + 1);
22573    0
22574}
22575
22576#[no_mangle]
22577pub unsafe extern "C" fn posix_getdents(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize {
22578    if flags != 0 {
22579        ERRNO!() = EINVAL;
22580        return -1;
22581    }
22582    let r = <Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, buf as i64, len as i64);
22583    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22584}
22585
22586#[no_mangle]
22587pub unsafe extern "C" fn riscv_flush_icache(start: *mut c_void, end: *mut c_void, flags: c_ulong) -> c_int {
22588    #[cfg(target_arch = "riscv64")]
22589    {
22590        let r = <Arch as Syscalls>::syscall3(259, start as i64, end as i64, flags as i64);
22591        syscall_ret(r) as c_int
22592    }
22593    #[cfg(not(target_arch = "riscv64"))]
22594    {
22595        let _ = (start, end, flags);
22596        0
22597    }
22598}
22599
22600#[no_mangle]
22601pub unsafe extern "C" fn __riscv_flush_icache(start: *mut c_void, end: *mut c_void, flags: c_ulong) -> c_int {
22602    riscv_flush_icache(start, end, flags)
22603}
22604
22605#[no_mangle]
22606pub unsafe extern "C" fn mkostemps(template: *mut c_char, suffixlen: c_int, flags: c_int) -> c_int {
22607    mkstemps_flags(template, suffixlen, flags)
22608}
22609
22610#[no_mangle]
22611pub unsafe extern "C" fn statfs(path: *const c_char, buf: *mut c_void) -> c_int {
22612    let r = <Arch as Syscalls>::syscall2(SYS_STATFS, path as i64, buf as i64);
22613    syscall_ret(r) as c_int
22614}
22615
22616#[no_mangle]
22617pub unsafe extern "C" fn fstatfs(fd: c_int, buf: *mut c_void) -> c_int {
22618    let r = <Arch as Syscalls>::syscall2(SYS_FSTATFS, fd as i64, buf as i64);
22619    syscall_ret(r) as c_int
22620}
22621
22622#[no_mangle]
22623pub unsafe extern "C" fn sysinfo(info: *mut c_void) -> c_int {
22624    let r = <Arch as Syscalls>::syscall1(SYS_SYSINFO, info as i64);
22625    syscall_ret(r) as c_int
22626}
22627
22628#[no_mangle]
22629pub unsafe extern "C" fn pthread_tryjoin_np(thread: PthreadT, retval: *mut *mut c_void) -> c_int {
22630    let slot = thread as *mut Thread;
22631    if slot.is_null() { return EINVAL; }
22632    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
22633    let tid = core::ptr::read_volatile(&raw const (*slot).tid);
22634    if tid > 0 { return EBUSY; }
22635    if tid < 0 { return EINVAL; }
22636    pthread_join(thread, retval)
22637}
22638
22639#[no_mangle]
22640pub unsafe extern "C" fn pthread_timedjoin_np(thread: PthreadT, retval: *mut *mut c_void, abstime: *const timespec) -> c_int {
22641    let slot = thread as *mut Thread;
22642    if slot.is_null() { return EINVAL; }
22643    if thread == pthread_self() { return EDEADLK; }
22644    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
22645    loop {
22646        let r = pthread_tryjoin_np(thread, retval);
22647        if r != EBUSY { return r; }
22648        let tid = core::ptr::read_volatile(&raw const (*slot).tid);
22649        if tid <= 0 { continue; }
22650        let e = futex_timedwait(&raw mut (*slot).tid, tid, abstime);
22651        if e == ETIMEDOUT { return ETIMEDOUT; }
22652    }
22653}
22654
22655
22656// utmp/utmpx are backed by the classic /var/run/utmp file.  musl itself
22657// leaves these as no-ops; keel provides the real file-backed API.
22658#[repr(C)]
22659pub struct UtmpExit {
22660    pub e_termination: i16,
22661    pub e_exit: i16,
22662}
22663
22664#[repr(C)]
22665pub struct Utmpx {
22666    pub ut_type: i16,
22667    pub __ut_pad1: i16,
22668    pub ut_pid: i32,
22669    pub ut_line: [c_char; 32],
22670    pub ut_id: [c_char; 4],
22671    pub ut_user: [c_char; 32],
22672    pub ut_host: [c_char; 256],
22673    pub ut_exit: UtmpExit,
22674    pub ut_session: i32,
22675    pub __ut_pad2: i32,
22676    pub ut_tv: timeval,
22677    pub ut_addr_v6: [u32; 4],
22678    pub __unused: [u8; 20],
22679}
22680
22681const UTMP_SIZE: usize = 400;
22682const _: [(); UTMP_SIZE] = [(); core::mem::size_of::<Utmpx>()];
22683
22684static mut UTMP_FD: c_int = -1;
22685static mut UTMP_PATH: [u8; 256] = [0; 256];
22686static mut UTMP_PATH_SET: bool = false;
22687#[repr(align(8))]
22688struct UtmpBuf([u8; UTMP_SIZE]);
22689static mut UTMP_BUF: UtmpBuf = UtmpBuf([0; UTMP_SIZE]);
22690
22691unsafe fn utmp_path_ptr() -> *const c_char {
22692    if !UTMP_PATH_SET {
22693        let default = b"/var/run/utmp\0";
22694        let mut i = 0;
22695        while i < default.len() && i < UTMP_PATH.len() {
22696            UTMP_PATH[i] = default[i];
22697            i += 1;
22698        }
22699        UTMP_PATH_SET = true;
22700    }
22701    UTMP_PATH.as_ptr() as *const c_char
22702}
22703
22704unsafe fn utmp_open_read() -> c_int {
22705    if UTMP_FD >= 0 {
22706        crate::close(UTMP_FD);
22707    }
22708    UTMP_FD = crate::open(utmp_path_ptr(), 0, 0);
22709    UTMP_FD
22710}
22711
22712unsafe fn utmp_open_append() -> c_int {
22713    crate::open(utmp_path_ptr(), 1 | 64 | 1024, 0o644)
22714}
22715
22716#[no_mangle]
22717pub unsafe extern "C" fn setutent() {
22718    let _ = utmp_open_read();
22719}
22720
22721#[no_mangle]
22722pub unsafe extern "C" fn endutent() {
22723    if UTMP_FD >= 0 {
22724        crate::close(UTMP_FD);
22725        UTMP_FD = -1;
22726    }
22727}
22728
22729#[no_mangle]
22730pub unsafe extern "C" fn getutent() -> *mut c_void {
22731    if UTMP_FD < 0 && utmp_open_read() < 0 {
22732        return core::ptr::null_mut();
22733    }
22734    let n = crate::read(UTMP_FD, UTMP_BUF.0.as_mut_ptr() as *mut c_void, UTMP_SIZE);
22735    if n == UTMP_SIZE as isize {
22736        UTMP_BUF.0.as_mut_ptr() as *mut c_void
22737    } else {
22738        core::ptr::null_mut()
22739    }
22740}
22741
22742unsafe fn utmp_id_eq(a: &[c_char; 4], b: &[c_char; 4]) -> bool {
22743    a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3]
22744}
22745
22746unsafe fn utmp_line_eq(a: &[c_char; 32], b: &[c_char; 32]) -> bool {
22747    let mut i = 0;
22748    while i < 32 {
22749        if a[i] != b[i] { return false; }
22750        if a[i] == 0 { return true; }
22751        i += 1;
22752    }
22753    true
22754}
22755
22756#[no_mangle]
22757pub unsafe extern "C" fn getutid(ut: *const c_void) -> *mut c_void {
22758    if ut.is_null() { return core::ptr::null_mut(); }
22759    let want = &*(ut as *const Utmpx);
22760    loop {
22761        let p = getutent();
22762        if p.is_null() { return p; }
22763        let cur = &*(p as *const Utmpx);
22764        let matched = match want.ut_type {
22765            1 | 2 | 3 | 4 => cur.ut_type == want.ut_type,
22766            _ => utmp_id_eq(&cur.ut_id, &want.ut_id)
22767                && (want.ut_type == 0 || cur.ut_type == want.ut_type),
22768        };
22769        if matched { return p; }
22770    }
22771}
22772
22773#[no_mangle]
22774pub unsafe extern "C" fn getutline(ut: *const c_void) -> *mut c_void {
22775    if ut.is_null() { return core::ptr::null_mut(); }
22776    let want = &*(ut as *const Utmpx);
22777    loop {
22778        let p = getutent();
22779        if p.is_null() { return p; }
22780        if utmp_line_eq(&(*(p as *const Utmpx)).ut_line, &want.ut_line) {
22781            return p;
22782        }
22783    }
22784}
22785
22786#[no_mangle]
22787pub unsafe extern "C" fn pututline(ut: *const c_void) -> *mut c_void {
22788    if ut.is_null() { return core::ptr::null_mut(); }
22789    let fd = utmp_open_append();
22790    if fd < 0 { return core::ptr::null_mut(); }
22791    let n = crate::write(fd, ut, UTMP_SIZE);
22792    crate::close(fd);
22793    if n == UTMP_SIZE as isize { ut as *mut c_void } else { core::ptr::null_mut() }
22794}
22795
22796#[no_mangle]
22797pub unsafe extern "C" fn updwtmp(file: *const c_char, ut: *const c_void) {
22798    if file.is_null() || ut.is_null() { return; }
22799    let fd = crate::open(file, 1 | 64 | 1024, 0o644);
22800    if fd >= 0 {
22801        let _ = crate::write(fd, ut, UTMP_SIZE);
22802        crate::close(fd);
22803    }
22804}
22805
22806unsafe fn utmp_set_name(file: *const c_char) -> c_int {
22807    if file.is_null() { return -1; }
22808    let len = crate::strlen(file);
22809    if len + 1 > UTMP_PATH.len() { return -1; }
22810    if UTMP_FD >= 0 {
22811        crate::close(UTMP_FD);
22812        UTMP_FD = -1;
22813    }
22814    core::ptr::copy_nonoverlapping(file, UTMP_PATH.as_mut_ptr() as *mut c_char, len + 1);
22815    UTMP_PATH_SET = true;
22816    0
22817}
22818
22819#[no_mangle]
22820pub unsafe extern "C" fn utmpname(file: *const c_char) -> c_int { utmp_set_name(file) }
22821
22822#[no_mangle]
22823pub unsafe extern "C" fn utmpxname(file: *const c_char) -> c_int { utmp_set_name(file) }
22824
22825
22826// Data symbols and internal aliases still referenced by some musl binaries.
22827#[no_mangle] pub static mut ___environ: *mut *mut c_char = core::ptr::null_mut();
22828#[no_mangle] pub static mut _environ: *mut *mut c_char = core::ptr::null_mut();
22829#[no_mangle] pub unsafe extern "C" fn __freelocale(loc: locale_t) { freelocale(loc) }
22830#[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) }
22831#[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) }
22832#[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) }
22833#[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) }
22834
22835#[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) }
22836#[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) }
22837#[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) }
22838#[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) }
22839#[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) }
22840#[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) }
22841
22842// ============================================================
22843// Resolver (UDP DNS)
22844// ============================================================
22845
22846const MAX_NS: usize = 3;
22847const MAX_SEARCH: usize = 6;
22848const HOST_NOT_FOUND: c_int = 1;
22849const TRY_AGAIN: c_int = 2;
22850const NO_RECOVERY: c_int = 3;
22851const NO_DATA: c_int = 4;
22852
22853static mut NS_COUNT: usize = 0;
22854static mut NS_ADDRS: [u32; MAX_NS] = [0; MAX_NS];
22855static mut SEARCH_COUNT: usize = 0;
22856static mut SEARCH_DOMAINS: [[u8; 256]; MAX_SEARCH] = [[0; 256]; MAX_SEARCH];
22857static RESOLV_PARSED: AtomicBool = AtomicBool::new(false);
22858static mut NAME_LOCK: c_int = 0;
22859static mut NAME_WAITERS: c_int = 0;
22860static mut RESOLV_INIT_LOCK: c_int = 0;
22861static mut RESOLV_INIT_WAITERS: c_int = 0;
22862
22863unsafe fn name_lock() {
22864    spinlock_lock(&raw mut NAME_LOCK, &raw mut NAME_WAITERS);
22865}
22866
22867unsafe fn name_unlock() {
22868    spinlock_unlock(&raw mut NAME_LOCK, &raw mut NAME_WAITERS);
22869}
22870
22871unsafe fn resolv_ensure() {
22872    if RESOLV_PARSED.load(Ordering::Acquire) {
22873        return;
22874    }
22875    spinlock_lock(&raw mut RESOLV_INIT_LOCK, &raw mut RESOLV_INIT_WAITERS);
22876    if !RESOLV_PARSED.load(Ordering::Acquire) {
22877        let _ = resolv_parse_config();
22878        RESOLV_PARSED.store(true, Ordering::Release);
22879    }
22880    spinlock_unlock(&raw mut RESOLV_INIT_LOCK, &raw mut RESOLV_INIT_WAITERS);
22881}
22882
22883#[repr(C)]
22884struct SockAddrIn {
22885    sin_family: u16,
22886    sin_port: u16,
22887    sin_addr: u32,
22888    sin_zero: [u8; 8],
22889}
22890
22891#[repr(C)]
22892struct PollFd {
22893    fd: c_int,
22894    events: i16,
22895    revents: i16,
22896}
22897
22898unsafe fn resolv_skip_ws(line: &[u8], mut i: usize) -> usize {
22899    while i < line.len() && (line[i] == b' ' || line[i] == b'\t') { i += 1; }
22900    i
22901}
22902
22903unsafe fn resolv_token<'a>(line: &'a [u8], mut i: usize) -> (&'a [u8], usize) {
22904    let start = i;
22905    while i < line.len() && line[i] != b' ' && line[i] != b'\t' && line[i] != b'#' { i += 1; }
22906    (&line[start..i], i)
22907}
22908
22909unsafe fn resolv_parse_config() -> c_int {
22910    NS_COUNT = 0;
22911    SEARCH_COUNT = 0;
22912    let path = b"/etc/resolv.conf\0";
22913    let fd = crate::open(path.as_ptr() as *const c_char, 0, 0);
22914    if fd < 0 { return -1; }
22915    let mut buf = [0u8; 4096];
22916    let n = crate::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len());
22917    crate::close(fd);
22918    if n <= 0 { return -1; }
22919    let len = n as usize;
22920    let mut i = 0;
22921    while i < len {
22922        let start = i;
22923        while i < len && buf[i] != b'\n' { i += 1; }
22924        let line = &buf[start..i];
22925        i += 1;
22926        let mut j = resolv_skip_ws(line, 0);
22927        if j >= line.len() || line[j] == b'#' { continue; }
22928        let (key, next) = resolv_token(line, j);
22929        j = next;
22930        if key == b"nameserver" {
22931            j = resolv_skip_ws(line, j);
22932            let (tok, _) = resolv_token(line, j);
22933            if !tok.is_empty() && NS_COUNT < MAX_NS {
22934                let mut name = [0u8; 64];
22935                let l = core::cmp::min(tok.len(), 63);
22936                name[..l].copy_from_slice(&tok[..l]);
22937                let addr = crate::inet_addr(name.as_ptr() as *const c_char);
22938                if addr != u32::MAX {
22939                    NS_ADDRS[NS_COUNT] = addr;
22940                    NS_COUNT += 1;
22941                }
22942            }
22943        } else if key == b"search" || key == b"domain" {
22944            loop {
22945                j = resolv_skip_ws(line, j);
22946                if j >= line.len() || line[j] == b'#' { break; }
22947                let (tok, next) = resolv_token(line, j);
22948                j = next;
22949                if tok.is_empty() { break; }
22950                if SEARCH_COUNT < MAX_SEARCH {
22951                    let l = core::cmp::min(tok.len(), 255);
22952                    SEARCH_DOMAINS[SEARCH_COUNT][..l].copy_from_slice(&tok[..l]);
22953                    SEARCH_DOMAINS[SEARCH_COUNT][l] = 0;
22954                    SEARCH_COUNT += 1;
22955                }
22956                if key == b"domain" { break; }
22957            }
22958        }
22959    }
22960    0
22961}
22962
22963#[no_mangle]
22964pub unsafe extern "C" fn res_init() -> c_int {
22965    resolv_ensure();
22966    0
22967}
22968
22969#[no_mangle]
22970pub unsafe extern "C" fn res_mkquery(
22971    op: c_int,
22972    dname: *const c_char,
22973    class: c_int,
22974    type_: c_int,
22975    _data: *const u8,
22976    _datalen: c_int,
22977    _newrr: *const u8,
22978    buf: *mut u8,
22979    buflen: c_int,
22980) -> c_int {
22981    if dname.is_null() || buf.is_null() { return -1; }
22982    let mut l = crate::strnlen(dname as *const u8, 255);
22983    if l > 0 && *dname.add(l - 1) == b'.' as c_char { l -= 1; }
22984    if l > 0 && *dname.add(l - 1) == b'.' as c_char { return -1; }
22985    let n = 17 + l + if l != 0 { 1 } else { 0 };
22986    if l > 253 || buflen < n as c_int || op < 0 || op > 15 || class < 0 || class > 255 || type_ < 0 || type_ > 255 {
22987        return -1;
22988    }
22989    let mut q = [0u8; 280];
22990    crate::memset(q.as_mut_ptr() as *mut c_void, 0, n);
22991    q[2] = (op * 8 + 1) as u8;
22992    q[3] = 32;
22993    q[5] = 1;
22994    core::ptr::copy_nonoverlapping(dname as *const u8, q.as_mut_ptr().add(13), l);
22995    let mut i = 13;
22996    while q[i] != 0 {
22997        let mut j = i;
22998        while q[j] != 0 && q[j] != b'.' { j += 1; }
22999        if j - i > 63 { return -1; }
23000        q[i - 1] = (j - i) as u8;
23001        i = j + 1;
23002    }
23003    q[i + 1] = type_ as u8;
23004    q[i + 3] = class as u8;
23005    let mut ts = timespec { tv_sec: 0, tv_nsec: 0 };
23006    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
23007    let id = (((ts.tv_nsec as u64) + (ts.tv_nsec as u64) / 65536) & 0xffff) as u16;
23008    q[0] = (id >> 8) as u8;
23009    q[1] = id as u8;
23010    core::ptr::copy_nonoverlapping(q.as_ptr(), buf, n);
23011    n as c_int
23012}
23013
23014unsafe fn res_send_inner(msg: *const u8, msglen: c_int, answer: *mut u8, anslen: c_int) -> c_int {
23015    if msg.is_null() || answer.is_null() || msglen < 12 || anslen < 12 { return -1; }
23016    resolv_ensure();
23017    if NS_COUNT == 0 {
23018        H_ERRNO!() = TRY_AGAIN;
23019        return -1;
23020    }
23021    for n in 0..NS_COUNT {
23022        let fd = crate::socket(AF_INET, SOCK_DGRAM, 0);
23023        if fd < 0 { continue; }
23024        let sa = SockAddrIn {
23025            sin_family: AF_INET as u16,
23026            sin_port: 53u16.to_be(),
23027            sin_addr: NS_ADDRS[n],
23028            sin_zero: [0; 8],
23029        };
23030        let sent = crate::sendto(fd, msg as *const c_void, msglen as usize, 0, &sa as *const SockAddrIn as *const crate::sockaddr, 16);
23031        if sent != msglen as isize {
23032            crate::close(fd);
23033            continue;
23034        }
23035        let mut pfd = PollFd { fd, events: 1, revents: 0 };
23036        let pr = crate::poll(&mut pfd as *mut PollFd as *mut c_void, 1, 5000);
23037        if pr <= 0 {
23038            crate::close(fd);
23039            continue;
23040        }
23041        let r = crate::recvfrom(fd, answer as *mut c_void, anslen as usize, 0, core::ptr::null_mut(), core::ptr::null_mut());
23042        crate::close(fd);
23043        if r >= 12 {
23044            let id_ok = *answer == *msg && *answer.add(1) == *msg.add(1);
23045            let qr = (*answer.add(2) & 0x80) != 0;
23046            if id_ok && qr {
23047                return r as c_int;
23048            }
23049        }
23050    }
23051    H_ERRNO!() = TRY_AGAIN;
23052    -1
23053}
23054
23055#[no_mangle]
23056pub unsafe extern "C" fn res_send(msg: *const u8, msglen: c_int, answer: *mut u8, anslen: c_int) -> c_int {
23057    if anslen < 512 {
23058        let mut buf = [0u8; 512];
23059        let r = res_send_inner(msg, msglen, buf.as_mut_ptr(), 512);
23060        if r >= 0 {
23061            let copy = core::cmp::min(r, anslen) as usize;
23062            if copy > 0 { core::ptr::copy_nonoverlapping(buf.as_ptr(), answer, copy); }
23063        }
23064        return r;
23065    }
23066    res_send_inner(msg, msglen, answer, anslen)
23067}
23068
23069#[no_mangle]
23070pub unsafe extern "C" fn res_query(
23071    dname: *const c_char,
23072    class: c_int,
23073    type_: c_int,
23074    answer: *mut u8,
23075    anslen: c_int,
23076) -> c_int {
23077    let mut q = [0u8; 280];
23078    let ql = res_mkquery(0, dname, class, type_, core::ptr::null(), 0, core::ptr::null(), q.as_mut_ptr(), q.len() as c_int);
23079    if ql < 0 { return ql; }
23080    let r = res_send(q.as_ptr(), ql, answer, anslen);
23081    if r < 12 {
23082        H_ERRNO!() = TRY_AGAIN;
23083        return -1;
23084    }
23085    let rcode = answer.add(3).read() & 0x0f;
23086    if rcode == 3 {
23087        H_ERRNO!() = HOST_NOT_FOUND;
23088        return -1;
23089    }
23090    if rcode == 0 && *answer.add(6) == 0 && *answer.add(7) == 0 {
23091        H_ERRNO!() = NO_DATA;
23092        return -1;
23093    }
23094    if rcode != 0 {
23095        H_ERRNO!() = NO_RECOVERY;
23096        return -1;
23097    }
23098    r
23099}
23100
23101#[no_mangle]
23102pub unsafe extern "C" fn res_querydomain(
23103    name: *const c_char,
23104    domain: *const c_char,
23105    class: c_int,
23106    type_: c_int,
23107    answer: *mut u8,
23108    anslen: c_int,
23109) -> c_int {
23110    if domain.is_null() || *domain == 0 { return res_query(name, class, type_, answer, anslen); }
23111    let mut buf = [0u8; 512];
23112    let nl = crate::strlen(name);
23113    let dl = crate::strlen(domain);
23114    if nl + 1 + dl >= buf.len() { return -1; }
23115    core::ptr::copy_nonoverlapping(name, buf.as_mut_ptr() as *mut c_char, nl);
23116    buf[nl] = b'.';
23117    core::ptr::copy_nonoverlapping(domain, buf.as_mut_ptr().add(nl + 1) as *mut c_char, dl);
23118    buf[nl + 1 + dl] = 0;
23119    res_query(buf.as_ptr() as *const c_char, class, type_, answer, anslen)
23120}
23121
23122#[no_mangle]
23123pub unsafe extern "C" fn res_search(
23124    name: *const c_char,
23125    class: c_int,
23126    type_: c_int,
23127    answer: *mut u8,
23128    anslen: c_int,
23129) -> c_int {
23130    if name.is_null() { return -1; }
23131    resolv_ensure();
23132    let len = crate::strlen(name);
23133    let mut dots = 0;
23134    for i in 0..len {
23135        if *name.add(i) == b'.' as c_char { dots += 1; }
23136    }
23137    let trailing_dot = len > 0 && *name.add(len - 1) == b'.' as c_char;
23138    if trailing_dot || dots >= 1 {
23139        let r = res_query(name, class, type_, answer, anslen);
23140        if r >= 0 { return r; }
23141        if trailing_dot { return -1; }
23142    }
23143    for i in 0..SEARCH_COUNT {
23144        let dom = SEARCH_DOMAINS[i].as_ptr() as *const c_char;
23145        let r = res_querydomain(name, dom, class, type_, answer, anslen);
23146        if r >= 0 { return r; }
23147        if H_ERRNO!() != HOST_NOT_FOUND && H_ERRNO!() != NO_DATA { return -1; }
23148    }
23149    if dots == 0 {
23150        return res_query(name, class, type_, answer, anslen);
23151    }
23152    -1
23153}
23154
23155// ============================================================
23156// Host and address resolution
23157// ============================================================
23158
23159#[repr(C)]
23160pub struct HostEnt {
23161    pub h_name: *mut c_char,
23162    pub h_aliases: *mut *mut c_char,
23163    pub h_addrtype: c_int,
23164    pub h_length: c_int,
23165    pub h_addr_list: *mut *mut c_char,
23166}
23167
23168#[repr(C)]
23169pub struct AddrInfo {
23170    pub ai_flags: c_int,
23171    pub ai_family: c_int,
23172    pub ai_socktype: c_int,
23173    pub ai_protocol: c_int,
23174    pub ai_addrlen: u32,
23175    pub ai_addr: *mut c_void,
23176    pub ai_canonname: *mut c_char,
23177    pub ai_next: *mut AddrInfo,
23178}
23179
23180static mut HOST_ENT: HostEnt = HostEnt {
23181    h_name: core::ptr::null_mut(),
23182    h_aliases: core::ptr::null_mut(),
23183    h_addrtype: 0,
23184    h_length: 0,
23185    h_addr_list: core::ptr::null_mut(),
23186};
23187static mut HOST_NAME: [c_char; 256] = [0; 256];
23188static mut HOST_ALIASES: [*mut c_char; 8] = [core::ptr::null_mut(); 8];
23189static mut HOST_ADDR: [u8; 16] = [0; 16];
23190static mut HOST_ADDR_PTRS: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
23191
23192// DNS wire-format offsets used by host_from_answer and friends.
23193const DNS_HDR_LEN: usize = 12;
23194const DNS_QDCOUNT_OFF: usize = 4;
23195const DNS_ANCOUNT_OFF: usize = 6;
23196const DNS_QUESTION_LEN: usize = 4;
23197const DNS_RR_TYPE_OFF: usize = 0;
23198const DNS_RR_CLASS_OFF: usize = 2;
23199const DNS_RR_RDLEN_OFF: usize = 8;
23200const DNS_RR_RDATA_OFF: usize = 10;
23201const DNS_CLASS_IN: u16 = 1;
23202const DNS_TYPE_A: u16 = 1;
23203const DNS_TYPE_AAAA: u16 = 28;
23204
23205unsafe fn host_from_answer(answer: *const u8, len: c_int, af: c_int) -> *mut HostEnt {
23206    if (len as usize) < DNS_HDR_LEN { return core::ptr::null_mut(); }
23207    let msg = match InBuf::new(answer, len as usize) {
23208        Some(msg) => msg,
23209        None => return core::ptr::null_mut(),
23210    };
23211    let qd = match msg.peek_u16_be(DNS_QDCOUNT_OFF) {
23212        Some(v) => v as usize,
23213        None => return core::ptr::null_mut(),
23214    };
23215    let an = match msg.peek_u16_be(DNS_ANCOUNT_OFF) {
23216        Some(v) => v as usize,
23217        None => return core::ptr::null_mut(),
23218    };
23219    let mut p = DNS_HDR_LEN;
23220    for _ in 0..qd {
23221        p = match dns_skip_name(&msg, p) {
23222            Some(v) => v,
23223            None => return core::ptr::null_mut(),
23224        };
23225        p = match p.checked_add(DNS_QUESTION_LEN) {
23226            Some(v) if v <= msg.len() => v,
23227            _ => return core::ptr::null_mut(),
23228        };
23229    }
23230    let want_type: u16 = if af == AF_INET6 { DNS_TYPE_AAAA } else { DNS_TYPE_A };
23231    let want_len = if af == AF_INET6 { 16 } else { 4 };
23232    for _ in 0..an {
23233        p = match dns_skip_name(&msg, p) {
23234            Some(v) => v,
23235            None => break,
23236        };
23237        let typ = match msg.peek_u16_be(p + DNS_RR_TYPE_OFF) {
23238            Some(v) => v,
23239            None => break,
23240        };
23241        let class = match msg.peek_u16_be(p + DNS_RR_CLASS_OFF) {
23242            Some(v) => v,
23243            None => break,
23244        };
23245        let rdlen = match msg.peek_u16_be(p + DNS_RR_RDLEN_OFF) {
23246            Some(v) => v as usize,
23247            None => break,
23248        };
23249        let rdata_off = match p.checked_add(DNS_RR_RDATA_OFF) {
23250            Some(v) => v,
23251            None => break,
23252        };
23253        let rdata = match msg.slice_at(rdata_off, rdlen) {
23254            Some(v) => v,
23255            None => break,
23256        };
23257        if typ == want_type && class == DNS_CLASS_IN && rdata.len() == want_len {
23258            core::ptr::copy_nonoverlapping(rdata.as_ptr(), HOST_ADDR.as_mut_ptr(), want_len);
23259            HOST_ENT.h_addrtype = af;
23260            HOST_ENT.h_length = want_len as c_int;
23261            HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
23262            HOST_ADDR_PTRS[1] = core::ptr::null_mut();
23263            HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
23264            HOST_ALIASES[0] = core::ptr::null_mut();
23265            HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
23266            HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
23267            H_ERRNO!() = 0;
23268            return &raw mut HOST_ENT;
23269        }
23270        p = match rdata_off.checked_add(rdlen) {
23271            Some(v) => v,
23272            None => break,
23273        };
23274    }
23275    core::ptr::null_mut()
23276}
23277
23278#[no_mangle]
23279pub unsafe extern "C" fn gethostbyname(name: *const c_char) -> *mut HostEnt {
23280    gethostbyname2(name, AF_INET)
23281}
23282
23283#[no_mangle]
23284pub unsafe extern "C" fn gethostbyname2(name: *const c_char, af: c_int) -> *mut HostEnt {
23285    if name.is_null() { H_ERRNO!() = HOST_NOT_FOUND; return core::ptr::null_mut(); }
23286    let mut addr = [0u8; 16];
23287    let addrlen = if af == AF_INET6 { 16 } else { 4 };
23288    if inet_pton(af, name, addr.as_mut_ptr() as *mut c_void) == 1 {
23289        core::ptr::copy_nonoverlapping(addr.as_ptr(), HOST_ADDR.as_mut_ptr(), addrlen);
23290        let n = crate::strlen(name);
23291        let l = core::cmp::min(n, 255);
23292        core::ptr::copy_nonoverlapping(name, HOST_NAME.as_mut_ptr(), l);
23293        HOST_NAME[l] = 0;
23294        HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
23295        HOST_ALIASES[0] = core::ptr::null_mut();
23296        HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
23297        HOST_ENT.h_addrtype = af;
23298        HOST_ENT.h_length = addrlen as c_int;
23299        HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
23300        HOST_ADDR_PTRS[1] = core::ptr::null_mut();
23301        HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
23302        H_ERRNO!() = 0;
23303        return &raw mut HOST_ENT;
23304    }
23305    let mut answer = [0u8; 512];
23306    let qtype = if af == AF_INET6 { 28 } else { 1 };
23307    let r = res_query(name, 1, qtype, answer.as_mut_ptr(), answer.len() as c_int);
23308    if r < 0 {
23309        if H_ERRNO!() == 0 { H_ERRNO!() = TRY_AGAIN; }
23310        return core::ptr::null_mut();
23311    }
23312    let ent = host_from_answer(answer.as_ptr(), r, af);
23313    if !ent.is_null() {
23314        let n = crate::strlen(name);
23315        let l = core::cmp::min(n, 255);
23316        core::ptr::copy_nonoverlapping(name, HOST_NAME.as_mut_ptr(), l);
23317        HOST_NAME[l] = 0;
23318    } else {
23319        H_ERRNO!() = HOST_NOT_FOUND;
23320    }
23321    ent
23322}
23323
23324#[no_mangle]
23325pub unsafe extern "C" fn gethostbyaddr(addr: *const c_void, len: u32, type_: c_int) -> *mut HostEnt {
23326    // musl implements gethostbyaddr() on top of getnameinfo(), so /etc/hosts
23327    // and the DNS reverse path behave identically for both APIs.
23328    let (addr_len, salen) = match type_ {
23329        AF_INET => (4usize, 16u32),
23330        AF_INET6 => (16usize, 28u32),
23331        _ => {
23332            H_ERRNO!() = HOST_NOT_FOUND;
23333            return core::ptr::null_mut();
23334        }
23335    };
23336    if addr.is_null() || len as usize != addr_len {
23337        H_ERRNO!() = HOST_NOT_FOUND;
23338        return core::ptr::null_mut();
23339    }
23340    let mut sa = [0u8; 28];
23341    *(sa.as_mut_ptr() as *mut u16) = type_ as u16;
23342    if type_ == AF_INET {
23343        core::ptr::copy_nonoverlapping(addr as *const u8, sa.as_mut_ptr().add(4), 4);
23344    } else {
23345        core::ptr::copy_nonoverlapping(addr as *const u8, sa.as_mut_ptr().add(8), 16);
23346    }
23347    let mut name = [0 as c_char; 256];
23348    let rc = getnameinfo(
23349        sa.as_ptr() as *const c_void,
23350        salen,
23351        name.as_mut_ptr(),
23352        name.len() as u32,
23353        core::ptr::null_mut(),
23354        0,
23355        0,
23356    );
23357    if rc != 0 {
23358        H_ERRNO!() = match rc {
23359            EAI_AGAIN_V => TRY_AGAIN,
23360            EAI_NONAME_V => HOST_NOT_FOUND,
23361            _ => NO_RECOVERY,
23362        };
23363        return core::ptr::null_mut();
23364    }
23365    let l = crate::strlen(name.as_ptr());
23366    if l >= HOST_NAME.len() {
23367        H_ERRNO!() = NO_RECOVERY;
23368        return core::ptr::null_mut();
23369    }
23370    core::ptr::copy_nonoverlapping(name.as_ptr(), HOST_NAME.as_mut_ptr(), l + 1);
23371    core::ptr::copy_nonoverlapping(addr as *const u8, HOST_ADDR.as_mut_ptr(), addr_len);
23372    HOST_ENT.h_name = HOST_NAME.as_mut_ptr();
23373    HOST_ALIASES[0] = HOST_NAME.as_mut_ptr();
23374    HOST_ALIASES[1] = core::ptr::null_mut();
23375    HOST_ENT.h_aliases = HOST_ALIASES.as_mut_ptr();
23376    HOST_ENT.h_addrtype = type_;
23377    HOST_ENT.h_length = addr_len as c_int;
23378    HOST_ADDR_PTRS[0] = HOST_ADDR.as_mut_ptr() as *mut c_char;
23379    HOST_ADDR_PTRS[1] = core::ptr::null_mut();
23380    HOST_ENT.h_addr_list = HOST_ADDR_PTRS.as_mut_ptr();
23381    H_ERRNO!() = 0;
23382    &raw mut HOST_ENT
23383}
23384
23385// ============================================================
23386// Legacy syscall/stdio/signal compatibility
23387// ============================================================
23388
23389#[inline]
23390fn sysno(x86_64: i64, generic: i64) -> i64 {
23391    if cfg!(target_arch = "x86_64") { x86_64 } else { generic }
23392}
23393
23394#[no_mangle]
23395pub unsafe extern "C" fn settimeofday(tv: *const c_void, tz: *const c_void) -> c_int {
23396    let r = <Arch as Syscalls>::syscall2(sysno(164, 170), tv as i64, tz as i64);
23397    syscall_ret(r) as c_int
23398}
23399
23400#[no_mangle]
23401pub unsafe extern "C" fn stime(t: *const i64) -> c_int {
23402    if t.is_null() { ERRNO!() = EINVAL; return -1; }
23403    let tv = timeval { tv_sec: *t, tv_usec: 0 };
23404    settimeofday(&tv as *const timeval as *const c_void, core::ptr::null())
23405}
23406
23407#[no_mangle]
23408pub unsafe extern "C" fn times(buf: *mut c_void) -> c_long {
23409    let r = <Arch as Syscalls>::syscall1(sysno(100, 153), buf as i64);
23410    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_long }
23411}
23412
23413#[no_mangle]
23414pub 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 {
23415    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);
23416    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
23417}
23418
23419#[no_mangle]
23420pub unsafe extern "C" fn tee(fd_in: c_int, fd_out: c_int, len: usize, flags: u32) -> isize {
23421    let r = <Arch as Syscalls>::syscall4(sysno(276, 77), fd_in as i64, fd_out as i64, len as i64, flags as i64);
23422    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
23423}
23424
23425#[no_mangle]
23426pub unsafe extern "C" fn statx(dirfd: c_int, path: *const c_char, flags: c_int, mask: u32, buf: *mut c_void) -> c_int {
23427    let r = <Arch as Syscalls>::syscall5(sysno(332, 291), dirfd as i64, path as i64, flags as i64, mask as i64, buf as i64);
23428    syscall_ret(r) as c_int
23429}
23430
23431#[no_mangle]
23432pub unsafe extern "C" fn setns(fd: c_int, nstype: c_int) -> c_int {
23433    let r = <Arch as Syscalls>::syscall2(SYS_SETNS, fd as i64, nstype as i64);
23434    syscall_ret(r) as c_int
23435}
23436
23437#[no_mangle]
23438pub unsafe extern "C" fn setfsuid(uid: u32) -> c_int {
23439    <Arch as Syscalls>::syscall1(sysno(122, 151), uid as i64) as c_int
23440}
23441
23442#[no_mangle]
23443pub unsafe extern "C" fn setfsgid(gid: u32) -> c_int {
23444    <Arch as Syscalls>::syscall1(sysno(123, 152), gid as i64) as c_int
23445}
23446
23447#[no_mangle]
23448pub unsafe extern "C" fn setregid(rgid: u32, egid: u32) -> c_int {
23449    let r = <Arch as Syscalls>::syscall2(sysno(114, 143), rgid as i64, egid as i64);
23450    syscall_ret(r) as c_int
23451}
23452
23453#[no_mangle]
23454pub 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 {
23455    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);
23456    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
23457}
23458
23459#[no_mangle]
23460pub 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 {
23461    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);
23462    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
23463}
23464
23465#[no_mangle]
23466pub unsafe extern "C" fn tcgetwinsize(fd: c_int, ws: *mut c_void) -> c_int {
23467    if fd < 0 || ws.is_null() { ERRNO!() = EINVAL; return -1; }
23468    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5413, ws as i64);
23469    syscall_ret(r) as c_int
23470}
23471
23472#[no_mangle]
23473pub unsafe extern "C" fn tcsetwinsize(fd: c_int, ws: *const c_void) -> c_int {
23474    if fd < 0 || ws.is_null() { ERRNO!() = EINVAL; return -1; }
23475    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5414, ws as i64);
23476    syscall_ret(r) as c_int
23477}
23478
23479#[no_mangle]
23480pub unsafe extern "C" fn sockatmark(fd: c_int) -> c_int {
23481    let mut at: c_int = 0;
23482    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x8905, &mut at as *mut c_int as i64);
23483    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { at }
23484}
23485
23486#[no_mangle]
23487pub unsafe extern "C" fn isastream(fd: c_int) -> c_int {
23488    let mut buf = [0u8; 64];
23489    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5401, buf.as_mut_ptr() as i64);
23490    if r < 0 { ERRNO!() = (-r) as c_int; 0 } else { 1 }
23491}
23492
23493#[no_mangle]
23494pub unsafe extern "C" fn posix_madvise(addr: *mut c_void, len: usize, advice: c_int) -> c_int {
23495    madvise(addr as *mut u8, len, advice)
23496}
23497
23498#[no_mangle]
23499pub unsafe extern "C" fn secure_getenv(name: *const c_char) -> *mut c_char {
23500    if getauxval(23) != 0 { return core::ptr::null_mut(); }
23501    getenv(name)
23502}
23503
23504#[no_mangle]
23505pub unsafe extern "C" fn sigandset(dest: *mut c_ulong, left: *const c_ulong, right: *const c_ulong) -> c_int {
23506    if dest.is_null() || left.is_null() || right.is_null() { return -1; }
23507    *dest = *left & *right;
23508    0
23509}
23510
23511#[no_mangle]
23512pub unsafe extern "C" fn sigorset(dest: *mut c_ulong, left: *const c_ulong, right: *const c_ulong) -> c_int {
23513    if dest.is_null() || left.is_null() || right.is_null() { return -1; }
23514    *dest = *left | *right;
23515    0
23516}
23517
23518#[no_mangle]
23519pub unsafe extern "C" fn sigisemptyset(set: *const c_ulong) -> c_int {
23520    if set.is_null() { return 1; }
23521    (*set == 0) as c_int
23522}
23523
23524#[no_mangle]
23525pub unsafe extern "C" fn sighold(sig: c_int) -> c_int {
23526    let set: c_ulong = 1u64 << (sig - 1) as u32;
23527    sigprocmask(0, &set, core::ptr::null_mut());
23528    0
23529}
23530
23531#[no_mangle]
23532pub unsafe extern "C" fn sigignore(sig: c_int) -> c_int {
23533    let _ = signal(sig, 1);
23534    0
23535}
23536
23537#[no_mangle]
23538pub unsafe extern "C" fn sigrelse(sig: c_int) -> c_int {
23539    let set: c_ulong = 1u64 << (sig - 1) as u32;
23540    sigprocmask(1, &set, core::ptr::null_mut());
23541    0
23542}
23543
23544#[no_mangle]
23545pub unsafe extern "C" fn siginterrupt(sig: c_int, flag: c_int) -> c_int {
23546    let mut sa: sigaction = core::mem::zeroed();
23547    if sigaction(sig, core::ptr::null(), &mut sa) != 0 { return -1; }
23548    if flag != 0 { sa.sa_flags &= !(SA_RESTART as c_int); } else { sa.sa_flags |= SA_RESTART as c_int; }
23549    sigaction(sig, &sa, core::ptr::null_mut())
23550}
23551
23552#[no_mangle]
23553pub unsafe extern "C" fn sigpause(sig: c_int) -> c_int {
23554    let set: c_ulong = 1u64 << (sig - 1) as u32;
23555    sigsuspend(&set)
23556}
23557
23558#[no_mangle]
23559pub unsafe extern "C" fn semtimedop(semid: c_int, sops: *mut c_void, nsops: usize, timeout: *const timespec) -> c_int {
23560    let r = <Arch as Syscalls>::syscall4(sysno(220, 192), semid as i64, sops as i64, nsops as i64, timeout as i64);
23561    syscall_ret(r) as c_int
23562}
23563
23564#[no_mangle]
23565pub unsafe extern "C" fn wait3(status: *mut c_int, options: c_int, rusage: *mut c_void) -> i32 {
23566    wait4(-1, status, options, rusage) as i32
23567}
23568
23569#[no_mangle]
23570pub unsafe extern "C" fn tempnam(dir: *const c_char, pfx: *const c_char) -> *mut c_char {
23571    let mut path = [0 as c_char; 256];
23572    let mut i = 0;
23573    if !dir.is_null() {
23574        while *dir.add(i) != 0 && i < 200 { path[i] = *dir.add(i); i += 1; }
23575        if i > 0 && path[i-1] != b'/' as c_char { path[i] = b'/' as c_char; i += 1; }
23576    } else {
23577        for &c in b"/tmp/" { path[i] = c as c_char; i += 1; }
23578    }
23579    if !pfx.is_null() {
23580        let mut j = 0;
23581        while *pfx.add(j) != 0 && i < 220 { path[i] = *pfx.add(j); i += 1; j += 1; }
23582    }
23583    for &c in b"XXXXXX" { path[i] = c as c_char; i += 1; }
23584    path[i] = 0;
23585    let fd = mkstemp(path.as_mut_ptr());
23586    if fd < 0 { return core::ptr::null_mut(); }
23587    close(fd);
23588    unlink(path.as_ptr());
23589    let n = strlen(path.as_ptr());
23590    let out = malloc(n + 1) as *mut c_char;
23591    if out.is_null() { return core::ptr::null_mut(); }
23592    core::ptr::copy_nonoverlapping(path.as_ptr(), out, n + 1);
23593    out
23594}
23595
23596#[no_mangle]
23597pub unsafe extern "C" fn putwc(c: u32, f: *mut c_void) -> u32 {
23598    fputwc(c as c_int, f as *mut FILE) as u32
23599}
23600
23601#[no_mangle]
23602pub unsafe extern "C" fn __uflow(f: *mut c_void) -> c_int {
23603    fgetc(f as *mut FILE)
23604}
23605
23606#[no_mangle]
23607pub unsafe extern "C" fn __xmknod(_ver: c_int, path: *const c_char, mode: c_uint, dev: u64) -> c_int {
23608    mknod(path, mode, dev)
23609}
23610
23611#[no_mangle]
23612pub unsafe extern "C" fn __xmknodat(_ver: c_int, dirfd: c_int, path: *const c_char, mode: c_uint, dev: u64) -> c_int {
23613    mknodat(dirfd, path, mode, dev)
23614}
23615
23616#[no_mangle]
23617pub 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 {
23618    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);
23619    syscall_ret(r) as c_int
23620}
23621
23622#[no_mangle]
23623pub unsafe extern "C" fn open_by_handle_at(mount_fd: c_int, handle: *mut c_void, flags: c_int) -> c_int {
23624    let r = <Arch as Syscalls>::syscall3(sysno(304, 265), mount_fd as i64, handle as i64, flags as i64);
23625    syscall_ret(r) as c_int
23626}
23627
23628#[no_mangle]
23629pub unsafe extern "C" fn dn_skipname(comp: *const u8, eom: *const u8) -> c_int {
23630    let len = match (eom as usize).checked_sub(comp as usize) {
23631        Some(n) => n,
23632        None => return -1,
23633    };
23634    let msg = match InBuf::new(comp, len) {
23635        Some(msg) => msg,
23636        None => return -1,
23637    };
23638    match dns_skip_name(&msg, 0) {
23639        Some(n) if n <= c_int::MAX as usize => n as c_int,
23640        _ => -1,
23641    }
23642}
23643
23644#[no_mangle]
23645pub 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 {
23646    if exp.is_null() || dst.is_null() || dstsiz <= 0 { return -1; }
23647    let mut o = 0usize;
23648    let mut p = exp;
23649    loop {
23650        let start = p;
23651        while *p != 0 && *p != b'.' as c_char { p = p.add(1); }
23652        let l = p as usize - start as usize;
23653        if l > 63 || o + l + 2 > dstsiz as usize { return -1; }
23654        *dst.add(o) = l as u8; o += 1;
23655        core::ptr::copy_nonoverlapping(start as *const u8, dst.add(o), l);
23656        o += l;
23657        if *p == 0 { break; }
23658        p = p.add(1);
23659    }
23660    if o + 1 > dstsiz as usize { return -1; }
23661    *dst.add(o) = 0;
23662    (o + 1) as c_int
23663}
23664
23665// ============================================================
23666// Shadow database
23667// ============================================================
23668
23669#[repr(C)]
23670#[derive(Copy, Clone)]
23671pub struct Spwd {
23672    pub sp_namp: *mut c_char,
23673    pub sp_pwdp: *mut c_char,
23674    pub sp_lstchg: c_long,
23675    pub sp_min: c_long,
23676    pub sp_max: c_long,
23677    pub sp_warn: c_long,
23678    pub sp_inact: c_long,
23679    pub sp_expire: c_long,
23680    pub sp_flag: c_ulong,
23681}
23682
23683static mut SPWD_ENT: Spwd = Spwd {
23684    sp_namp: core::ptr::null_mut(), sp_pwdp: core::ptr::null_mut(),
23685    sp_lstchg: 0, sp_min: 0, sp_max: 0, sp_warn: 0, sp_inact: 0,
23686    sp_expire: 0, sp_flag: 0,
23687};
23688static mut SPWD_BUF: *mut c_char = core::ptr::null_mut();
23689static mut SPWD_BUF_CAP: usize = 0;
23690static mut SPWD_LINE: *mut c_char = core::ptr::null_mut();
23691static mut SPWD_LINE_CAP: usize = 0;
23692static mut SPWD_FILE: *mut FILE = core::ptr::null_mut();
23693
23694unsafe fn ensure_spwd_buf(need: usize) -> bool {
23695    if SPWD_BUF_CAP >= need {
23696        return true;
23697    }
23698    let mut cap = if SPWD_BUF_CAP == 0 { 1024 } else { SPWD_BUF_CAP };
23699    while cap < need {
23700        cap = match cap.checked_mul(2) {
23701            Some(v) => v,
23702            None => return false,
23703        };
23704    }
23705    let grown = crate::realloc(SPWD_BUF as *mut c_void, cap) as *mut c_char;
23706    if grown.is_null() {
23707        ERRNO!() = ENOMEM;
23708        return false;
23709    }
23710    SPWD_BUF = grown;
23711    SPWD_BUF_CAP = cap;
23712    true
23713}
23714
23715/// Read one line from `f` with getline and parse it into the static entry.
23716/// Lines that do not have all nine shadow fields are skipped.
23717unsafe fn spwd_next(f: *mut FILE) -> *mut Spwd {
23718    loop {
23719        let n = crate::getline(&raw mut SPWD_LINE, &raw mut SPWD_LINE_CAP, f);
23720        if n < 0 {
23721            return core::ptr::null_mut();
23722        }
23723        let len = n as usize;
23724        if len > 0 && *SPWD_LINE.add(len - 1) == b'\n' as c_char {
23725            *SPWD_LINE.add(len - 1) = 0;
23726        }
23727        if !ensure_spwd_buf(len + 1) {
23728            return core::ptr::null_mut();
23729        }
23730        if parse_spwd(SPWD_LINE, &raw mut SPWD_ENT, SPWD_BUF, SPWD_BUF_CAP) {
23731            return &raw mut SPWD_ENT;
23732        }
23733    }
23734}
23735
23736unsafe fn parse_spwd(line: *const c_char, ent: *mut Spwd, buf: *mut c_char, buflen: usize) -> bool {
23737    let mut fields: [*mut c_char; 9] = [core::ptr::null_mut(); 9];
23738    let n = match split_colon_fields(line, buf, buflen, &mut fields) {
23739        Some(n) => n,
23740        None => return false,
23741    };
23742    if n < 9 { return false; }
23743    (*ent).sp_namp = fields[0];
23744    (*ent).sp_pwdp = fields[1];
23745    (*ent).sp_lstchg = crate::strtol(fields[2], core::ptr::null_mut(), 10) as c_long;
23746    (*ent).sp_min = crate::strtol(fields[3], core::ptr::null_mut(), 10) as c_long;
23747    (*ent).sp_max = crate::strtol(fields[4], core::ptr::null_mut(), 10) as c_long;
23748    (*ent).sp_warn = crate::strtol(fields[5], core::ptr::null_mut(), 10) as c_long;
23749    (*ent).sp_inact = crate::strtol(fields[6], core::ptr::null_mut(), 10) as c_long;
23750    (*ent).sp_expire = crate::strtol(fields[7], core::ptr::null_mut(), 10) as c_long;
23751    (*ent).sp_flag = crate::strtoul(fields[8], core::ptr::null_mut(), 10) as c_ulong;
23752    true
23753}
23754
23755#[no_mangle]
23756pub unsafe extern "C" fn setspent() {
23757    endspent();
23758    SPWD_FILE = crate::fopen(b"/etc/shadow\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
23759}
23760
23761#[no_mangle]
23762pub unsafe extern "C" fn endspent() {
23763    if !SPWD_FILE.is_null() { crate::fclose(SPWD_FILE); SPWD_FILE = core::ptr::null_mut(); }
23764}
23765
23766#[no_mangle]
23767pub unsafe extern "C" fn getspent() -> *mut Spwd {
23768    if SPWD_FILE.is_null() { setspent(); if SPWD_FILE.is_null() { return core::ptr::null_mut(); } }
23769    spwd_next(SPWD_FILE)
23770}
23771
23772#[no_mangle]
23773pub unsafe extern "C" fn fgetspent(f: *mut FILE) -> *mut Spwd {
23774    if f.is_null() { return core::ptr::null_mut(); }
23775    spwd_next(f)
23776}
23777
23778#[no_mangle]
23779pub unsafe extern "C" fn getspnam(name: *const c_char) -> *mut Spwd {
23780    if name.is_null() { return core::ptr::null_mut(); }
23781    setspent();
23782    loop {
23783        let sp = getspent();
23784        if sp.is_null() { break; }
23785        if crate::strcmp((*sp).sp_namp as *const u8, name as *const u8) == 0 { endspent(); return sp; }
23786    }
23787    endspent();
23788    core::ptr::null_mut()
23789}
23790
23791unsafe fn getsp_r_inner(
23792    name: *const c_char,
23793    sp: *mut Spwd,
23794    buf: *mut c_char,
23795    buflen: usize,
23796    result: *mut *mut Spwd,
23797) -> c_int {
23798    if name.is_null() || sp.is_null() || buf.is_null() || result.is_null() {
23799        return EINVAL;
23800    }
23801    *result = core::ptr::null_mut();
23802    let f = crate::fopen(b"/etc/shadow\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
23803    if f.is_null() { return ERRNO!(); }
23804    let mut line: *mut c_char = core::ptr::null_mut();
23805    let mut cap: usize = 0;
23806    let mut err = 0;
23807    loop {
23808        let n = crate::getline(&raw mut line, &raw mut cap, f);
23809        if n < 0 { break; }
23810        let mut len = n as usize;
23811        if len > 0 && *line.add(len - 1) == b'\n' as c_char {
23812            *line.add(len - 1) = 0;
23813            len -= 1;
23814        }
23815        if len + 1 > buflen {
23816            err = ERANGE;
23817            break;
23818        }
23819        if parse_spwd(line, sp, buf, buflen) {
23820            if crate::strcmp((*sp).sp_namp as *const u8, name as *const u8) == 0 {
23821                *result = sp;
23822                break;
23823            }
23824        }
23825    }
23826    crate::free(line as *mut c_void);
23827    crate::fclose(f);
23828    err
23829}
23830
23831#[no_mangle]
23832pub 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 {
23833    getsp_r_inner(name, sp, buf, buflen, result)
23834}
23835
23836#[no_mangle]
23837pub unsafe extern "C" fn putspent(sp: *const Spwd, f: *mut FILE) -> c_int {
23838    if sp.is_null() || f.is_null() { return -1; }
23839    crate::fprintf(f, b"%s:%s:%ld:%ld:%ld:%ld:%ld:%ld:%lu\\n\0".as_ptr() as *const c_char,
23840        (*sp).sp_namp, (*sp).sp_pwdp, (*sp).sp_lstchg, (*sp).sp_min, (*sp).sp_max,
23841        (*sp).sp_warn, (*sp).sp_inact, (*sp).sp_expire, (*sp).sp_flag)
23842}
23843
23844#[no_mangle]
23845pub unsafe extern "C" fn getgrouplist(user: *const c_char, group: u32, groups: *mut u32, ngroups: *mut i32) -> c_int {
23846    if user.is_null() || groups.is_null() || ngroups.is_null() { return -1; }
23847    if *ngroups < 0 { return -1; }
23848    let max = *ngroups as usize;
23849    let mut n = 0usize;
23850    if n < max { *groups.add(n) = group; }
23851    n += 1;
23852    setgrent();
23853    loop {
23854        let g = getgrent();
23855        if g.is_null() { break; }
23856        if (*g).gr_gid == group { continue; }
23857        let mut found = false;
23858        let mut i = 0;
23859        while !(*(*g).gr_mem.add(i)).is_null() {
23860            if crate::strcmp(*(*g).gr_mem.add(i) as *const u8, user as *const u8) == 0 {
23861                found = true;
23862                break;
23863            }
23864            i += 1;
23865        }
23866        if found {
23867            if n < max { *groups.add(n) = (*g).gr_gid; }
23868            n += 1;
23869        }
23870    }
23871    endgrent();
23872    if n > max { *ngroups = n as i32; return -1; }
23873    *ngroups = n as i32;
23874    n as c_int
23875}