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#![allow(dead_code, non_camel_case_types)]
6// A libc necessarily keeps mutable global state (stdio tables, passwd/group
7// buffers, resolver state).  References to it are deliberate and confined to
8// the C ABI entry points.
9#![allow(static_mut_refs)]
10// C `_Complex` values are passed as two floating-point registers on every
11// supported target; Rust tuples use the same SysV/AAPCS classification.
12#![allow(improper_ctypes_definitions)]
13
14use core::ffi::{c_char, c_int, c_long, c_longlong, c_uint, c_ulong, c_ulonglong, c_void, VaList};
15
16// Stable-Rust representation of C `long double` on the 128-bit targets.
17// AArch64 passes binary128 in one SIMD register; RISC-V passes it in a pair
18// of FP registers, which a two-f64 struct reproduces.
19#[cfg(target_arch = "aarch64")]
20pub type f128 = core::arch::aarch64::float64x2_t;
21
22#[cfg(target_arch = "riscv64")]
23#[repr(C)]
24#[derive(Copy, Clone)]
25pub struct f128 {
26    lo: u64,
27    hi: u64,
28}
29
30#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
31#[inline]
32fn f128_from_bits(bits: u128) -> f128 {
33    unsafe { core::mem::transmute::<u128, f128>(bits) }
34}
35
36#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
37#[inline]
38fn f128_to_bits(x: f128) -> u128 {
39    unsafe { core::mem::transmute::<f128, u128>(x) }
40}
41
42#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
43fn f128_is_nan(x: f128) -> bool {
44    let bits = f128_to_bits(x);
45    ((bits >> 112) & 0x7fff) == 0x7fff && (bits & ((1u128 << 112) - 1)) != 0
46}
47
48#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
49fn f128_to_f64(x: f128) -> f64 {
50    let bits = f128_to_bits(x);
51    let sign = (bits >> 127) as u64;
52    let exp = ((bits >> 112) & 0x7fff) as i32;
53    let frac = bits & ((1u128 << 112) - 1);
54    let signbit = sign << 63;
55    if exp == 0x7fff {
56        let m = if frac == 0 { 0x7ff0_0000_0000_0000 } else { 0x7ff8_0000_0000_0000 };
57        return f64::from_bits(signbit | m);
58    }
59    if exp == 0 { return f64::from_bits(signbit); }
60    let e = exp - 16383;
61    if e > 1023 { return f64::from_bits(signbit | 0x7ff0_0000_0000_0000); }
62    if e < -1074 { return f64::from_bits(signbit); }
63    let sig = (1u128 << 112) | frac;
64    if e >= -1022 {
65        let mut m = (sig >> 60) as u64;
66        let rem = sig & ((1u128 << 60) - 1);
67        let half = 1u128 << 59;
68        if rem > half || (rem == half && (m & 1) != 0) { m += 1; }
69        let mut ef = (e + 1023) as u64;
70        if m == (1u64 << 53) { m >>= 1; ef += 1; }
71        if ef >= 0x7ff { return f64::from_bits(signbit | 0x7ff0_0000_0000_0000); }
72        return f64::from_bits(signbit | (ef << 52) | (m & ((1u64 << 52) - 1)));
73    }
74    let rshift = (-(e + 962)) as u32;
75    let mut m = (sig >> rshift) as u64;
76    let rem = sig & ((1u128 << rshift) - 1);
77    let half = 1u128 << (rshift - 1);
78    if rem > half || (rem == half && (m & 1) != 0) { m += 1; }
79    if m >= (1u64 << 52) {
80        return f64::from_bits(signbit | (1u64 << 52));
81    }
82    f64::from_bits(signbit | m)
83}
84
85#[cfg(target_arch = "riscv64")]
86unsafe fn valist_read_f128(args: &mut VaList<'_>) -> f128 {
87    // RISC-V va_list is an opaque pointer to the next argument. A 16-byte
88    // variable argument is 16-byte aligned and 16 bytes long.
89    let pp = args as *mut VaList<'_> as *mut *const u8;
90    let p = ((*pp as usize) + 15) & !15usize;
91    let bits = core::ptr::read_unaligned(p as *const u128);
92    *pp = (p + 16) as *const u8;
93    f128_from_bits(bits)
94}
95
96#[cfg(target_arch = "aarch64")]
97#[repr(C)]
98struct Aarch64VaList {
99    stack: *const u8,
100    gr_top: *const u8,
101    vr_top: *const u8,
102    gr_offs: i32,
103    vr_offs: i32,
104}
105
106#[cfg(target_arch = "aarch64")]
107unsafe fn valist_read_f128(args: &mut VaList<'_>) -> f128 {
108    let p = args as *mut VaList<'_> as *mut Aarch64VaList;
109    let off = (*p).vr_offs;
110    let addr = if off == 0 {
111        let a = (*p).stack;
112        (*p).stack = a.add(16);
113        a
114    } else {
115        let a = (*p).vr_top.offset(off as isize);
116        (*p).vr_offs = off + 16;
117        a
118    };
119    f128_from_bits(core::ptr::read_unaligned(addr as *const u128))
120}
121
122#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
123fn f64_to_f128(v: f64) -> f128 {
124    let bits = v.to_bits();
125    let sign = (bits >> 63) as u128;
126    let exp = ((bits >> 52) & 0x7ff) as i32;
127    let frac = bits & ((1u64 << 52) - 1);
128    if exp == 0x7ff {
129        let m = if frac == 0 { 0 } else { ((frac as u128) << 60) | (1u128 << 111) };
130        return f128_from_bits((sign << 127) | (0x7fff_u128 << 112) | m);
131    }
132    if exp == 0 {
133        if frac == 0 { return f128_from_bits(sign << 127); }
134        let msb = 63 - frac.leading_zeros() as i32; // 0..51
135        let e = msb - 1074;
136        let f = ((frac as u128) << (112 - msb as u32)) & ((1u128 << 112) - 1);
137        return f128_from_bits((sign << 127) | (((e + 16383) as u128) << 112) | f);
138    }
139    let e = exp - 1023;
140    let f = (frac as u128) << 60;
141    f128_from_bits((sign << 127) | (((e + 16383) as u128) << 112) | f)
142}
143
144use core::ptr::null_mut;
145use core::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, AtomicU32, AtomicUsize, Ordering};
146
147macro_rules! ERRNO {
148    () => { *errno_ptr() };
149}
150
151// h_errno shares the TCB with errno: 0x30 is errno, 0x34 is the free slot
152// before the vDSO getrandom state at 0x38.  The exported `h_errno` symbol is
153// the fallback for static programs and threads without a TCB, matching musl.
154macro_rules! H_ERRNO {
155    () => { *h_errno_ptr() };
156}
157
158include!("encoding_tables.rs");
159include!("math_helpers.rs");
160include!("math_bitmanip.rs");
161include!("math_sqrtfmod.rs");
162include!("math_trig.rs");
163include!("math_exp.rs");
164include!("math_lgamma.rs");
165include!("math_tgamma.rs");
166include!("math_bessel.rs");
167include!("alloc.rs");
168include!("math_log.rs");
169include!("math_pow.rs");
170include!("math_hypot.rs");
171include!("math_hyperbolic.rs");
172include!("math_invtrig.rs");
173include!("math_lrint.rs");
174include!("math_long_double.rs");
175include!("string_fast.rs");
176include!("vdso.rs");
177include!("arch.rs");
178
179// ============================================================
180// errno
181// ============================================================
182
183const EILSEQ: c_int = 84;
184const EINVAL: c_int = 22;
185const EACCES: c_int = 13;
186const ENODEV: c_int = 19;
187const EMSGSIZE: c_int = 90;
188const EFAULT: c_int = 14;
189const E2BIG: c_int = 7;
190const EIO: c_int = 5;
191const ENXIO: c_int = 6;
192const EBADF: c_int = 9;
193const ERANGE: c_int = 34;
194const ENOSYS: c_int = 38;
195const ENOENT: c_int = 2;
196const EEXIST: c_int = 17;
197const ENOTDIR: c_int = 20;
198const EMFILE: c_int = 24;
199const ENOSPC: c_int = 28;
200const ENAMETOOLONG: c_int = 36;
201const ELOOP: c_int = 40;
202const EIDRM: c_int = 43;
203const ENOTSUP: c_int = 95;
204const EAFNOSUPPORT: c_int = 97;
205
206const LC_CTYPE: c_int = 0;
207const LC_NUMERIC: c_int = 1;
208const LC_TIME: c_int = 2;
209const LC_COLLATE: c_int = 3;
210const LC_MONETARY: c_int = 4;
211const LC_MESSAGES: c_int = 5;
212const LC_ALL: c_int = 6;
213const ENOMEM: c_int = 12;
214const EINTR: c_int = 4;
215const EPERM: c_int = 1;
216const EAGAIN: c_int = 11;
217const EBUSY: c_int = 16;
218const EDEADLK: c_int = 35;
219const ETIMEDOUT: c_int = 110;
220const ECANCELED: c_int = 125;
221const EOVERFLOW: c_int = 75;
222const EOWNERDEAD: c_int = 130;
223const ENOTRECOVERABLE: c_int = 131;
224
225// Static executables have no dynamic loader to build a TCB, so they keep the
226// traditional process-global errno. Dynamic programs store it in the TCB, just
227// below the thread pointer. The offset is inside the 256-byte TCB that
228// libc.so allocates for every thread (0x00 self pointer, 0x08 generation,
229// 0x28 stack canary).
230static mut ERRNO_FALLBACK: c_int = 0;
231static ERRNO_TLS_ACTIVE: AtomicUsize = AtomicUsize::new(0);
232const ERRNO_TCB_OFFSET: usize = 0x30;
233
234#[inline]
235unsafe fn errno_ptr() -> *mut c_int {
236    if ERRNO_TLS_ACTIVE.load(Ordering::Relaxed) == 0 {
237        return core::ptr::addr_of_mut!(ERRNO_FALLBACK);
238    }
239    // tcb_slot() performs the TP read and self-pointer validation once.
240    let slot = tcb_slot(ERRNO_TCB_OFFSET);
241    if slot.is_null() {
242        core::ptr::addr_of_mut!(ERRNO_FALLBACK)
243    } else {
244        slot as *mut c_int
245    }
246}
247
248/// Called once from __libc_start_main. The dynamic loader has already set up
249/// a TCB for dynamic programs; static programs leave %fs / TP at zero.
250unsafe fn errno_init() {
251    let tp = arch_get_tp();
252    #[cfg(target_arch = "x86_64")]
253    let tcb = tp;
254    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
255    let tcb = tp.wrapping_sub(256);
256    if tp != 0 && core::ptr::read(tcb as *const usize) == tcb {
257        ERRNO_TLS_ACTIVE.store(1, Ordering::Relaxed);
258    }
259}
260
261/// Normalize a raw syscall result the way musl's `__syscall_ret` does:
262/// turn `-errno` into `-1` and publish the error through `errno`.
263#[inline]
264unsafe fn syscall_ret(r: i64) -> i64 {
265    if r < 0 {
266        *errno_ptr() = (-r) as c_int;
267        -1
268    } else {
269        r
270    }
271}
272
273#[no_mangle]
274pub unsafe extern "C" fn __errno_location() -> *mut c_int {
275    errno_ptr()
276}
277
278unsafe fn h_errno_ptr() -> *mut c_int {
279    if ERRNO_TLS_ACTIVE.load(Ordering::Relaxed) == 0 {
280        return core::ptr::addr_of_mut!(h_errno);
281    }
282    // errno occupies 0x30..0x34; h_errno is the next int in the TCB.
283    errno_ptr().add(1)
284}
285
286#[cfg(not(test))]
287#[panic_handler]
288fn panic(_: &core::panic::PanicInfo) -> ! {
289    // A libc cannot unwind; looping here turns every internal panic into a
290    // permanent CPU spin (and may leave locks held).  Match abort semantics
291    // so the process dies with SIGABRT and the failure is observable.
292    unsafe { abort() }
293}
294
295// Required by the Rust runtime; panic=abort never unwinds.
296#[cfg(not(test))]
297#[no_mangle]
298pub extern "C" fn rust_eh_personality() {}
299
300// ============================================================
301// Constants
302// ============================================================
303
304const PROT_READ: i32 = 1;
305const PROT_WRITE: i32 = 2;
306const MAP_SHARED: i32 = 0x01;
307const MAP_PRIVATE: i32 = 0x02;
308const MAP_ANONYMOUS: i32 = 0x20;
309
310// ============================================================
311// Syscall wrappers (raw, no_std)
312// ============================================================
313
314#[inline]
315unsafe fn sys_write(fd: i64, buf: *const u8, count: usize) -> i64 {
316    <Arch as Syscalls>::syscall3(SYS_WRITE, fd as i64, buf as i64, count as i64)
317}
318
319#[inline]
320unsafe fn sys_read(fd: i64, buf: *mut u8, count: usize) -> i64 {
321    <Arch as Syscalls>::syscall3(SYS_READ, fd as i64, buf as i64, count as i64)
322}
323
324#[inline]
325unsafe fn sys_open(path: *const u8, flags: i64, mode: i64) -> i64 {
326    <Arch as Syscalls>::syscall4(SYS_OPENAT, AT_FDCWD as i64, path as i64, flags as i64, mode as i64)
327}
328
329#[inline]
330unsafe fn sys_close(fd: i64) -> i64 {
331    <Arch as Syscalls>::syscall1(SYS_CLOSE, fd as i64)
332}
333
334#[inline]
335unsafe fn sys_lseek(fd: i64, offset: i64, whence: i64) -> i64 {
336    <Arch as Syscalls>::syscall3(SYS_LSEEK, fd as i64, offset as i64, whence as i64)
337}
338
339unsafe fn sys_mmap(
340    addr: *mut u8,
341    length: usize,
342    prot: i32,
343    flags: i32,
344    fd: i32,
345    offset: i64,
346) -> *mut u8 {
347    let result = <Arch as Syscalls>::syscall6(SYS_MMAP, addr as i64, length as i64, prot as i64, flags as i64, fd as i64, offset);
348    if result < 0 && result > -crate::SYSCALL_ERR_MAX {
349        ERRNO!() = (-result) as c_int;
350        return MMAP_FAILED;
351    }
352    result as *mut u8
353}
354
355unsafe fn sys_munmap(addr: *mut u8, length: usize) -> i64 {
356    <Arch as Syscalls>::syscall2(SYS_MUNMAP, addr as i64, length as i64)
357}
358
359// ============================================================
360// String/memory functions
361// ============================================================
362
363// strlen, memcpy, memset, memmove and memcmp live in string_fast.rs.
364
365#[no_mangle]
366pub unsafe extern "C" fn bcmp(s1: *const c_void, s2: *const c_void, n: usize) -> c_int {
367    memcmp(s1, s2, n)
368}
369
370// strcmp lives in string_fast.rs.
371
372#[no_mangle]
373pub unsafe extern "C" fn strncmp(s1: *const u8, s2: *const u8, n: usize) -> c_int {
374    let mut i = 0;
375    while i < n {
376        let a = *s1.add(i);
377        let b = *s2.add(i);
378        if a != b {
379            return a as c_int - b as c_int;
380        }
381        if a == 0 {
382            return 0;
383        }
384        i += 1;
385    }
386    0
387}
388
389#[no_mangle]
390pub unsafe extern "C" fn strcpy(dst: *mut u8, src: *const u8) -> *mut u8 {
391    let mut i = 0;
392    loop {
393        let c = *src.add(i);
394        *dst.add(i) = c;
395        if c == 0 {
396            break;
397        }
398        i += 1;
399    }
400    dst
401}
402
403#[no_mangle]
404pub unsafe extern "C" fn strncpy(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 {
405    let mut i = 0;
406    while i < n && *src.add(i) != 0 {
407        *dst.add(i) = *src.add(i);
408        i += 1;
409    }
410    while i < n {
411        *dst.add(i) = 0;
412        i += 1;
413    }
414    dst
415}
416
417#[no_mangle]
418pub unsafe extern "C" fn strcat(dst: *mut u8, src: *const u8) -> *mut u8 {
419    let mut i = 0;
420    while *dst.add(i) != 0 {
421        i += 1;
422    }
423    let mut j = 0;
424    loop {
425        let c = *src.add(j);
426        *dst.add(i + j) = c;
427        if c == 0 {
428            break;
429        }
430        j += 1;
431    }
432    dst
433}
434
435#[no_mangle]
436pub unsafe extern "C" fn strncat(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 {
437    let mut i = 0;
438    while *dst.add(i) != 0 {
439        i += 1;
440    }
441    let mut j = 0;
442    while j < n && *src.add(j) != 0 {
443        *dst.add(i + j) = *src.add(j);
444        j += 1;
445    }
446    *dst.add(i + j) = 0;
447    dst
448}
449
450#[no_mangle]
451pub unsafe extern "C" fn strlcpy(dst: *mut u8, src: *const u8, n: usize) -> usize {
452    let l = strlen(src as *const c_char);
453    if n > 0 {
454        let c = if l < n { l } else { n - 1 };
455        core::ptr::copy_nonoverlapping(src, dst, c);
456        *dst.add(c) = 0;
457    }
458    l
459}
460
461#[no_mangle]
462pub unsafe extern "C" fn strlcat(dst: *mut u8, src: *const u8, n: usize) -> usize {
463    let dl = strlen(dst as *const c_char);
464    let sl = strlen(src as *const c_char);
465    if dl >= n { return n + sl; }
466    let c = if sl < n - dl { sl } else { n - dl - 1 };
467    core::ptr::copy_nonoverlapping(src, dst.add(dl), c);
468    *dst.add(dl + c) = 0;
469    dl + sl
470}
471
472#[no_mangle]
473pub unsafe extern "C" fn bcopy(src: *const c_void, dst: *mut c_void, n: usize) {
474    core::ptr::copy(src as *const u8, dst as *mut u8, n);
475}
476
477#[no_mangle]
478pub unsafe extern "C" fn bzero(s: *mut c_void, n: usize) {
479    core::ptr::write_bytes(s as *mut u8, 0, n);
480}
481
482#[no_mangle]
483pub unsafe extern "C" fn strndup(s: *const c_char, n: usize) -> *mut c_char {
484    let mut len = 0;
485    while len < n && *s.add(len) != 0 {
486        len += 1;
487    }
488    let p = malloc(len + 1) as *mut c_char;
489    if p.is_null() {
490        return core::ptr::null_mut();
491    }
492    core::ptr::copy_nonoverlapping(s, p, len);
493    *p.add(len) = 0;
494    p
495}
496
497#[no_mangle]
498pub unsafe extern "C" fn strchr(s: *const u8, c: c_int) -> *mut u8 {
499    let target = c as u8;
500    let mut i = 0;
501    loop {
502        let ch = *s.add(i);
503        if ch == target {
504            return s.add(i) as *mut u8;
505        }
506        if ch == 0 {
507            return null_mut();
508        }
509        i += 1;
510    }
511}
512
513#[no_mangle]
514pub unsafe extern "C" fn strrchr(s: *const u8, c: c_int) -> *mut u8 {
515    let target = c as u8;
516    let mut i = 0;
517    let mut last: *mut u8 = null_mut();
518    loop {
519        let ch = *s.add(i);
520        if ch == target {
521            last = s.add(i) as *mut u8;
522        }
523        if ch == 0 {
524            return last;
525        }
526        i += 1;
527    }
528}
529
530#[no_mangle]
531pub unsafe extern "C" fn strnlen(s: *const u8, maxlen: usize) -> usize {
532    let mut i = 0;
533    while i < maxlen && *s.add(i) != 0 {
534        i += 1;
535    }
536    i
537}
538
539#[no_mangle]
540pub unsafe extern "C" fn strcspn(s: *const u8, reject: *const u8) -> usize {
541    let mut i = 0;
542    loop {
543        let c = *s.add(i);
544        if c == 0 {
545            return i;
546        }
547        let mut j = 0;
548        loop {
549            let r = *reject.add(j);
550            if r == 0 {
551                break;
552            }
553            if c == r {
554                return i;
555            }
556            j += 1;
557        }
558        i += 1;
559    }
560}
561
562#[no_mangle]
563pub unsafe extern "C" fn strspn(s: *const u8, accept: *const u8) -> usize {
564    let mut i = 0;
565    loop {
566        let c = *s.add(i);
567        if c == 0 {
568            return i;
569        }
570        let mut found = false;
571        let mut j = 0;
572        loop {
573            let a = *accept.add(j);
574            if a == 0 {
575                break;
576            }
577            if c == a {
578                found = true;
579                break;
580            }
581            j += 1;
582        }
583        if !found {
584            return i;
585        }
586        i += 1;
587    }
588}
589
590#[no_mangle]
591pub unsafe extern "C" fn strpbrk(s: *const u8, accept: *const u8) -> *mut u8 {
592    let mut i = 0;
593    loop {
594        let c = *s.add(i);
595        if c == 0 {
596            return null_mut();
597        }
598        let mut j = 0;
599        loop {
600            let a = *accept.add(j);
601            if a == 0 {
602                break;
603            }
604            if c == a {
605                return s.add(i) as *mut u8;
606            }
607            j += 1;
608        }
609        i += 1;
610    }
611}
612
613#[no_mangle]
614pub unsafe extern "C" fn strstr(haystack: *const u8, needle: *const u8) -> *mut u8 {
615    if *needle == 0 {
616        return haystack as *mut u8;
617    }
618    let mut i = 0;
619    loop {
620        let h = *haystack.add(i);
621        if h == 0 {
622            return null_mut();
623        }
624        if h == *needle {
625            let mut j = 0;
626            loop {
627                let n = *needle.add(j);
628                if n == 0 {
629                    return haystack.add(i) as *mut u8;
630                }
631                if *haystack.add(i + j) != n {
632                    break;
633                }
634                j += 1;
635            }
636        }
637        i += 1;
638    }
639}
640
641#[no_mangle]
642pub unsafe extern "C" fn memchr(s: *const u8, c: c_int, n: usize) -> *mut u8 {
643    let target = c as u8;
644    let mut i = 0;
645    while i < n {
646        if *s.add(i) == target {
647            return s.add(i) as *mut u8;
648        }
649        i += 1;
650    }
651    null_mut()
652}
653
654#[no_mangle]
655pub unsafe extern "C" fn memrchr(s: *const u8, c: c_int, n: usize) -> *mut u8 {
656    let target = c as u8;
657    let mut i = n;
658    while i > 0 {
659        i -= 1;
660        if *s.add(i) == target {
661            return s.add(i) as *mut u8;
662        }
663    }
664    null_mut()
665}
666
667#[no_mangle]
668pub unsafe extern "C" fn memmem(
669    haystack: *const c_void, haystacklen: usize,
670    needle: *const c_void, needlelen: usize,
671) -> *mut c_void {
672    if needlelen == 0 { return haystack as *mut c_void; }
673    if haystacklen < needlelen { return null_mut(); }
674    let h = haystack as *const u8;
675    let n = needle as *const u8;
676    let last = haystacklen - needlelen;
677    for i in 0..=last {
678        if *h.add(i) == *n && memcmp(h.add(i) as *const c_void, n as *const c_void, needlelen) == 0 {
679            return h.add(i) as *mut c_void;
680        }
681    }
682    null_mut()
683}
684
685#[no_mangle]
686pub unsafe extern "C" fn strtok(s: *mut u8, delim: *const u8) -> *mut u8 {
687    static mut STATE: *mut u8 = core::ptr::null_mut();
688    let mut p = if s.is_null() { STATE } else { s };
689    if p.is_null() {
690        return core::ptr::null_mut();
691    }
692    loop {
693        let c = *p;
694        if c == 0 {
695            STATE = core::ptr::null_mut();
696            return core::ptr::null_mut();
697        }
698        let mut is_delim = false;
699        let mut i = 0;
700        loop {
701            let d = *delim.add(i);
702            if d == 0 {
703                break;
704            }
705            if c == d {
706                is_delim = true;
707                break;
708            }
709            i += 1;
710        }
711        if !is_delim {
712            break;
713        }
714        p = p.add(1);
715    }
716    let start = p;
717    loop {
718        let c = *p;
719        if c == 0 {
720            STATE = core::ptr::null_mut();
721            return start;
722        }
723        let mut is_delim = false;
724        let mut i = 0;
725        loop {
726            let d = *delim.add(i);
727            if d == 0 {
728                break;
729            }
730            if c == d {
731                is_delim = true;
732                break;
733            }
734            i += 1;
735        }
736        if is_delim {
737            *p = 0;
738            STATE = p.add(1);
739            return start;
740        }
741        p = p.add(1);
742    }
743}
744
745// ============================================================
746// C type aliases
747// ============================================================
748
749type SizeT = usize;
750type SSizeT = isize;
751type mode_t = c_uint;
752type TimeT = c_long;
753type ClockT = c_long;
754type wchar_t = c_int;
755type wint_t = c_uint;
756type wctype_t = *const c_int;
757type wctrans_t = *const c_int;
758
759const WEOF: wint_t = 0xffffffff;
760
761#[repr(C)]
762pub struct tm {
763    pub tm_sec: c_int,
764    pub tm_min: c_int,
765    pub tm_hour: c_int,
766    pub tm_mday: c_int,
767    pub tm_mon: c_int,
768    pub tm_year: c_int,
769    pub tm_wday: c_int,
770    pub tm_yday: c_int,
771    pub tm_isdst: c_int,
772    pub tm_gmtoff: c_long,
773    pub tm_zone: *const c_char,
774}
775
776#[repr(C)]
777pub struct timeval {
778    pub tv_sec: TimeT,
779    pub tv_usec: c_long,
780}
781
782#[repr(C)]
783pub struct Timeb {
784    pub time: TimeT,
785    pub millitm: u16,
786    pub timezone: i16,
787    pub dstflag: u16,
788}
789
790// ============================================================
791// ctype.h
792// ============================================================
793
794const CT_UPPER: u8 = 1 << 0;
795const CT_LOWER: u8 = 1 << 1;
796const CT_DIGIT: u8 = 1 << 2;
797const CT_SPACE: u8 = 1 << 3;
798const CT_PUNCT: u8 = 1 << 4;
799const CT_CNTRL: u8 = 1 << 5;
800const CT_BLANK: u8 = 1 << 6;
801const CT_XDIGIT: u8 = 1 << 7;
802
803const CT_TABLE: [u8; 128] = {
804    let mut t = [0u8; 128];
805    let mut i = 0;
806    while i < 128 {
807        let c = i as u8;
808        let mut flags = 0u8;
809        if c >= b'A' && c <= b'Z' {
810            flags |= CT_UPPER;
811        }
812        if c >= b'a' && c <= b'z' {
813            flags |= CT_LOWER;
814        }
815        if c >= b'0' && c <= b'9' {
816            flags |= CT_DIGIT;
817        }
818        if c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == b'\x0c' || c == b'\x0b' {
819            flags |= CT_SPACE;
820        }
821        if (c >= b'!' && c <= b'/')
822            || (c >= b':' && c <= b'@')
823            || (c >= b'[' && c <= b'`')
824            || (c >= b'{' && c <= b'~')
825        {
826            flags |= CT_PUNCT;
827        }
828        if c < 0x20 || c == 0x7f {
829            flags |= CT_CNTRL;
830        }
831        if c == b' ' || c == b'\t' {
832            flags |= CT_BLANK;
833        }
834        if (c >= b'0' && c <= b'9') || (c >= b'A' && c <= b'F') || (c >= b'a' && c <= b'f') {
835            flags |= CT_XDIGIT;
836        }
837        t[i] = flags;
838        i += 1;
839    }
840    t
841};
842
843#[inline]
844fn ct_flags(c: c_int) -> u8 {
845    if c < 0 || c > 127 {
846        0
847    } else {
848        CT_TABLE[c as usize]
849    }
850}
851
852#[no_mangle]
853pub extern "C" fn isalnum(c: c_int) -> c_int {
854    (ct_flags(c) & (CT_UPPER | CT_LOWER | CT_DIGIT) != 0) as c_int
855}
856
857#[no_mangle]
858pub extern "C" fn isalpha(c: c_int) -> c_int {
859    (ct_flags(c) & (CT_UPPER | CT_LOWER) != 0) as c_int
860}
861
862#[no_mangle]
863pub extern "C" fn isascii(c: c_int) -> c_int {
864    ((c as u32) <= 127) as c_int
865}
866
867#[no_mangle]
868pub extern "C" fn isblank(c: c_int) -> c_int {
869    (ct_flags(c) & CT_BLANK != 0) as c_int
870}
871
872#[no_mangle]
873pub extern "C" fn iscntrl(c: c_int) -> c_int {
874    (ct_flags(c) & CT_CNTRL != 0) as c_int
875}
876
877#[no_mangle]
878pub extern "C" fn isdigit(c: c_int) -> c_int {
879    (ct_flags(c) & CT_DIGIT != 0) as c_int
880}
881
882#[no_mangle]
883pub extern "C" fn isgraph(c: c_int) -> c_int {
884    (ct_flags(c) & (CT_UPPER | CT_LOWER | CT_DIGIT | CT_PUNCT) != 0) as c_int
885}
886
887#[no_mangle]
888pub extern "C" fn islower(c: c_int) -> c_int {
889    (ct_flags(c) & CT_LOWER != 0) as c_int
890}
891
892#[no_mangle]
893pub extern "C" fn isprint(c: c_int) -> c_int {
894    let flags = ct_flags(c);
895    (flags & (CT_UPPER | CT_LOWER | CT_DIGIT | CT_PUNCT | CT_BLANK) != 0) as c_int
896}
897
898#[no_mangle]
899pub extern "C" fn ispunct(c: c_int) -> c_int {
900    (ct_flags(c) & CT_PUNCT != 0) as c_int
901}
902
903#[no_mangle]
904pub extern "C" fn isspace(c: c_int) -> c_int {
905    (ct_flags(c) & CT_SPACE != 0) as c_int
906}
907
908#[no_mangle]
909pub extern "C" fn isupper(c: c_int) -> c_int {
910    (ct_flags(c) & CT_UPPER != 0) as c_int
911}
912
913#[no_mangle]
914pub extern "C" fn isxdigit(c: c_int) -> c_int {
915    (ct_flags(c) & CT_XDIGIT != 0) as c_int
916}
917
918#[no_mangle]
919pub extern "C" fn tolower(c: c_int) -> c_int {
920    if (ct_flags(c) & CT_UPPER) != 0 {
921        c + (b'a' as c_int - b'A' as c_int)
922    } else {
923        c
924    }
925}
926
927#[no_mangle]
928pub extern "C" fn toupper(c: c_int) -> c_int {
929    if (ct_flags(c) & CT_LOWER) != 0 {
930        c - (b'a' as c_int - b'A' as c_int)
931    } else {
932        c
933    }
934}
935
936// ============================================================
937// stdlib.h: integer conversion, abs, rand
938// ============================================================
939
940unsafe fn parse_digit(c: u8, base: c_int) -> Option<u8> {
941    if c == 0 { return None; }
942    let d = if c >= b'0' && c <= b'9' {
943        c - b'0'
944    } else if c >= b'a' && c <= b'z' {
945        c - b'a' + 10
946    } else if c >= b'A' && c <= b'Z' {
947        c - b'A' + 10
948    } else {
949        return None;
950    };
951    if (d as c_int) < base {
952        Some(d)
953    } else {
954        None
955    }
956}
957
958unsafe fn parse_prefix(s: *const u8, base: *mut c_int) -> *const u8 {
959    let mut p = s;
960    if *base == 0 {
961        if *p == b'0' {
962            if (*p.add(1) == b'x' || *p.add(1) == b'X') && parse_digit(*p.add(2), 16).is_some() {
963                *base = 16;
964                p = p.add(2);
965            } else {
966                *base = 8;
967            }
968        } else {
969            *base = 10;
970        }
971    } else if *base == 16 {
972        if *p == b'0' && (*p.add(1) == b'x' || *p.add(1) == b'X') && parse_digit(*p.add(2), 16).is_some() {
973            p = p.add(2);
974        }
975    }
976    p
977}
978
979unsafe fn strtox(
980    s: *const c_char,
981    endptr: *mut *mut c_char,
982    mut base: c_int,
983    pos_limit: u64,
984    neg_limit: u64,
985) -> (u64, bool, bool) {
986    let s0 = s as *const u8;
987    let mut p = s0;
988    while isspace(*p as c_int) != 0 {
989        p = p.add(1);
990    }
991
992    if base < 0 || base == 1 || base > 36 {
993        if !endptr.is_null() {
994            *endptr = s as *mut c_char;
995        }
996        ERRNO!() = EINVAL;
997        return (0, false, false);
998    }
999
1000    let mut neg = false;
1001    match *p {
1002        b'-' => { neg = true; p = p.add(1); }
1003        b'+' => p = p.add(1),
1004        _ => {}
1005    }
1006
1007    p = parse_prefix(p, &mut base);
1008
1009    let limit = if neg { neg_limit } else { pos_limit };
1010    let mut val: u64 = 0;
1011    let mut any = false;
1012    while let Some(d) = parse_digit(*p, base) {
1013        any = true;
1014        if val > (limit - d as u64) / base as u64 {
1015            while parse_digit(*p, base).is_some() { p = p.add(1); }
1016            if !endptr.is_null() { *endptr = p as *mut c_char; }
1017            ERRNO!() = ERANGE;
1018            return (limit, true, neg);
1019        }
1020        val = val * base as u64 + d as u64;
1021        p = p.add(1);
1022    }
1023
1024    if !endptr.is_null() {
1025        *endptr = if any { p as *mut c_char } else { s as *mut c_char };
1026    }
1027    (val, false, neg)
1028}
1029
1030#[no_mangle]
1031pub unsafe extern "C" fn strtol(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_long {
1032    let pos_limit = c_long::MAX as u64;
1033    let neg_limit = pos_limit.wrapping_add(1);
1034    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
1035    if overflow {
1036        return if neg { c_long::MIN } else { c_long::MAX };
1037    }
1038    if neg { val.wrapping_neg() as c_long } else { val as c_long }
1039}
1040
1041#[no_mangle]
1042pub unsafe extern "C" fn strtoul(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulong {
1043    let limit = c_ulong::MAX as u64;
1044    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
1045    if overflow {
1046        return c_ulong::MAX;
1047    }
1048    if neg { val.wrapping_neg() as c_ulong } else { val as c_ulong }
1049}
1050
1051#[no_mangle]
1052pub unsafe extern "C" fn strtoll(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_longlong {
1053    let pos_limit = c_longlong::MAX as u64;
1054    let neg_limit = pos_limit.wrapping_add(1);
1055    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
1056    if overflow {
1057        return if neg { c_longlong::MIN } else { c_longlong::MAX };
1058    }
1059    if neg { val.wrapping_neg() as c_longlong } else { val as c_longlong }
1060}
1061
1062#[no_mangle]
1063pub unsafe extern "C" fn strtoull(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulonglong {
1064    let limit = c_ulonglong::MAX as u64;
1065    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
1066    if overflow {
1067        return c_ulonglong::MAX;
1068    }
1069    if neg { val.wrapping_neg() as c_ulonglong } else { val as c_ulonglong }
1070}
1071
1072#[no_mangle]
1073pub unsafe extern "C" fn atoi(s: *const c_char) -> c_int {
1074    strtol(s, core::ptr::null_mut(), 10) as c_int
1075}
1076
1077#[no_mangle]
1078pub unsafe extern "C" fn atol(s: *const c_char) -> c_long {
1079    strtol(s, core::ptr::null_mut(), 10)
1080}
1081
1082#[no_mangle]
1083pub unsafe extern "C" fn atoll(s: *const c_char) -> c_longlong {
1084    strtoll(s, core::ptr::null_mut(), 10)
1085}
1086
1087#[no_mangle]
1088pub extern "C" fn abs(n: c_int) -> c_int {
1089    if n < 0 {
1090        -n
1091    } else {
1092        n
1093    }
1094}
1095
1096#[no_mangle]
1097pub extern "C" fn labs(n: c_long) -> c_long {
1098    if n < 0 {
1099        -n
1100    } else {
1101        n
1102    }
1103}
1104
1105#[no_mangle]
1106pub extern "C" fn llabs(n: c_longlong) -> c_longlong {
1107    if n < 0 {
1108        -n
1109    } else {
1110        n
1111    }
1112}
1113
1114static mut RAND_STATE: c_uint = 1;
1115
1116#[no_mangle]
1117pub extern "C" fn srand(seed: c_uint) {
1118    unsafe {
1119        RAND_STATE = seed;
1120    }
1121}
1122
1123#[no_mangle]
1124pub extern "C" fn rand() -> c_int {
1125    unsafe {
1126        RAND_STATE = RAND_STATE.wrapping_mul(1103515245).wrapping_add(12345);
1127        ((RAND_STATE >> 16) & 0x7fff) as c_int
1128    }
1129}
1130
1131// ============================================================
1132// stdlib.h: div, ldiv, lldiv
1133// ============================================================
1134
1135#[repr(C)]
1136pub struct div_t { pub quot: c_int, pub rem: c_int }
1137#[repr(C)]
1138pub struct ldiv_t { pub quot: c_long, pub rem: c_long }
1139#[repr(C)]
1140pub struct lldiv_t { pub quot: c_longlong, pub rem: c_longlong }
1141
1142#[no_mangle]
1143pub extern "C" fn div(num: c_int, den: c_int) -> div_t {
1144    div_t { quot: num / den, rem: num % den }
1145}
1146
1147#[no_mangle]
1148pub extern "C" fn ldiv(num: c_long, den: c_long) -> ldiv_t {
1149    ldiv_t { quot: num / den, rem: num % den }
1150}
1151
1152#[no_mangle]
1153pub extern "C" fn lldiv(num: c_longlong, den: c_longlong) -> lldiv_t {
1154    lldiv_t { quot: num / den, rem: num % den }
1155}
1156
1157// ============================================================
1158// bsearch
1159// ============================================================
1160
1161type CmpFn = unsafe extern "C" fn(*const c_void, *const c_void) -> c_int;
1162
1163#[no_mangle]
1164pub unsafe extern "C" fn bsearch(
1165    key: *const c_void,
1166    base: *const c_void,
1167    nel: usize,
1168    width: usize,
1169    cmp: CmpFn,
1170) -> *mut c_void {
1171    let mut base = base as *const u8;
1172    let mut nel = nel;
1173    while nel > 0 {
1174        let trial = base.add(width * (nel / 2));
1175        let sign = cmp(key, trial as *const c_void);
1176        if sign < 0 {
1177            nel /= 2;
1178        } else if sign > 0 {
1179            base = trial.add(width);
1180            nel -= nel / 2 + 1;
1181        } else {
1182            return trial as *mut c_void;
1183        }
1184    }
1185    null_mut()
1186}
1187
1188// ============================================================
1189// signal.h
1190// ============================================================
1191
1192pub const SA_RESTORER: c_ulong = 0x04000000;
1193
1194pub const SIG_DFL: usize = 0;
1195pub const SIG_IGN: usize = 1;
1196pub const SIG_ERR: usize = !0usize;
1197
1198pub const SIGHUP: c_int = 1;
1199pub const SIGINT: c_int = 2;
1200pub const SIGQUIT: c_int = 3;
1201pub const SIGILL: c_int = 4;
1202pub const SIGTRAP: c_int = 5;
1203pub const SIGABRT: c_int = 6;
1204pub const SIGIOT: c_int = 6;
1205pub const SIGBUS: c_int = 7;
1206pub const SIGFPE: c_int = 8;
1207pub const SIGKILL: c_int = 9;
1208pub const SIGUSR1: c_int = 10;
1209pub const SIGSEGV: c_int = 11;
1210pub const SIGUSR2: c_int = 12;
1211pub const SIGPIPE: c_int = 13;
1212pub const SIGALRM: c_int = 14;
1213pub const SIGTERM: c_int = 15;
1214pub const SIGSTKFLT: c_int = 16;
1215pub const SIGCHLD: c_int = 17;
1216pub const SIGCONT: c_int = 18;
1217pub const SIGSTOP: c_int = 19;
1218pub const SIGTSTP: c_int = 20;
1219pub const SIGTTIN: c_int = 21;
1220pub const SIGTTOU: c_int = 22;
1221pub const SIGURG: c_int = 23;
1222pub const SIGXCPU: c_int = 24;
1223pub const SIGXFSZ: c_int = 25;
1224pub const SIGVTALRM: c_int = 26;
1225pub const SIGPROF: c_int = 27;
1226pub const SIGWINCH: c_int = 28;
1227pub const SIGIO: c_int = 29;
1228pub const SIGPOLL: c_int = 29;
1229pub const SIGPWR: c_int = 30;
1230pub const SIGSYS: c_int = 31;
1231pub const SIGUNUSED: c_int = 31;
1232pub const _NSIG: c_int = 65;
1233
1234pub const SIG_BLOCK: c_int = 0;
1235pub const SIG_UNBLOCK: c_int = 1;
1236pub const SIG_SETMASK: c_int = 2;
1237
1238pub const SA_NOCLDSTOP: c_ulong = 1;
1239pub const SA_NOCLDWAIT: c_ulong = 2;
1240pub const SA_SIGINFO: c_ulong = 4;
1241pub const SA_ONSTACK: c_ulong = 0x08000000;
1242pub const SA_RESTART: c_ulong = 0x10000000;
1243pub const SA_NODEFER: c_ulong = 0x40000000;
1244pub const SA_RESETHAND: c_ulong = 0x80000000;
1245
1246pub const SS_ONSTACK: c_int = 1;
1247pub const SS_DISABLE: c_int = 2;
1248#[cfg(target_arch = "aarch64")]
1249pub const MINSIGSTKSZ: usize = 6144;
1250#[cfg(target_arch = "aarch64")]
1251pub const SIGSTKSZ: usize = 12288;
1252#[cfg(not(target_arch = "aarch64"))]
1253pub const MINSIGSTKSZ: usize = 2048;
1254#[cfg(not(target_arch = "aarch64"))]
1255pub const SIGSTKSZ: usize = 8192;
1256
1257pub const SI_USER: c_int = 0;
1258pub const SI_TKILL: c_int = -6;
1259
1260#[repr(C)]
1261pub struct timespec {
1262    pub tv_sec: c_long,
1263    pub tv_nsec: c_long,
1264}
1265
1266#[repr(C)]
1267pub struct siginfo_t {
1268    pub si_signo: c_int,
1269    pub si_errno: c_int,
1270    pub si_code: c_int,
1271    // The remaining bytes of the 128-byte siginfo_t are not accessed.
1272    _pad: [u8; 128 - 3 * core::mem::size_of::<c_int>()],
1273}
1274
1275#[repr(C)]
1276pub struct stack_t {
1277    pub ss_sp: *mut c_void,
1278    pub ss_flags: c_int,
1279    pub ss_size: usize,
1280}
1281
1282// Kernel ABI for rt_sigaction (x86_64/riscv64/aarch64 all use the same
1283// handler/flags/restorer/8-byte-mask layout).
1284#[repr(C)]
1285pub struct KSigAction {
1286    pub sa_handler: usize,
1287    pub sa_flags: c_ulong,
1288    pub sa_restorer: usize,
1289    pub sa_mask: [c_ulong; 1],
1290}
1291
1292// musl's public layout: handler, 128-byte sigset_t, flags, restorer.
1293#[repr(C)]
1294pub struct sigaction {
1295    pub sa_handler: usize,
1296    pub sa_mask: [u64; 16],
1297    pub sa_flags: c_int,
1298    pub sa_restorer: usize,
1299}
1300
1301pub type SigSetT = c_ulong;
1302
1303#[cfg(target_arch = "x86_64")]
1304core::arch::global_asm!(
1305    ".global sig_restorer",
1306    ".type sig_restorer, @function",
1307    "sig_restorer:",
1308    "mov eax, 15",
1309    "syscall",
1310);
1311
1312#[cfg(target_arch = "aarch64")]
1313core::arch::global_asm!(
1314    ".global sig_restorer",
1315    ".type sig_restorer, @function",
1316    "sig_restorer:",
1317    "mov x8, #139",
1318    "svc #0",
1319);
1320
1321#[cfg(target_arch = "riscv64")]
1322core::arch::global_asm!(
1323    ".global sig_restorer",
1324    ".type sig_restorer, @function",
1325    "sig_restorer:",
1326    "li a7, 139",
1327    "ecall",
1328);
1329
1330extern "C" {
1331    fn sig_restorer();
1332}
1333
1334#[inline]
1335unsafe fn sys_rt_sigaction(sig: c_int,
1336    act: *const KSigAction,
1337    oldact: *mut KSigAction,
1338    sigsetsize: usize,) -> i64 {
1339    <Arch as Syscalls>::syscall4(SYS_RT_SIGACTION, sig as i64, act as i64, oldact as i64, sigsetsize as i64)
1340}
1341
1342#[inline]
1343unsafe fn sys_rt_sigprocmask(how: c_int,
1344    set: *const SigSetT,
1345    oldset: *mut SigSetT,
1346    sigsetsize: usize,) -> i64 {
1347    <Arch as Syscalls>::syscall4(SYS_RT_SIGPROCMASK, how as i64, set as i64, oldset as i64, sigsetsize as i64)
1348}
1349
1350#[inline]
1351unsafe fn sys_rt_sigpending(set: *mut SigSetT, sigsetsize: usize) -> i64 {
1352    <Arch as Syscalls>::syscall2(SYS_RT_SIGPENDING, set as i64, sigsetsize as i64)
1353}
1354
1355#[inline]
1356unsafe fn sys_rt_sigsuspend(mask: *const SigSetT, sigsetsize: usize) -> i64 {
1357    <Arch as Syscalls>::syscall2(SYS_RT_SIGSUSPEND, mask as i64, sigsetsize as i64)
1358}
1359
1360#[inline]
1361unsafe fn sys_rt_sigtimedwait(set: *const SigSetT,
1362    info: *mut siginfo_t,
1363    timeout: *const timespec,
1364    sigsetsize: usize,) -> i64 {
1365    <Arch as Syscalls>::syscall4(SYS_RT_SIGTIMEDWAIT, set as i64, info as i64, timeout as i64, sigsetsize as i64)
1366}
1367
1368#[inline]
1369unsafe fn sys_sigaltstack(ss: *const stack_t, old_ss: *mut stack_t) -> i64 {
1370    <Arch as Syscalls>::syscall2(SYS_SIGALTSTACK, ss as i64, old_ss as i64)
1371}
1372
1373#[inline]
1374unsafe fn sys_tgkill(tgid: c_int, tid: c_int, sig: c_int) -> i64 {
1375    <Arch as Syscalls>::syscall3(SYS_TGKILL, tgid as i64, tid as i64, sig as i64)
1376}
1377
1378const CLOCK_REALTIME: c_int = 0;
1379const CLOCK_MONOTONIC: c_int = 1;
1380
1381#[inline]
1382unsafe fn sys_clock_gettime(clockid: c_int, ts: *mut timespec) -> i64 {
1383    <Arch as Syscalls>::syscall2(SYS_CLOCK_GETTIME, clockid as i64, ts as i64)
1384}
1385
1386// clock_gettime lives in vdso.rs: it prefers the kernel's vDSO entry point
1387// and only falls back to sys_clock_gettime() there.
1388
1389#[no_mangle]
1390pub unsafe extern "C" fn sigprocmask(
1391    how: c_int,
1392    set: *const SigSetT,
1393    oldset: *mut SigSetT,
1394) -> c_int {
1395    // mask out internal rt signals (32, 33) before touching the kernel
1396    let internal_mask: SigSetT = (1u64 << 31) | (1u64 << 32);
1397    let filtered: SigSetT;
1398    let set_ptr: *const SigSetT = if set.is_null() {
1399        set
1400    } else {
1401        filtered = *set & !internal_mask;
1402        &filtered
1403    };
1404    let r = sys_rt_sigprocmask(how, set_ptr, oldset, core::mem::size_of::<SigSetT>());
1405    if r < 0 {
1406        ERRNO!() = (-r) as c_int;
1407        return -1;
1408    }
1409    if !oldset.is_null() {
1410        *oldset &= !internal_mask;
1411    }
1412    0
1413}
1414
1415#[inline]
1416unsafe fn sys_kill(pid: c_int, sig: c_int) -> i64 {
1417    <Arch as Syscalls>::syscall2(SYS_KILL, pid as i64, sig as i64)
1418}
1419
1420#[inline]
1421unsafe fn sys_getpid() -> i64 {
1422    <Arch as Syscalls>::syscall0(SYS_GETPID)
1423}
1424
1425#[no_mangle]
1426pub unsafe extern "C" fn sigaction(
1427    signum: c_int,
1428    act: *const sigaction,
1429    oldact: *mut sigaction,
1430) -> c_int {
1431    let mut kact: KSigAction = core::mem::zeroed();
1432    let act_ptr = if act.is_null() {
1433        core::ptr::null()
1434    } else {
1435        kact.sa_handler = (*act).sa_handler;
1436        kact.sa_flags = ((*act).sa_flags as c_ulong) | SA_RESTORER;
1437        kact.sa_restorer = if (*act).sa_flags as c_ulong & SA_RESTORER != 0
1438            && (*act).sa_restorer != 0
1439        {
1440            (*act).sa_restorer
1441        } else {
1442            sig_restorer as *const () as usize
1443        };
1444        kact.sa_mask[0] = (*act).sa_mask[0];
1445        &kact
1446    };
1447    let mut kold: KSigAction = core::mem::zeroed();
1448    let old_ptr = if oldact.is_null() { core::ptr::null_mut() } else { &mut kold };
1449    let r = sys_rt_sigaction(signum, act_ptr, old_ptr, 8);
1450    if r < 0 {
1451        ERRNO!() = (-r) as c_int;
1452        return -1;
1453    }
1454    if !oldact.is_null() {
1455        (*oldact).sa_handler = kold.sa_handler;
1456        (*oldact).sa_flags = kold.sa_flags as c_int;
1457        (*oldact).sa_restorer = kold.sa_restorer;
1458        (*oldact).sa_mask = [0; 16];
1459        (*oldact).sa_mask[0] = kold.sa_mask[0];
1460    }
1461    0
1462}
1463
1464#[no_mangle]
1465pub unsafe extern "C" fn signal(signum: c_int, handler: usize) -> usize {
1466    // musl's signal() installs the handler with SA_RESTART, so interrupted
1467    // syscalls (waitpid, read, ...) are restarted automatically.
1468    let act = sigaction {
1469        sa_handler: handler,
1470        sa_mask: [0; 16],
1471        sa_flags: SA_RESTART as c_int,
1472        sa_restorer: 0,
1473    };
1474    let mut old: sigaction = core::mem::zeroed();
1475    if sigaction(signum, &act, &mut old) == -1 {
1476        SIG_ERR
1477    } else {
1478        old.sa_handler
1479    }
1480}
1481
1482#[no_mangle]
1483pub unsafe extern "C" fn kill(pid: c_int, sig: c_int) -> c_int {
1484    let r = sys_kill(pid, sig);
1485    syscall_ret(r) as c_int
1486}
1487
1488#[no_mangle]
1489pub unsafe extern "C" fn tgkill(tgid: c_int, tid: c_int, sig: c_int) -> c_int {
1490    let r = sys_tgkill(tgid, tid, sig);
1491    syscall_ret(r) as c_int
1492}
1493
1494#[no_mangle]
1495pub unsafe extern "C" fn getpid() -> c_int {
1496    sys_getpid() as c_int
1497}
1498
1499#[no_mangle]
1500pub unsafe extern "C" fn raise(sig: c_int) -> c_int {
1501    let r = sys_tgkill(sys_getpid() as c_int, sys_gettid() as c_int, sig);
1502    syscall_ret(r) as c_int
1503}
1504
1505#[no_mangle]
1506pub unsafe extern "C" fn sigemptyset(set: *mut SigSetT) -> c_int {
1507    *set = 0;
1508    0
1509}
1510
1511#[no_mangle]
1512pub unsafe extern "C" fn sigfillset(set: *mut SigSetT) -> c_int {
1513    // musl: all signals except 32 (SIGCANCEL) and 33 (SIGSYNCCALL)
1514    *set = 0xFFFF_FFFC_7FFF_FFFFu64;
1515    0
1516}
1517
1518#[no_mangle]
1519pub unsafe extern "C" fn sigaddset(set: *mut SigSetT, signum: c_int) -> c_int {
1520    let s = (signum as c_uint).wrapping_sub(1);
1521    if s as usize >= 64 {
1522        ERRNO!() = EINVAL;
1523        return -1;
1524    }
1525    // internal rt signals (32, 33) cannot be manipulated
1526    if signum >= 32 && signum < __libc_current_sigrtmin() {
1527        return 0;
1528    }
1529    *set |= 1u64 << s;
1530    0
1531}
1532
1533#[no_mangle]
1534pub unsafe extern "C" fn sigdelset(set: *mut SigSetT, signum: c_int) -> c_int {
1535    let s = (signum as c_uint).wrapping_sub(1);
1536    if s as usize >= 64 {
1537        ERRNO!() = EINVAL;
1538        return -1;
1539    }
1540    // internal rt signals (32, 33) are never members
1541    if signum >= 32 && signum < __libc_current_sigrtmin() {
1542        return 0;
1543    }
1544    *set &= !(1u64 << s);
1545    0
1546}
1547
1548#[no_mangle]
1549pub unsafe extern "C" fn sigismember(set: *const SigSetT, signum: c_int) -> c_int {
1550    let s = (signum as c_uint).wrapping_sub(1);
1551    if s as usize >= 64 { return 0; }
1552    // internal rt signals (32, 33) are never members
1553    if signum >= 32 && signum < __libc_current_sigrtmin() {
1554        return 0;
1555    }
1556    ((*set & (1u64 << s)) != 0) as c_int
1557}
1558
1559#[no_mangle]
1560pub unsafe extern "C" fn sigpending(set: *mut SigSetT) -> c_int {
1561    let r = sys_rt_sigpending(set, core::mem::size_of::<SigSetT>());
1562    syscall_ret(r) as c_int
1563}
1564
1565#[no_mangle]
1566pub unsafe extern "C" fn sigsuspend(mask: *const SigSetT) -> c_int {
1567    let r = sys_rt_sigsuspend(mask, core::mem::size_of::<SigSetT>());
1568    if r < 0 {
1569        ERRNO!() = (-r) as c_int;
1570    }
1571    -1
1572}
1573
1574#[no_mangle]
1575pub unsafe extern "C" fn sigtimedwait(
1576    mask: *const SigSetT,
1577    info: *mut siginfo_t,
1578    timeout: *const timespec,
1579) -> c_int {
1580    loop {
1581        let r = sys_rt_sigtimedwait(mask, info, timeout, core::mem::size_of::<SigSetT>());
1582        if r >= 0 {
1583            return r as c_int;
1584        }
1585        let e = (-r) as c_int;
1586        if e != EINTR {
1587            ERRNO!() = e;
1588            return -1;
1589        }
1590    }
1591}
1592
1593#[no_mangle]
1594pub unsafe extern "C" fn sigwaitinfo(
1595    mask: *const SigSetT,
1596    info: *mut siginfo_t,
1597) -> c_int {
1598    sigtimedwait(mask, info, core::ptr::null())
1599}
1600
1601#[no_mangle]
1602pub unsafe extern "C" fn sigwait(
1603    mask: *const SigSetT,
1604    sig: *mut c_int,
1605) -> c_int {
1606    let mut info: siginfo_t = core::mem::zeroed();
1607    if sigtimedwait(mask, &mut info, core::ptr::null()) < 0 {
1608        return ERRNO!();
1609    }
1610    *sig = info.si_signo;
1611    0
1612}
1613
1614#[no_mangle]
1615pub unsafe extern "C" fn sigaltstack(ss: *const stack_t, old_ss: *mut stack_t) -> c_int {
1616    if !ss.is_null() {
1617        if (*ss).ss_flags & SS_ONSTACK != 0 {
1618            ERRNO!() = EINVAL;
1619            return -1;
1620        }
1621        if (*ss).ss_flags & SS_DISABLE == 0 && (*ss).ss_size < MINSIGSTKSZ {
1622            ERRNO!() = ENOMEM;
1623            return -1;
1624        }
1625    }
1626    let r = sys_sigaltstack(ss, old_ss);
1627    syscall_ret(r) as c_int
1628}
1629
1630// ============================================================
1631// setjmp.h
1632// jmp_buf is unsigned long[8]: rbx, rbp, r12-r15, rsp, rip
1633// ============================================================
1634
1635#[no_mangle]
1636#[inline(never)]
1637#[cfg(target_arch = "x86_64")]
1638pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1639    core::arch::asm!(
1640        "mov rax, [rsp]",
1641        "lea rcx, [rsp + 8]",
1642        "mov [r8], rbx",
1643        "mov [r8 + 8], rbp",
1644        "mov [r8 + 16], r12",
1645        "mov [r8 + 24], r13",
1646        "mov [r8 + 32], r14",
1647        "mov [r8 + 40], r15",
1648        "mov [r8 + 48], rcx",
1649        "mov [r8 + 56], rax",
1650        in("r8") env,
1651        lateout("rax") _,
1652        lateout("rcx") _,
1653        options(nostack),
1654    );
1655    0
1656}
1657
1658#[no_mangle]
1659#[inline(never)]
1660#[cfg(target_arch = "x86_64")]
1661pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1662    let ret = if val == 0 { 1 } else { val } as u32;
1663    core::arch::asm!(
1664        "mov rbx, [r8]",
1665        "mov rbp, [r8 + 8]",
1666        "mov r12, [r8 + 16]",
1667        "mov r13, [r8 + 24]",
1668        "mov r14, [r8 + 32]",
1669        "mov r15, [r8 + 40]",
1670        "mov rsp, [r8 + 48]",
1671        "mov eax, edx",
1672        "jmp [r8 + 56]",
1673        in("r8") env,
1674        in("edx") ret,
1675        options(noreturn),
1676    );
1677}
1678
1679#[no_mangle]
1680#[unsafe(naked)]
1681#[cfg(target_arch = "aarch64")]
1682pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1683    core::arch::naked_asm!(
1684        "stp x19, x20, [x0, #0]",
1685        "stp x21, x22, [x0, #16]",
1686        "stp x23, x24, [x0, #32]",
1687        "stp x25, x26, [x0, #48]",
1688        "stp x27, x28, [x0, #64]",
1689        "stp x29, x30, [x0, #80]",
1690        "mov x2, sp",
1691        "str x2, [x0, #104]",
1692        "stp d8, d9, [x0, #112]",
1693        "stp d10, d11, [x0, #128]",
1694        "stp d12, d13, [x0, #144]",
1695        "stp d14, d15, [x0, #160]",
1696        "mov x0, #0",
1697        "ret",
1698    );
1699}
1700
1701#[no_mangle]
1702#[inline(never)]
1703#[cfg(target_arch = "aarch64")]
1704pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1705    let ret = if val == 0 { 1 } else { val } as u64;
1706    core::arch::asm!(
1707        "ldp x19, x20, [x0]",
1708        "ldp x21, x22, [x0, #16]",
1709        "ldp x23, x24, [x0, #32]",
1710        "ldp x25, x26, [x0, #48]",
1711        "ldp x27, x28, [x0, #64]",
1712        "ldp x29, x30, [x0, #80]",
1713        "ldr x2, [x0, #104]",
1714        "mov sp, x2",
1715        "ldp d8, d9, [x0, #112]",
1716        "ldp d10, d11, [x0, #128]",
1717        "ldp d12, d13, [x0, #144]",
1718        "ldp d14, d15, [x0, #160]",
1719        "mov x0, x1",
1720        "br x30",
1721        in("x0") env,
1722        in("x1") ret,
1723        options(noreturn),
1724    );
1725}
1726
1727#[no_mangle]
1728#[unsafe(naked)]
1729#[cfg(target_arch = "riscv64")]
1730pub unsafe extern "C" fn setjmp(env: *mut c_ulong) -> c_int {
1731    core::arch::naked_asm!(
1732        "sd s0, 0(a0)",
1733        "sd s1, 8(a0)",
1734        "sd s2, 16(a0)",
1735        "sd s3, 24(a0)",
1736        "sd s4, 32(a0)",
1737        "sd s5, 40(a0)",
1738        "sd s6, 48(a0)",
1739        "sd s7, 56(a0)",
1740        "sd s8, 64(a0)",
1741        "sd s9, 72(a0)",
1742        "sd s10, 80(a0)",
1743        "sd s11, 88(a0)",
1744        "sd sp, 96(a0)",
1745        "sd ra, 104(a0)",
1746        "li a0, 0",
1747        "ret",
1748    );
1749}
1750
1751#[no_mangle]
1752#[inline(never)]
1753#[cfg(target_arch = "riscv64")]
1754pub unsafe extern "C" fn longjmp(env: *const c_ulong, val: c_int) -> ! {
1755    let ret = if val == 0 { 1 } else { val } as u64;
1756    core::arch::asm!(
1757        "ld s0, 0(a0)",
1758        "ld s1, 8(a0)",
1759        "ld s2, 16(a0)",
1760        "ld s3, 24(a0)",
1761        "ld s4, 32(a0)",
1762        "ld s5, 40(a0)",
1763        "ld s6, 48(a0)",
1764        "ld s7, 56(a0)",
1765        "ld s8, 64(a0)",
1766        "ld s9, 72(a0)",
1767        "ld s10, 80(a0)",
1768        "ld s11, 88(a0)",
1769        "ld sp, 96(a0)",
1770        "ld ra, 104(a0)",
1771        "mv a0, a1",
1772        "ret",
1773        in("a0") env,
1774        in("a1") ret,
1775        options(noreturn),
1776    );
1777}
1778
1779// sigsetjmp is implemented in raw assembly because the Rust compiler
1780// rewrites naked_asm that touches rbx into incorrect push/pop sequences,
1781// corrupting the caller's rbx across the initial return. The exported wrappers
1782// jump to a local hidden assembly implementation; the layout matches musl:
1783// env[0..7] = __jmp_buf, env[8] = saved return address, env[9] = saved signal
1784// mask, env[10] = saved rbx.
1785
1786#[no_mangle]
1787#[unsafe(naked)]
1788#[cfg(target_arch = "x86_64")]
1789pub unsafe extern "C" fn sigsetjmp(_env: *mut c_ulong, _savemask: c_int) -> c_int {
1790    core::arch::naked_asm!("jmp sigsetjmp_real");
1791}
1792
1793#[no_mangle]
1794#[unsafe(naked)]
1795#[cfg(target_arch = "x86_64")]
1796pub unsafe extern "C" fn __sigsetjmp(_env: *mut c_ulong, _savemask: c_int) -> c_int {
1797    core::arch::naked_asm!("jmp sigsetjmp_real");
1798}
1799
1800#[cfg(target_arch = "x86_64")]
1801core::arch::global_asm!(
1802    ".type sigsetjmp_real, @function",
1803    "sigsetjmp_real:",
1804    "   test esi, esi",
1805    "   jz 1f",
1806    "   pop qword ptr [rdi + 64]",
1807    "   mov qword ptr [rdi + 80], rbx",
1808    // Do not push rbx here: it would move the stack by 8 bytes and make
1809    // setjmp save an rsp that is 8 bytes below the caller's, misaligning the
1810    // caller after longjmp (postgres bootstrap crashes in AVX memset).
1811    "   mov rbx, rdi",
1812    "   call setjmp",
1813    "   push qword ptr [rbx + 64]",
1814    "   mov rdi, rbx",
1815    "   mov esi, eax",
1816    "   mov rbx, qword ptr [rbx + 80]",
1817    "   lea rdx, [rdi + 72]",
1818    "   test esi, esi",
1819    "   jz 2f",
1820    "   mov rsi, rdx",
1821    "   xor rdx, rdx",
1822    "   mov edi, 2",
1823    "   jmp 3f",
1824    "2:",
1825    "   xor rsi, rsi",
1826    "   mov edi, 2",
1827    "3:",
1828    "   mov eax, 14",
1829    "   mov r10d, 8",
1830    "   syscall",
1831    "   test esi, esi",
1832    "   jnz 4f",
1833    "   mov rax, 0xfffffffe7fffffff",
1834    "   and qword ptr [rdx], rax",
1835    "4:",
1836    "   mov eax, esi",
1837    "   ret",
1838    "1:",
1839    "   jmp setjmp",
1840);
1841
1842
1843#[no_mangle]
1844#[cfg(target_arch = "aarch64")]
1845pub unsafe extern "C" fn __sigsetjmp_tail(env: *mut c_ulong, ret: c_int) -> c_int {
1846    const SIG_SETMASK: c_int = 2;
1847    let ss = env.add(23) as *mut SigSetT;
1848    let set = if ret != 0 { ss as *const SigSetT } else { core::ptr::null() };
1849    let old = if ret != 0 { core::ptr::null_mut() } else { ss };
1850    let _ = sys_rt_sigprocmask(SIG_SETMASK, set, old, core::mem::size_of::<SigSetT>());
1851    ret
1852}
1853
1854#[no_mangle]
1855#[unsafe(naked)]
1856#[cfg(target_arch = "aarch64")]
1857pub unsafe extern "C" fn sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1858    core::arch::naked_asm!(
1859        "cbz w1, setjmp",
1860        "str x30, [x0, #176]",
1861        "str x19, [x0, #192]",
1862        "mov x19, x0",
1863        "bl setjmp",
1864        "mov w1, w0",
1865        "mov x0, x19",
1866        "ldr x30, [x0, #176]",
1867        "ldr x19, [x0, #192]",
1868        "b __sigsetjmp_tail",
1869    );
1870}
1871
1872#[no_mangle]
1873#[unsafe(naked)]
1874#[cfg(target_arch = "aarch64")]
1875pub unsafe extern "C" fn __sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1876    core::arch::naked_asm!(
1877        "cbz w1, setjmp",
1878        "str x30, [x0, #176]",
1879        "str x19, [x0, #192]",
1880        "mov x19, x0",
1881        "bl setjmp",
1882        "mov w1, w0",
1883        "mov x0, x19",
1884        "ldr x30, [x0, #176]",
1885        "ldr x19, [x0, #192]",
1886        "b __sigsetjmp_tail",
1887    );
1888}
1889
1890
1891#[no_mangle]
1892#[cfg(target_arch = "riscv64")]
1893pub unsafe extern "C" fn __sigsetjmp_tail(env: *mut c_ulong, ret: c_int) -> c_int {
1894    const SIG_SETMASK: c_int = 2;
1895    let ss = env.add(27) as *mut SigSetT;
1896    let set = if ret != 0 { ss as *const SigSetT } else { core::ptr::null() };
1897    let old = if ret != 0 { core::ptr::null_mut() } else { ss };
1898    let _ = sys_rt_sigprocmask(SIG_SETMASK, set, old, core::mem::size_of::<SigSetT>());
1899    ret
1900}
1901
1902#[no_mangle]
1903#[unsafe(naked)]
1904#[cfg(target_arch = "riscv64")]
1905pub unsafe extern "C" fn sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1906    core::arch::naked_asm!(
1907        "bnez a1, 1f",
1908        "tail setjmp",
1909        "1:",
1910        "sd ra, 208(a0)",
1911        "sd s0, 224(a0)",
1912        "mv s0, a0",
1913        "call setjmp",
1914        "mv a1, a0",
1915        "mv a0, s0",
1916        "ld s0, 224(a0)",
1917        "ld ra, 208(a0)",
1918        "tail __sigsetjmp_tail",
1919    );
1920}
1921
1922#[no_mangle]
1923#[unsafe(naked)]
1924#[cfg(target_arch = "riscv64")]
1925pub unsafe extern "C" fn __sigsetjmp(env: *mut c_ulong, savemask: c_int) -> c_int {
1926    core::arch::naked_asm!(
1927        "bnez a1, 1f",
1928        "tail setjmp",
1929        "1:",
1930        "sd ra, 208(a0)",
1931        "sd s0, 224(a0)",
1932        "mv s0, a0",
1933        "call setjmp",
1934        "mv a1, a0",
1935        "mv a0, s0",
1936        "ld s0, 224(a0)",
1937        "ld ra, 208(a0)",
1938        "tail __sigsetjmp_tail",
1939    );
1940}
1941
1942#[no_mangle]
1943#[inline(never)]
1944pub unsafe extern "C" fn siglongjmp(env: *const c_ulong, val: c_int) -> ! {
1945    longjmp(env, val);
1946}
1947
1948// ============================================================
1949// syscall wrappers: fstat/newfstatat/getrlimit/setrlimit/utimensat
1950// ============================================================
1951
1952#[inline]
1953unsafe fn sys_newfstatat(dirfd: i32, path: *const c_char, buf: *mut u8, flags: i32) -> i64 {
1954    <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, dirfd as i64, path as i64, buf as i64, flags as i64)
1955}
1956
1957#[inline]
1958unsafe fn sys_fstat(fd: i32, buf: *mut u8) -> i64 {
1959    <Arch as Syscalls>::syscall2(SYS_FSTAT, fd as i64, buf as i64)
1960}
1961
1962#[inline]
1963unsafe fn sys_getrlimit(resource: i32, rlim: *mut u8) -> i64 {
1964    <Arch as Syscalls>::syscall2(SYS_GETRLIMIT, resource as i64, rlim as i64)
1965}
1966
1967#[inline]
1968unsafe fn sys_setrlimit(resource: i32, rlim: *const u8) -> i64 {
1969    <Arch as Syscalls>::syscall2(SYS_SETRLIMIT, resource as i64, rlim as i64)
1970}
1971
1972#[inline]
1973unsafe fn sys_utimensat(dirfd: i32, path: *const c_char, times: *const u8, flags: i32) -> i64 {
1974    <Arch as Syscalls>::syscall4(SYS_UTIMENSAT, dirfd as i64, path as i64, times as i64, flags as i64)
1975}
1976
1977// ============================================================
1978// unistd.h: process primitives
1979// ============================================================
1980
1981#[inline]
1982unsafe fn sys_fork() -> i64 {
1983    #[cfg(target_arch = "x86_64")]
1984    { <Arch as Syscalls>::syscall0(SYS_FORK) }
1985    #[cfg(target_arch = "aarch64")]
1986    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
1987    #[cfg(target_arch = "riscv64")]
1988    { <Arch as Syscalls>::syscall2(SYS_CLONE, 17, 0) }
1989}
1990
1991
1992#[inline]
1993unsafe fn sys_execve(path: *const c_char, argv: *const *const c_char, envp: *const *const c_char) -> i64 {
1994    <Arch as Syscalls>::syscall3(SYS_EXECVE, path as i64, argv as i64, envp as i64)
1995}
1996
1997#[inline]
1998unsafe fn sys_wait4(pid: c_int, status: *mut c_int, options: c_int, rusage: *mut c_void) -> i64 {
1999    <Arch as Syscalls>::syscall4(SYS_WAIT4, pid as i64, status as i64, options as i64, rusage as i64)
2000}
2001
2002#[inline]
2003unsafe fn sys_getppid() -> i64 {
2004    <Arch as Syscalls>::syscall0(SYS_GETPPID)
2005}
2006
2007#[inline]
2008unsafe fn sys_getuid() -> i64 {
2009    <Arch as Syscalls>::syscall0(SYS_GETUID)
2010}
2011
2012#[inline]
2013unsafe fn sys_getgid() -> i64 {
2014    <Arch as Syscalls>::syscall0(SYS_GETGID)
2015}
2016
2017#[inline]
2018unsafe fn sys_geteuid() -> i64 {
2019    <Arch as Syscalls>::syscall0(SYS_GETEUID)
2020}
2021
2022#[inline]
2023unsafe fn sys_getegid() -> i64 {
2024    <Arch as Syscalls>::syscall0(SYS_GETEGID)
2025}
2026
2027#[no_mangle]
2028pub unsafe extern "C" fn fork() -> c_int {
2029    __fork_handler(-1);
2030    let ret = sys_fork();
2031    // Run the atfork handlers before publishing errno, exactly like musl's
2032    // __syscall_ret: a failing fork must report the kernel's errno even if a
2033    // handler changes errno. RLIMIT_NPROC is enforced by the kernel and does
2034    // not apply to root, so do not second-guess it here.
2035    if ret < 0 {
2036        let err = (-ret) as c_int;
2037        __fork_handler(0);
2038        ERRNO!() = err;
2039        return -1;
2040    }
2041    if ret == 0 {
2042        allocator_after_fork();
2043        thread_allocator_after_fork();
2044        __fork_handler(1);
2045    } else {
2046        __fork_handler(0);
2047    }
2048    ret as c_int
2049}
2050
2051#[no_mangle]
2052pub unsafe extern "C" fn execve(
2053    path: *const c_char,
2054    argv: *const *const c_char,
2055    envp: *const *const c_char,
2056) -> c_int {
2057    let r = sys_execve(path, argv, envp);
2058    syscall_ret(r) as c_int
2059}
2060
2061#[no_mangle]
2062pub unsafe extern "C" fn wait(status: *mut c_int) -> c_int {
2063    let r = sys_wait4(-1, status, 0, core::ptr::null_mut());
2064    syscall_ret(r) as c_int
2065}
2066
2067#[no_mangle]
2068pub unsafe extern "C" fn waitpid(pid: c_int, status: *mut c_int, options: c_int) -> c_int {
2069    let r = sys_wait4(pid, status, options, core::ptr::null_mut());
2070    syscall_ret(r) as c_int
2071}
2072
2073#[no_mangle]
2074pub unsafe extern "C" fn getppid() -> c_int {
2075    sys_getppid() as c_int
2076}
2077
2078#[no_mangle]
2079pub unsafe extern "C" fn getuid() -> c_uint {
2080    sys_getuid() as c_uint
2081}
2082
2083#[no_mangle]
2084pub unsafe extern "C" fn getgid() -> c_uint {
2085    sys_getgid() as c_uint
2086}
2087
2088#[no_mangle]
2089pub unsafe extern "C" fn geteuid() -> c_uint {
2090    sys_geteuid() as c_uint
2091}
2092
2093#[no_mangle]
2094pub unsafe extern "C" fn getegid() -> c_uint {
2095    sys_getegid() as c_uint
2096}
2097
2098#[no_mangle]
2099pub unsafe extern "C" fn vfork() -> c_int {
2100    // keel uses the portable fork semantics; fork() also runs the atfork
2101    // handlers and resets the allocator/thread caches in the child.
2102    fork()
2103}
2104
2105#[no_mangle]
2106pub unsafe extern "C" fn execl(path: *const c_char, arg: *const c_char, mut args: ...) -> c_int {
2107    let mut cap = 16usize;
2108    let mut argv = malloc(cap * core::mem::size_of::<*const c_char>()) as *mut *const c_char;
2109    if argv.is_null() { ERRNO!() = ENOMEM; return -1; }
2110    *argv.add(0) = arg;
2111    let mut n: usize = 1;
2112    loop {
2113        let a: *const c_char = args.next_arg();
2114        if a.is_null() { break; }
2115        if n + 1 >= cap {
2116            cap = match cap.checked_mul(2) { Some(v) => v, None => { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; } };
2117            let grown = realloc(argv as *mut c_void, cap * core::mem::size_of::<*const c_char>()) as *mut *const c_char;
2118            if grown.is_null() { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; }
2119            argv = grown;
2120        }
2121        *argv.add(n) = a;
2122        n += 1;
2123    }
2124    *argv.add(n) = core::ptr::null();
2125    let r = sys_execve(path, argv, __environ as *const *const c_char);
2126    free(argv as *mut c_void);
2127    syscall_ret(r) as c_int
2128}
2129
2130// ============================================================
2131// spawn.h: posix_spawn family
2132// ============================================================
2133
2134// Matches musl's posix_spawn_file_actions_t layout.  Actions are a growable
2135// linked list; PATH search uses a stack buffer and an O(n) scan per entry.
2136unsafe fn spawn_execvp(file: *const c_char, argv: *const *const c_char, envp: *const *const c_char) -> ! {
2137    let flen = strlen(file as *const c_char);
2138    let f = file as *const u8;
2139    let mut has_slash = false;
2140    for i in 0..flen {
2141        if *f.add(i) == b'/' { has_slash = true; break; }
2142    }
2143    if has_slash {
2144        sys_execve(file, argv, envp);
2145        _exit(127);
2146    }
2147    let path = getenv(b"PATH\0".as_ptr() as *const c_char);
2148    let default_path = b"/usr/local/bin:/usr/bin:/bin\0";
2149    let p = if path.is_null() { default_path.as_ptr() } else { path as *const u8 };
2150    let plen = strlen(p as *const c_char);
2151    let mut buf = [0u8; PATH_MAX_V];
2152    let mut i: usize = 0;
2153    while i <= plen {
2154        let start = i;
2155        while i < plen && *p.add(i) != b':' { i += 1; }
2156        let dlen = i - start;
2157        if dlen > 0 && dlen + 1 + flen < PATH_MAX_V {
2158            core::ptr::copy_nonoverlapping(p.add(start), buf.as_mut_ptr(), dlen);
2159            *buf.as_mut_ptr().add(dlen) = b'/';
2160            core::ptr::copy_nonoverlapping(f, buf.as_mut_ptr().add(dlen + 1), flen + 1);
2161            sys_execve(buf.as_ptr() as *const c_char, argv, envp);
2162            // execve failed, try next
2163        }
2164        i += 1; // skip ':'
2165    }
2166    _exit(127);
2167}
2168
2169#[no_mangle]
2170pub unsafe extern "C" fn posix_spawnp(
2171    pid: *mut c_int,
2172    file: *const c_char,
2173    fa: *const posix_spawn_file_actions_t,
2174    attrp: *const posix_spawnattr_t,
2175    argv: *const *const c_char,
2176    envp: *const *const c_char,
2177) -> c_int {
2178    let child = sys_fork();
2179    if child < 0 {
2180        ERRNO!() = (-child) as c_int;
2181        return -1;
2182    }
2183    if child == 0 {
2184        // child: apply attributes and file actions, then exec
2185        spawn_apply_attr(attrp);
2186        spawn_apply_actions(fa);
2187        let actual_envp = if envp.is_null() { __environ as *const *const c_char } else { envp };
2188        spawn_execvp(file, argv, actual_envp);
2189    }
2190    *pid = child as c_int;
2191    0
2192}
2193
2194#[no_mangle]
2195pub unsafe extern "C" fn posix_spawn(
2196    pid: *mut c_int,
2197    path: *const c_char,
2198    fa: *const posix_spawn_file_actions_t,
2199    attrp: *const posix_spawnattr_t,
2200    argv: *const *const c_char,
2201    envp: *const *const c_char,
2202) -> c_int {
2203    // posix_spawnp() skips PATH search when the path contains '/', so it is
2204    // also the correct implementation of posix_spawn().
2205    posix_spawnp(pid, path, fa, attrp, argv, envp)
2206}
2207
2208// ============================================================
2209// sys/stat.h: stat / fstat / utimensat / futimens
2210// ============================================================
2211
2212#[cfg(target_arch = "x86_64")]
2213#[repr(C)]
2214pub struct Stat {
2215    pub st_dev: u64,
2216    pub st_ino: u64,
2217    pub st_nlink: u64,
2218    pub st_mode: u32,
2219    pub st_uid: u32,
2220    pub st_gid: u32,
2221    _pad0: u32,
2222    pub st_rdev: u64,
2223    pub st_size: i64,
2224    pub st_blksize: i64,
2225    pub st_blocks: i64,
2226    pub st_atim: timespec,
2227    pub st_mtim: timespec,
2228    pub st_ctim: timespec,
2229    _unused: [i64; 3],
2230}
2231
2232#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
2233#[repr(C)]
2234pub struct Stat {
2235    pub st_dev: u64,
2236    pub st_ino: u64,
2237    pub st_mode: u32,
2238    pub st_nlink: u32,
2239    pub st_uid: u32,
2240    pub st_gid: u32,
2241    pub st_rdev: u64,
2242    __pad1: u64,
2243    pub st_size: i64,
2244    pub st_blksize: i32,
2245    __pad2: i32,
2246    pub st_blocks: i64,
2247    pub st_atim: timespec,
2248    pub st_mtim: timespec,
2249    pub st_ctim: timespec,
2250    __unused4: u32,
2251    __unused5: u32,
2252}
2253
2254pub const S_IFMT: u32 = 0o170000;
2255pub const S_IFDIR: u32 = 0o040000;
2256pub const S_IFCHR: u32 = 0o020000;
2257pub const S_IFBLK: u32 = 0o060000;
2258pub const S_IFREG: u32 = 0o100000;
2259pub const S_IFLNK: u32 = 0o120000;
2260pub const S_IFIFO: u32 = 0o010000;
2261pub const S_IFSOCK: u32 = 0o140000;
2262
2263pub const AT_FDCWD: i32 = -100;
2264
2265const AT_SYMLINK_NOFOLLOW: c_int = 0x100;
2266const AT_EACCESS: c_int = 0x200;
2267const AT_REMOVEDIR: c_int = 0x200;
2268
2269#[no_mangle]
2270pub unsafe extern "C" fn stat(path: *const c_char, buf: *mut Stat) -> c_int {
2271    let r = sys_newfstatat(AT_FDCWD, path, buf as *mut u8, 0);
2272    syscall_ret(r) as c_int
2273}
2274
2275#[no_mangle]
2276pub unsafe extern "C" fn fstat(fd: c_int, buf: *mut Stat) -> c_int {
2277    let r = sys_fstat(fd, buf as *mut u8);
2278    syscall_ret(r) as c_int
2279}
2280
2281// ============================================================
2282// sys/resource.h: getrlimit / setrlimit
2283// ============================================================
2284
2285#[repr(C)]
2286pub struct Rlimit {
2287    pub rlim_cur: u64,
2288    pub rlim_max: u64,
2289}
2290
2291pub const RLIMIT_NOFILE: c_int = 7;
2292pub const RLIMIT_STACK: c_int = 3;
2293pub const RLIMIT_DATA: c_int = 2;
2294pub const RLIMIT_AS: c_int = 9;
2295pub const RLIMIT_CPU: c_int = 0;
2296pub const RLIMIT_FSIZE: c_int = 1;
2297pub const RLIMIT_CORE: c_int = 4;
2298pub const RLIMIT_RSS: c_int = 5;
2299pub const RLIMIT_NPROC: c_int = 6;
2300pub const RLIMIT_MEMLOCK: c_int = 8;
2301pub const RLIMIT_LOCKS: c_int = 10;
2302pub const RLIMIT_SIGPENDING: c_int = 11;
2303pub const RLIMIT_MSGQUEUE: c_int = 12;
2304pub const RLIMIT_NICE: c_int = 13;
2305pub const RLIMIT_RTPRIO: c_int = 14;
2306pub const RLIMIT_RTTIME: c_int = 15;
2307pub const RLIM_INFINITY: u64 = !0u64;
2308
2309#[no_mangle]
2310pub unsafe extern "C" fn getrlimit(resource: c_int, rlim: *mut Rlimit) -> c_int {
2311    let r = sys_getrlimit(resource, rlim as *mut u8);
2312    syscall_ret(r) as c_int
2313}
2314
2315#[no_mangle]
2316pub unsafe extern "C" fn setrlimit(resource: c_int, rlim: *const Rlimit) -> c_int {
2317    let r = sys_setrlimit(resource, rlim as *const u8);
2318    syscall_ret(r) as c_int
2319}
2320
2321// ============================================================
2322// utimensat / futimens
2323// ============================================================
2324
2325#[no_mangle]
2326pub unsafe extern "C" fn utimensat(dirfd: c_int, path: *const c_char, times: *const timespec, flags: c_int) -> c_int {
2327    let r = sys_utimensat(dirfd, path, times as *const u8, flags);
2328    syscall_ret(r) as c_int
2329}
2330
2331#[no_mangle]
2332pub unsafe extern "C" fn futimens(fd: c_int, times: *const timespec) -> c_int {
2333    let r = sys_utimensat(fd, core::ptr::null(), times as *const u8, 0);
2334    syscall_ret(r) as c_int
2335}
2336
2337// ============================================================
2338// sys/socket.h
2339// ============================================================
2340
2341pub const AF_UNIX: c_int = 1;
2342pub const AF_INET: c_int = 2;
2343pub const AF_INET6: c_int = 10;
2344
2345pub const SOCK_STREAM: c_int = 1;
2346pub const SOCK_DGRAM: c_int = 2;
2347
2348pub const SHUT_RD: c_int = 0;
2349pub const SHUT_WR: c_int = 1;
2350pub const SHUT_RDWR: c_int = 2;
2351
2352pub const SOL_SOCKET: c_int = 1;
2353pub const SO_REUSEADDR: c_int = 2;
2354
2355#[repr(C)]
2356pub struct sockaddr {
2357    pub sa_family: u16,
2358    pub sa_data: [u8; 14],
2359}
2360
2361#[inline]
2362unsafe fn sys_socket(domain: c_int, ty: c_int, protocol: c_int) -> i64 {
2363    <Arch as Syscalls>::syscall3(SYS_SOCKET, domain as i64, ty as i64, protocol as i64)
2364}
2365
2366#[inline]
2367unsafe fn sys_socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_int) -> i64 {
2368    <Arch as Syscalls>::syscall4(SYS_SOCKETPAIR, domain as i64, ty as i64, protocol as i64, sv as i64)
2369}
2370
2371#[inline]
2372unsafe fn sys_bind(fd: c_int, addr: *const sockaddr, len: c_uint) -> i64 {
2373    <Arch as Syscalls>::syscall3(SYS_BIND, fd as i64, addr as i64, len as i64)
2374}
2375
2376#[inline]
2377unsafe fn sys_listen(fd: c_int, backlog: c_int) -> i64 {
2378    <Arch as Syscalls>::syscall2(SYS_LISTEN, fd as i64, backlog as i64)
2379}
2380
2381#[inline]
2382unsafe fn sys_accept(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> i64 {
2383    <Arch as Syscalls>::syscall3(SYS_ACCEPT, fd as i64, addr as i64, len as i64)
2384}
2385
2386#[inline]
2387unsafe fn sys_connect(fd: c_int, addr: *const sockaddr, len: c_uint) -> i64 {
2388    <Arch as Syscalls>::syscall3(SYS_CONNECT, fd as i64, addr as i64, len as i64)
2389}
2390
2391#[inline]
2392unsafe fn sys_sendto(fd: c_int,
2393    buf: *const c_void,
2394    len: usize,
2395    flags: c_int,
2396    addr: *const sockaddr,
2397    addrlen: c_uint,) -> i64 {
2398    <Arch as Syscalls>::syscall6(SYS_SENDTO, fd as i64, buf as i64, len as i64, flags as i64, addr as i64, addrlen as i64)
2399}
2400
2401#[inline]
2402unsafe fn sys_recvfrom(fd: c_int,
2403    buf: *mut c_void,
2404    len: usize,
2405    flags: c_int,
2406    addr: *mut sockaddr,
2407    addrlen: *mut c_uint,) -> i64 {
2408    <Arch as Syscalls>::syscall6(SYS_RECVFROM, fd as i64, buf as i64, len as i64, flags as i64, addr as i64, addrlen as i64)
2409}
2410
2411#[inline]
2412unsafe fn sys_shutdown(fd: c_int, how: c_int) -> i64 {
2413    <Arch as Syscalls>::syscall2(SYS_SHUTDOWN, fd as i64, how as i64)
2414}
2415
2416#[inline]
2417unsafe fn sys_setsockopt(fd: c_int,
2418    level: c_int,
2419    optname: c_int,
2420    optval: *const c_void,
2421    optlen: c_uint,) -> i64 {
2422    <Arch as Syscalls>::syscall5(SYS_SETSOCKOPT, fd as i64, level as i64, optname as i64, optval as i64, optlen as i64)
2423}
2424
2425#[inline]
2426unsafe fn sys_getsockname(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> i64 {
2427    <Arch as Syscalls>::syscall3(SYS_GETSOCKNAME, fd as i64, addr as i64, len as i64)
2428}
2429
2430#[no_mangle]
2431pub unsafe extern "C" fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int {
2432    let r = sys_socket(domain, ty, protocol);
2433    syscall_ret(r) as c_int
2434}
2435
2436#[no_mangle]
2437pub unsafe extern "C" fn socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_int) -> c_int {
2438    let r = sys_socketpair(domain, ty, protocol, sv);
2439    syscall_ret(r) as c_int
2440}
2441
2442#[no_mangle]
2443pub unsafe extern "C" fn bind(fd: c_int, addr: *const sockaddr, len: c_uint) -> c_int {
2444    let r = sys_bind(fd, addr, len);
2445    syscall_ret(r) as c_int
2446}
2447
2448#[no_mangle]
2449pub unsafe extern "C" fn listen(fd: c_int, backlog: c_int) -> c_int {
2450    let r = sys_listen(fd, backlog);
2451    syscall_ret(r) as c_int
2452}
2453
2454#[no_mangle]
2455pub unsafe extern "C" fn accept(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> c_int {
2456    let r = sys_accept(fd, addr, len);
2457    syscall_ret(r) as c_int
2458}
2459
2460#[no_mangle]
2461pub unsafe extern "C" fn connect(fd: c_int, addr: *const sockaddr, len: c_uint) -> c_int {
2462    let r = sys_connect(fd, addr, len);
2463    syscall_ret(r) as c_int
2464}
2465
2466#[no_mangle]
2467pub unsafe extern "C" fn send(fd: c_int, buf: *const c_void, len: usize, flags: c_int) -> isize {
2468    let r = sys_sendto(fd, buf, len, flags, core::ptr::null(), 0);
2469    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2470    r as isize
2471}
2472
2473#[no_mangle]
2474pub unsafe extern "C" fn recv(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize {
2475    let r = sys_recvfrom(fd, buf, len, flags, core::ptr::null_mut(), core::ptr::null_mut());
2476    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2477    r as isize
2478}
2479
2480#[no_mangle]
2481pub unsafe extern "C" fn sendto(
2482    fd: c_int,
2483    buf: *const c_void,
2484    len: usize,
2485    flags: c_int,
2486    addr: *const sockaddr,
2487    addrlen: c_uint,
2488) -> isize {
2489    let r = sys_sendto(fd, buf, len, flags, addr, addrlen);
2490    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2491    r as isize
2492}
2493
2494#[no_mangle]
2495pub unsafe extern "C" fn recvfrom(
2496    fd: c_int,
2497    buf: *mut c_void,
2498    len: usize,
2499    flags: c_int,
2500    addr: *mut sockaddr,
2501    addrlen: *mut c_uint,
2502) -> isize {
2503    let r = sys_recvfrom(fd, buf, len, flags, addr, addrlen);
2504    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
2505    r as isize
2506}
2507
2508#[no_mangle]
2509pub unsafe extern "C" fn shutdown(fd: c_int, how: c_int) -> c_int {
2510    let r = sys_shutdown(fd, how);
2511    syscall_ret(r) as c_int
2512}
2513
2514#[no_mangle]
2515pub unsafe extern "C" fn setsockopt(
2516    fd: c_int,
2517    level: c_int,
2518    optname: c_int,
2519    optval: *const c_void,
2520    optlen: c_uint,
2521) -> c_int {
2522    let r = sys_setsockopt(fd, level, optname, optval, optlen);
2523    syscall_ret(r) as c_int
2524}
2525
2526#[no_mangle]
2527pub unsafe extern "C" fn getsockname(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> c_int {
2528    let r = sys_getsockname(fd, addr, len);
2529    syscall_ret(r) as c_int
2530}
2531
2532#[no_mangle]
2533pub extern "C" fn htonl(hostlong: c_uint) -> c_uint {
2534    hostlong.to_be()
2535}
2536
2537#[no_mangle]
2538pub extern "C" fn ntohl(netlong: c_uint) -> c_uint {
2539    c_uint::from_be(netlong)
2540}
2541
2542#[no_mangle]
2543pub extern "C" fn htons(hostshort: u16) -> u16 {
2544    hostshort.to_be()
2545}
2546
2547#[no_mangle]
2548pub extern "C" fn ntohs(netshort: u16) -> u16 {
2549    u16::from_be(netshort)
2550}
2551
2552pub type PthreadT = c_ulong;
2553
2554// pthread_attr_t: musl 64-bit layout (56 bytes = int[14])
2555#[repr(C)]
2556pub struct pthread_attr_t {
2557    __i: [c_int; 14],
2558}
2559
2560// pthread_mutex_t: musl 64-bit layout (40 bytes = int[10])
2561// _m_type=__i[0], _m_lock=__i[1], _m_waiters=__i[2], _m_count=__i[5]
2562#[repr(C)]
2563pub struct pthread_mutex_t {
2564    __i: [c_int; 10],
2565}
2566
2567#[repr(C)]
2568pub struct pthread_mutexattr_t {
2569    __attr: c_uint,
2570}
2571
2572// pthread_cond_t: musl 64-bit layout (48 bytes = int[12])
2573// _c_seq=__i[2], _c_waiters=__i[3], _c_clock=__i[4]
2574#[repr(C)]
2575pub struct pthread_cond_t {
2576    __i: [c_int; 12],
2577}
2578
2579#[repr(C)]
2580pub struct pthread_condattr_t {
2581    __attr: c_uint,
2582}
2583
2584// pthread_rwlock_t: musl 64-bit layout (56 bytes = int[14])
2585// _rw_lock=__i[0], _rw_waiters=__i[1], _rw_shared=__i[2]
2586#[repr(C)]
2587pub struct pthread_rwlock_t {
2588    __i: [c_int; 14],
2589}
2590
2591#[repr(C)]
2592pub struct pthread_rwlockattr_t {
2593    __attr: [c_uint; 2],
2594}
2595
2596// pthread_barrier_t: musl 64-bit layout (32 bytes = int[8])
2597#[repr(C)]
2598pub struct pthread_barrier_t {
2599    __i: [c_int; 8],
2600}
2601
2602#[repr(C)]
2603pub struct pthread_barrierattr_t {
2604    __attr: c_uint,
2605}
2606
2607pub type pthread_spinlock_t = c_int;
2608pub type pthread_once_t = c_int;
2609pub type pthread_key_t = c_uint;
2610
2611// sem_t: musl 64-bit layout (32 bytes = int[8])
2612#[repr(C)]
2613pub struct sem_t {
2614    __val: [c_int; 8],
2615}
2616
2617#[repr(C)]
2618pub struct sched_param {
2619    pub sched_priority: c_int,
2620}
2621
2622const CLONE_VM: c_ulong = 0x00000100;
2623const CLONE_FS: c_ulong = 0x00000200;
2624const CLONE_FILES: c_ulong = 0x00000400;
2625const CLONE_SIGHAND: c_ulong = 0x00000800;
2626const CLONE_THREAD: c_ulong = 0x00010000;
2627const CLONE_SYSVSEM: c_ulong = 0x00040000;
2628const CLONE_SETTLS: c_ulong = 0x00080000;
2629const CLONE_PARENT_SETTID: c_ulong = 0x00100000;
2630const CLONE_CHILD_CLEARTID: c_ulong = 0x00200000;
2631
2632const FUTEX_WAIT: c_int = 0;
2633const FUTEX_WAKE: c_int = 1;
2634const FUTEX_LOCK_PI: c_int = 6;
2635const FUTEX_UNLOCK_PI: c_int = 7;
2636const FUTEX_TRYLOCK_PI: c_int = 8;
2637
2638// SIGCANCEL (32) is musl's internal cancel signal
2639const SIGCANCEL: c_int = 32;
2640
2641const PTHREAD_MUTEX_NORMAL: c_int = 0;
2642const PTHREAD_MUTEX_DEFAULT: c_int = 0;
2643const PTHREAD_MUTEX_RECURSIVE: c_int = 1;
2644const PTHREAD_MUTEX_ERRORCHECK: c_int = 2;
2645
2646const PTHREAD_CREATE_JOINABLE: c_int = 0;
2647const PTHREAD_CREATE_DETACHED: c_int = 1;
2648
2649const PTHREAD_CANCEL_ENABLE: c_int = 0;
2650const PTHREAD_CANCEL_DISABLE: c_int = 1;
2651const PTHREAD_CANCEL_DEFERRED: c_int = 0;
2652const PTHREAD_CANCEL_ASYNCHRONOUS: c_int = 1;
2653
2654const PTHREAD_SCOPE_SYSTEM: c_int = 0;
2655const PTHREAD_PROCESS_PRIVATE: c_int = 0;
2656const PTHREAD_PROCESS_SHARED: c_int = 1;
2657const PTHREAD_INHERIT_SCHED: c_int = 0;
2658const PTHREAD_EXPLICIT_SCHED: c_int = 1;
2659
2660const PTHREAD_BARRIER_SERIAL_THREAD: c_int = -1;
2661
2662const PTHREAD_KEYS_MAX: usize = 128;
2663const PTHREAD_DESTRUCTOR_ITERATIONS: usize = 4;
2664const SEM_VALUE_MAX: c_int = 0x7fffffff;
2665
2666const DT_EXITED: c_int = 0;
2667const DT_EXITING: c_int = 1;
2668const DT_JOINABLE: c_int = 2;
2669const DT_DETACHED: c_int = 3;
2670
2671// musl __ptcb cleanup handler node
2672#[repr(C)]
2673#[derive(Copy, Clone)]
2674pub struct __ptcb {
2675    __f: Option<unsafe extern "C" fn(*mut c_void)>,
2676    __x: *mut c_void,
2677    __next: *mut __ptcb,
2678}
2679
2680// robust_list_head for kernel robust mutex support
2681#[repr(C)]
2682#[derive(Copy, Clone)]
2683struct robust_list {
2684    next: *mut robust_list,
2685}
2686
2687#[repr(C)]
2688#[derive(Copy, Clone)]
2689struct robust_list_head {
2690    list: robust_list,
2691    futex_offset: c_long,
2692    pending: *mut robust_list,
2693}
2694
2695// Adapted from musl's x86_64 clone.s.
2696#[cfg(all(target_arch = "x86_64", not(test)))]
2697core::arch::global_asm!(
2698    ".global __keel_clone",
2699    ".type __keel_clone, @function",
2700    "__keel_clone:",
2701    "mov rax, rdi",
2702    "mov rdi, rdx",
2703    "mov rdx, r8",
2704    "mov r10, [rsp + 8]",
2705    "mov r8, r9",
2706    "mov r9, rax",
2707    "and rsi, -16",
2708    "sub rsi, 8",
2709    "mov [rsi], rcx",
2710    "mov eax, 56",
2711    "syscall",
2712    "test rax, rax",
2713    "jnz 1f",
2714    "pop rdi",
2715    "call r9",
2716    // A clone() child that returns from its function must exit with that
2717    // value (musl does the same); falling through to hlt raises SIGSEGV.
2718    "mov edi, eax",
2719    "mov eax, 60",
2720    "syscall",
2721    "hlt",
2722    "1:",
2723    "ret",
2724);
2725
2726// Adapted from musl's aarch64 clone.s.
2727#[no_mangle]
2728#[unsafe(naked)]
2729#[cfg(target_arch = "aarch64")]
2730pub unsafe extern "C" fn __keel_clone(
2731    fn_: usize,
2732    stack: *mut u8,
2733    flags: c_ulong,
2734    arg: *mut c_void,
2735    ptid: *mut c_int,
2736    tls: c_ulong,
2737    ctid: *mut c_int,
2738) -> i64 {
2739    core::arch::naked_asm!(
2740        "and x1, x1, #-16",
2741        "stp x0, x3, [x1, #-16]!",
2742        "uxtw x0, w2",
2743        "mov x2, x4",
2744        "mov x3, x5",
2745        "mov x4, x6",
2746        "mov x8, #220",
2747        "svc #0",
2748        "cbz x0, 1f",
2749        "ret",
2750        "1:",
2751        "mov x29, #0",
2752        "ldp x1, x0, [sp], #16",
2753        "blr x1",
2754        "mov x8, #93",
2755        "svc #0",
2756    );
2757}
2758
2759#[no_mangle]
2760#[unsafe(naked)]
2761#[cfg(target_arch = "riscv64")]
2762pub unsafe extern "C" fn __keel_clone(
2763    fn_: usize,
2764    stack: *mut u8,
2765    flags: c_ulong,
2766    arg: *mut c_void,
2767    ptid: *mut c_int,
2768    tls: c_ulong,
2769    ctid: *mut c_int,
2770) -> i64 {
2771    core::arch::naked_asm!(
2772        "andi a1, a1, -16",
2773        "addi a1, a1, -16",
2774        "sd a0, 0(a1)",
2775        "sd a3, 8(a1)",
2776        "mv a0, a2",
2777        "mv a2, a4",
2778        "mv a3, a5",
2779        "mv a4, a6",
2780        "li a7, 220",
2781        "ecall",
2782        "beqz a0, 1f",
2783        "ret",
2784        "1:",
2785        "ld a1, 0(sp)",
2786        "ld a0, 8(sp)",
2787        "jalr a1",
2788        "li a7, 93",
2789        "ecall",
2790    );
2791}
2792
2793#[cfg(all(target_arch = "x86_64", test))]
2794#[inline(never)]
2795unsafe fn __keel_clone(
2796    _fn_: usize,
2797    _stack: *mut u8,
2798    _flags: c_ulong,
2799    _arg: *mut c_void,
2800    _ptid: *mut c_int,
2801    _tls: c_ulong,
2802    _ctid: *mut c_int,
2803) -> i64 {
2804    -1
2805}
2806
2807#[cfg(all(target_arch = "x86_64", not(test)))]
2808extern "C" {
2809    fn __keel_clone(
2810        fn_: usize,
2811        stack: *mut u8,
2812        flags: c_ulong,
2813        arg: *mut c_void,
2814        ptid: *mut c_int,
2815        tls: c_ulong,
2816        ctid: *mut c_int,
2817    ) -> i64;
2818}
2819
2820#[derive(Copy, Clone)]
2821struct TlsHooks {
2822    create: unsafe extern "C" fn() -> *mut u8,
2823    init: unsafe extern "C" fn(*mut u8) -> *mut u8,
2824    block_size: extern "C" fn() -> usize,
2825    base_offset: extern "C" fn() -> usize,
2826}
2827
2828// Installed by the dynamic loader before any thread is created. A static
2829// executable leaves this as None and uses the weak fallbacks.
2830static mut TLS_HOOKS: Option<TlsHooks> = None;
2831
2832/// Called by the dynamic loader once it is self-relocated.  A static
2833/// executable does not call this and keeps the fallback behaviour.
2834#[no_mangle]
2835pub unsafe extern "C" fn __keel_set_thread_tls_hooks(
2836    create: usize,
2837    init: usize,
2838    block_size: usize,
2839    base_offset: usize,
2840) {
2841    TLS_HOOKS = Some(TlsHooks {
2842        create: core::mem::transmute(create),
2843        init: core::mem::transmute(init),
2844        block_size: core::mem::transmute(block_size),
2845        base_offset: core::mem::transmute(base_offset),
2846    });
2847}
2848
2849#[inline(never)]
2850#[no_mangle]
2851pub extern "C" fn __keel_create_thread_tls() -> *mut u8 {
2852    match unsafe { TLS_HOOKS } {
2853        Some(hooks) => unsafe { (hooks.create)() },
2854        None => core::ptr::null_mut(),
2855    }
2856}
2857
2858#[inline(never)]
2859#[no_mangle]
2860pub unsafe extern "C" fn __keel_init_thread_tls_at(block: *mut u8) -> *mut u8 {
2861    match TLS_HOOKS {
2862        Some(hooks) => (hooks.init)(block),
2863        None => core::ptr::null_mut(),
2864    }
2865}
2866
2867#[inline(never)]
2868#[no_mangle]
2869pub extern "C" fn __keel_tls_block_size() -> usize {
2870    match unsafe { TLS_HOOKS } {
2871        Some(hooks) => (hooks.block_size)(),
2872        None => 0,
2873    }
2874}
2875
2876#[inline(never)]
2877#[no_mangle]
2878pub extern "C" fn __keel_tls_base_offset() -> usize {
2879    match unsafe { TLS_HOOKS } {
2880        Some(hooks) => (hooks.base_offset)(),
2881        None => 0,
2882    }
2883}
2884
2885#[inline]
2886unsafe fn sys_gettid() -> i64 {
2887    <Arch as Syscalls>::syscall0(SYS_GETTID)
2888}
2889
2890#[inline]
2891unsafe fn sys_futex(uaddr: *mut c_int,
2892    futex_op: c_int,
2893    val: c_int,
2894    timeout: *mut c_void,
2895    uaddr2: *mut c_int,
2896    val3: c_int,) -> i64 {
2897    <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)
2898}
2899
2900const THREAD_CHUNK: usize = 1024;
2901const STACK_SIZE: usize = 1024 * 1024;
2902// Per-thread pointer to its Thread record.  The TCB has room after errno
2903// (0x30), the vDSO getrandom state (0x38), and this pointer (0x40).
2904const THREAD_TCB_OFFSET: usize = 0x40;
2905
2906#[repr(C)]
2907#[derive(Copy, Clone)]
2908struct Thread {
2909    tid: c_int,
2910    detach_state: c_int,
2911    result: *mut c_void,
2912    cancel: c_int,
2913    cancel_state: c_int,
2914    cancel_type: c_int,
2915    user_fn: usize,
2916    user_arg: *mut c_void,
2917    stack: *mut u8,
2918    stack_size: usize,
2919    stack_owned: bool,
2920    fs_base: *mut u8,
2921    // TLS block as allocated at creation. The global TLS size can grow when
2922    // a DSO is dlopen'ed, so it must not be used to free an older thread's
2923    // block: the address and length would be wrong and could unmap a
2924    // neighbouring thread stack.
2925    tls_base: *mut u8,
2926    tls_size: usize,
2927    tsd: [*mut c_void; PTHREAD_KEYS_MAX],
2928    cancelbuf: *mut __ptcb,
2929    robust_list: robust_list_head,
2930    free_next: *mut Thread,
2931}
2932
2933static mut THREADS: [Thread; THREAD_CHUNK] = [Thread {
2934    tid: -1,
2935    detach_state: DT_JOINABLE,
2936    result: core::ptr::null_mut(),
2937    cancel: 0,
2938    cancel_state: PTHREAD_CANCEL_ENABLE,
2939    cancel_type: PTHREAD_CANCEL_DEFERRED,
2940    user_fn: 0,
2941    user_arg: core::ptr::null_mut(),
2942    stack: core::ptr::null_mut(),
2943    stack_size: 0,
2944    stack_owned: false,
2945    fs_base: core::ptr::null_mut(),
2946    tls_base: core::ptr::null_mut(),
2947    tls_size: 0,
2948    tsd: [core::ptr::null_mut(); PTHREAD_KEYS_MAX],
2949    cancelbuf: core::ptr::null_mut(),
2950    robust_list: robust_list_head {
2951        list: robust_list { next: core::ptr::null_mut() },
2952        futex_offset: 0,
2953        pending: core::ptr::null_mut(),
2954    },
2955    free_next: core::ptr::null_mut(),
2956}; THREAD_CHUNK];
2957#[repr(C)]
2958struct ThreadChunk {
2959    next: *mut ThreadChunk,
2960    base: *mut Thread,
2961}
2962static THREAD_CHUNK_LIST: AtomicPtr<ThreadChunk> =
2963    AtomicPtr::new(core::ptr::null_mut());
2964static EXTRA_CHUNK_COUNT: AtomicUsize = AtomicUsize::new(0);
2965// Free list of thread slots, protected by THREAD_LOCK.  Slots are never
2966// moved, so pthread_t values stay valid for the life of a thread.
2967static mut FREE_THREADS: *mut Thread = core::ptr::null_mut();
2968static mut THREAD_TABLE_READY: bool = false;
2969static mut THREAD_LOCK: c_int = 0;
2970static mut THREAD_WAITERS: c_int = 0;
2971static ACTIVE_THREADS: AtomicUsize = AtomicUsize::new(0);
2972static mut KEY_DTORS: [Option<unsafe extern "C" fn(*mut c_void)>; PTHREAD_KEYS_MAX] = [None; PTHREAD_KEYS_MAX];
2973static NEXT_KEY: AtomicUsize = AtomicUsize::new(0);
2974
2975// futex helpers
2976unsafe fn futex_wait(addr: *mut c_int, expected: c_int) -> c_int {
2977    let r = sys_futex(addr, FUTEX_WAIT, expected, null_mut(), null_mut(), 0);
2978    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
2979}
2980
2981unsafe fn futex_wake(addr: *mut c_int, count: c_int) {
2982    let c = if count < 0 { c_int::MAX } else { count };
2983    sys_futex(addr, FUTEX_WAKE, c, null_mut(), null_mut(), 0);
2984}
2985
2986unsafe fn futex_lock_pi(addr: *mut c_int, abs_timeout: *const timespec) -> c_int {
2987    let timeout_ptr = if abs_timeout.is_null() { null_mut() } else { abs_timeout as *mut c_void };
2988    let r = sys_futex(addr, FUTEX_LOCK_PI, 0, timeout_ptr, null_mut(), 0);
2989    if r < 0 { (-r) as c_int } else { 0 }
2990}
2991
2992unsafe fn futex_unlock_pi(addr: *mut c_int) -> c_int {
2993    let r = sys_futex(addr, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
2994    if r < 0 { (-r) as c_int } else { 0 }
2995}
2996
2997#[inline]
2998unsafe fn sys_set_robust_list(head: *mut robust_list_head, len: usize) -> i64 {
2999    <Arch as Syscalls>::syscall2(SYS_SET_ROBUST_LIST, head as i64, len as i64)
3000}
3001
3002unsafe fn futex_timedwait(addr: *mut c_int, expected: c_int, abs_timeout: *const timespec) -> c_int {
3003    if abs_timeout.is_null() { return futex_wait(addr, expected); }
3004    let mut now: timespec = core::mem::zeroed();
3005    if sys_clock_gettime(CLOCK_REALTIME, &mut now) < 0 { return EINVAL; }
3006    let mut rel: timespec = core::mem::zeroed();
3007    rel.tv_sec = (*abs_timeout).tv_sec - now.tv_sec;
3008    rel.tv_nsec = (*abs_timeout).tv_nsec - now.tv_nsec;
3009    if rel.tv_nsec < 0 { rel.tv_sec -= 1; rel.tv_nsec += 1_000_000_000; }
3010    if rel.tv_sec < 0 { return ETIMEDOUT; }
3011    let r = sys_futex(addr, FUTEX_WAIT, expected, &mut rel as *mut timespec as *mut c_void, null_mut(), 0);
3012    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
3013}
3014
3015// atomic helpers wrapping AtomicI32
3016unsafe fn a_cas(addr: *mut c_int, expected: c_int, desired: c_int) -> c_int {
3017    let a = &*(addr as *const AtomicI32);
3018    match a.compare_exchange(expected, desired, Ordering::AcqRel, Ordering::Acquire) {
3019        Ok(v) | Err(v) => v,
3020    }
3021}
3022
3023unsafe fn a_store(addr: *mut c_int, val: c_int) {
3024    (*(addr as *const AtomicI32)).store(val, Ordering::Release);
3025}
3026
3027unsafe fn a_load(addr: *const c_int) -> c_int {
3028    (*(addr as *const AtomicI32)).load(Ordering::Acquire)
3029}
3030
3031unsafe fn a_swap(addr: *mut c_int, val: c_int) -> c_int {
3032    (*(addr as *const AtomicI32)).swap(val, Ordering::AcqRel)
3033}
3034
3035unsafe fn a_fetch_add(addr: *mut c_int, val: c_int) -> c_int {
3036    (*(addr as *const AtomicI32)).fetch_add(val, Ordering::AcqRel)
3037}
3038
3039unsafe fn a_fetch_sub(addr: *mut c_int, val: c_int) -> c_int {
3040    (*(addr as *const AtomicI32)).fetch_sub(val, Ordering::AcqRel)
3041}
3042
3043unsafe fn spinlock_lock(lock: *mut c_int, waiters: *mut c_int) {
3044    while a_swap(lock, 1) != 0 {
3045        let mut spins = 100;
3046        while spins > 0 && a_load(lock) != 0 { core::hint::spin_loop(); spins -= 1; }
3047        if a_load(lock) == 0 { continue; }
3048        a_fetch_add(waiters, 1);
3049        futex_wait(lock, 1);
3050        a_fetch_sub(waiters, 1);
3051    }
3052}
3053
3054unsafe fn spinlock_unlock(lock: *mut c_int, waiters: *mut c_int) {
3055    a_store(lock, 0);
3056    if a_load(waiters) > 0 { futex_wake(lock, 1); }
3057}
3058
3059unsafe fn thread_slot_count() -> usize {
3060    THREAD_CHUNK + EXTRA_CHUNK_COUNT.load(Ordering::Acquire) * THREAD_CHUNK
3061}
3062
3063unsafe fn thread_slot_at(index: usize) -> *mut Thread {
3064    if index < THREAD_CHUNK {
3065        core::ptr::addr_of_mut!(THREADS[index])
3066    } else {
3067        let extra = index - THREAD_CHUNK;
3068        let chunk_index = extra / THREAD_CHUNK;
3069        let offset = extra % THREAD_CHUNK;
3070        let mut chunk = THREAD_CHUNK_LIST.load(Ordering::Acquire);
3071        let mut i = 0usize;
3072        while i < chunk_index && !chunk.is_null() {
3073            chunk = (*chunk).next;
3074            i += 1;
3075        }
3076        if chunk.is_null() {
3077            return core::ptr::null_mut();
3078        }
3079        (*chunk).base.add(offset)
3080    }
3081}
3082
3083unsafe fn release_thread_slot(slot: *const Thread) {
3084    let slot = slot as *mut Thread;
3085    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3086    (*slot).tid = -1;
3087    (*slot).free_next = FREE_THREADS;
3088    FREE_THREADS = slot;
3089    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3090}
3091
3092/// Link slots `start..THREAD_CHUNK` of `base` into the free list.  Caller
3093/// holds THREAD_LOCK.
3094unsafe fn push_free_slots(base: *mut Thread, start: usize) {
3095    let mut i = THREAD_CHUNK;
3096    while i > start {
3097        i -= 1;
3098        let slot = base.add(i);
3099        (*slot).free_next = FREE_THREADS;
3100        FREE_THREADS = slot;
3101    }
3102}
3103
3104unsafe fn alloc_thread_slot() -> Option<&'static mut Thread> {
3105    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3106    if !THREAD_TABLE_READY {
3107        // Slot 0 is reserved for the process's initial thread.  Registering
3108        // it must not require touching the rest of the table.
3109        push_free_slots(core::ptr::addr_of_mut!(THREADS[0]), 1);
3110        THREAD_TABLE_READY = true;
3111    }
3112    let mut slot = FREE_THREADS;
3113    if slot.is_null() {
3114        let bytes = core::mem::size_of::<ThreadChunk>()
3115            + THREAD_CHUNK * core::mem::size_of::<Thread>();
3116        let raw = sys_mmap(
3117            core::ptr::null_mut(),
3118            bytes,
3119            PROT_READ | PROT_WRITE,
3120            MAP_PRIVATE | MAP_ANONYMOUS,
3121            -1,
3122            0,
3123        ) as *mut u8;
3124        if raw.is_null() || raw == MMAP_FAILED {
3125            spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3126            return None;
3127        }
3128        let header = raw as *mut ThreadChunk;
3129        let base = raw.add(core::mem::size_of::<ThreadChunk>()) as *mut Thread;
3130        (*header).base = base;
3131        push_free_slots(base, 1);
3132        (*header).next = THREAD_CHUNK_LIST.load(Ordering::Relaxed);
3133        THREAD_CHUNK_LIST.store(header, Ordering::Release);
3134        EXTRA_CHUNK_COUNT.fetch_add(1, Ordering::AcqRel);
3135        slot = base;
3136    } else {
3137        FREE_THREADS = (*slot).free_next;
3138        (*slot).free_next = core::ptr::null_mut();
3139    }
3140    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
3141    Some(&mut *slot)
3142}
3143
3144/// The child of fork() keeps only the calling thread.  Rebuild the free list
3145/// so slots belonging to vanished threads are reusable, and update the
3146/// current thread's tid to the child's.
3147unsafe fn thread_allocator_after_fork() {
3148    a_store(&raw mut THREAD_LOCK, 0);
3149    a_store(&raw mut THREAD_WAITERS, 0);
3150    let tp = tcb_slot(THREAD_TCB_OFFSET);
3151    let current = if tp.is_null() {
3152        core::ptr::null_mut()
3153    } else {
3154        core::ptr::read_unaligned(tp) as *mut Thread
3155    };
3156    let child_tid = sys_gettid() as c_int;
3157    if !THREAD_TABLE_READY {
3158        // The initial thread is registered directly in slot 0, so the free
3159        // list may never have been built.  Only update that one slot; the
3160        // first pthread_create() will build the free list.
3161        if !current.is_null() {
3162            (*current).tid = child_tid;
3163            ACTIVE_THREADS.store(1, Ordering::Release);
3164        }
3165        return;
3166    }
3167    let count = thread_slot_count();
3168    let mut free = core::ptr::null_mut();
3169    let mut active = 0usize;
3170    let mut i = 0usize;
3171    while i < count {
3172        let slot = thread_slot_at(i);
3173        if slot == current {
3174            (*slot).tid = child_tid;
3175            (*slot).free_next = core::ptr::null_mut();
3176            active += 1;
3177        } else {
3178            (*slot).tid = -1;
3179            (*slot).free_next = free;
3180            free = slot;
3181        }
3182        i += 1;
3183    }
3184    FREE_THREADS = free;
3185    ACTIVE_THREADS.store(active, Ordering::Release);
3186}
3187
3188unsafe fn run_key_dtors(slot: &mut Thread) {
3189    for _ in 0..PTHREAD_DESTRUCTOR_ITERATIONS {
3190        let mut any = false;
3191        for i in 0..PTHREAD_KEYS_MAX {
3192            let val = slot.tsd[i];
3193            if !val.is_null() {
3194                if let Some(dtor) = KEY_DTORS[i] {
3195                    slot.tsd[i] = core::ptr::null_mut();
3196                    any = true;
3197                    dtor(val);
3198                }
3199            }
3200        }
3201        if !any { break; }
3202    }
3203}
3204
3205unsafe extern "C" fn thread_entry(slot: *mut c_void) -> *mut c_void {
3206    let slot = &mut *(slot as *mut Thread);
3207    let tp = tcb_slot(THREAD_TCB_OFFSET);
3208    if !tp.is_null() {
3209        core::ptr::write_unaligned(tp, slot as *mut Thread as usize);
3210    }
3211    // A reused slot may still carry the previous thread's robust-list state;
3212    // register a fresh list for this thread.
3213    slot.robust_list.list.next = core::ptr::null_mut();
3214    slot.robust_list.futex_offset = 0;
3215    slot.robust_list.pending = core::ptr::null_mut();
3216    ensure_robust_list(slot);
3217    let mut set: SigSetT = 0;
3218    sigemptyset(&mut set);
3219    sigaddset(&mut set, SIGCANCEL);
3220    pthread_sigmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
3221    let user_fn: unsafe extern "C" fn(*mut c_void) -> *mut c_void =
3222        core::mem::transmute::<usize, _>(slot.user_fn);
3223    let ret = user_fn(slot.user_arg);
3224    thread_finish(slot, ret)
3225}
3226
3227/// Common exit path for a thread that returned from its start routine and
3228/// for pthread_exit(): run cleanup handlers and TSD destructors, publish the
3229/// result, and give up the CPU.
3230unsafe fn thread_finish(slot: &mut Thread, retval: *mut c_void) -> ! {
3231    run_cleanup_handlers(slot);
3232    run_key_dtors(slot);
3233    vdso_getrandom_thread_exit();
3234    slot.result = retval;
3235    a_store(&raw mut slot.detach_state, DT_EXITED);
3236    futex_wake(&raw mut slot.detach_state, 1);
3237    if ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel) <= 1 {
3238        exit(0);
3239    }
3240    sys_exit_thread(0)
3241}
3242
3243unsafe fn init_thread_slot(slot: *mut Thread, me: c_int) {
3244    (*slot).tid = me;
3245    (*slot).detach_state = DT_JOINABLE;
3246    (*slot).result = core::ptr::null_mut();
3247    (*slot).cancel = 0;
3248    (*slot).cancel_state = PTHREAD_CANCEL_ENABLE;
3249    (*slot).cancel_type = PTHREAD_CANCEL_DEFERRED;
3250    (*slot).cancelbuf = core::ptr::null_mut();
3251    core::ptr::write_bytes((*slot).tsd.as_mut_ptr(), 0, PTHREAD_KEYS_MAX);
3252    (*slot).robust_list.list.next = core::ptr::null_mut();
3253    (*slot).robust_list.futex_offset = 0;
3254    (*slot).robust_list.pending = core::ptr::null_mut();
3255    (*slot).free_next = core::ptr::null_mut();
3256}
3257
3258unsafe fn register_main_thread() -> Option<&'static mut Thread> {
3259    let me = sys_gettid() as c_int;
3260    let tp = tcb_slot(THREAD_TCB_OFFSET);
3261    if !tp.is_null() {
3262        let p = core::ptr::read_unaligned(tp) as *mut Thread;
3263        if !p.is_null() && (*p).tid == me {
3264            return Some(&mut *p);
3265        }
3266    }
3267    let slot = core::ptr::addr_of_mut!(THREADS[0]);
3268    init_thread_slot(slot, me);
3269    if !tp.is_null() {
3270        core::ptr::write_unaligned(tp, slot as usize);
3271    }
3272    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3273    Some(&mut *slot)
3274}
3275
3276unsafe fn register_current_thread() -> Option<&'static mut Thread> {
3277    let me = sys_gettid() as c_int;
3278    let slot_ref = alloc_thread_slot()?;
3279    let slot = slot_ref as *mut Thread;
3280    init_thread_slot(slot, me);
3281    let tp = tcb_slot(THREAD_TCB_OFFSET);
3282    if !tp.is_null() {
3283        core::ptr::write_unaligned(tp, slot as usize);
3284    }
3285    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3286    Some(&mut *slot)
3287}
3288
3289unsafe fn find_thread() -> Option<&'static mut Thread> {
3290    let me = sys_gettid() as c_int;
3291    let tp = tcb_slot(THREAD_TCB_OFFSET);
3292    if !tp.is_null() {
3293        let p = core::ptr::read_unaligned(tp) as *mut Thread;
3294        if !p.is_null() && (*p).tid == me {
3295            return Some(&mut *p);
3296        }
3297    }
3298    let main = core::ptr::addr_of_mut!(THREADS[0]);
3299    if (*main).tid == me {
3300        if !tp.is_null() {
3301            core::ptr::write_unaligned(tp, main as usize);
3302        }
3303        return Some(&mut *main);
3304    }
3305    let count = thread_slot_count();
3306    let mut i = 0usize;
3307    while i < count {
3308        let slot = thread_slot_at(i);
3309        if core::ptr::read_volatile(&raw const (*slot).tid) == me {
3310            if !tp.is_null() {
3311                core::ptr::write_unaligned(tp, slot as usize);
3312            }
3313            return Some(&mut *slot);
3314        }
3315        i += 1;
3316    }
3317    register_current_thread()
3318}
3319
3320#[no_mangle]
3321pub unsafe extern "C" fn pthread_self() -> PthreadT {
3322    match find_thread() {
3323        Some(slot) => slot as *mut Thread as PthreadT,
3324        None => 0,
3325    }
3326}
3327
3328#[no_mangle]
3329pub unsafe extern "C" fn pthread_equal(t1: PthreadT, t2: PthreadT) -> c_int {
3330    (t1 == t2) as c_int
3331}
3332
3333unsafe fn dynamic_tls_init(block: *mut u8) -> *mut u8 {
3334    __keel_init_thread_tls_at(block)
3335}
3336
3337unsafe fn dynamic_tls_create() -> *mut u8 {
3338    __keel_create_thread_tls()
3339}
3340
3341/// Prefer carving TLS out of the top of an application-provided stack; a
3342/// separate mapping can land below a MAP_GROWSDOWN stack and block growth.
3343unsafe fn carve_thread_tls(
3344    init_at: unsafe fn(*mut u8) -> *mut u8,
3345    create: unsafe fn() -> *mut u8,
3346    user_top: *mut c_void,
3347    stack_size: usize,
3348    tls_total: usize,
3349    stack_owned: bool,
3350    stack_top: &mut *mut u8,
3351    tls_owned: &mut bool,
3352) -> *mut u8 {
3353    if !stack_owned && tls_total > 0 && stack_size > tls_total + PAGE {
3354        let block = ((user_top as usize - tls_total) & !63usize) as *mut u8;
3355        let fs = init_at(block);
3356        if !fs.is_null() {
3357            *stack_top = block;
3358            *tls_owned = false;
3359            return fs;
3360        }
3361    }
3362    create()
3363}
3364
3365#[no_mangle]
3366pub unsafe extern "C" fn pthread_create(
3367    thread: *mut PthreadT,
3368    attr: *const pthread_attr_t,
3369    start_routine: usize,
3370    arg: *mut c_void,
3371) -> c_int {
3372    if start_routine == 0 || thread.is_null() { return EINVAL; }
3373    let Some(slot_ref) = alloc_thread_slot() else { return EAGAIN; };
3374    let slot = slot_ref as *mut Thread;
3375    let stack_size = if !attr.is_null() {
3376        let s = attr_stack_size(attr);
3377        if s > 0 { s } else { STACK_SIZE }
3378    } else { STACK_SIZE };
3379    // musl stores the stack *top* in pthread_attr_t; zero means "allocate".
3380    let user_top = if !attr.is_null() {
3381        attr_stack_top(attr)
3382    } else {
3383        core::ptr::null_mut()
3384    };
3385    let stack_owned = user_top.is_null();
3386    let stack = if stack_owned {
3387        sys_mmap(null_mut(), stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
3388    } else {
3389        (user_top as *mut u8).sub(stack_size)
3390    };
3391    if stack == MMAP_FAILED { release_thread_slot(slot); return EAGAIN; }
3392    let static_mode = RC_STATIC_EXEC;
3393    let tls_total = if static_mode {
3394        STATIC_TLS_BLOCK_SIZE
3395    } else {
3396        __keel_tls_block_size()
3397    };
3398    let mut stack_top = stack.add(stack_size);
3399    let mut tls_owned = true;
3400    let fs_base = if static_mode {
3401        carve_thread_tls(
3402            static_tls_init_block,
3403            static_tls_create_block,
3404            user_top,
3405            stack_size,
3406            tls_total,
3407            stack_owned,
3408            &mut stack_top,
3409            &mut tls_owned,
3410        )
3411    } else {
3412        carve_thread_tls(
3413            dynamic_tls_init,
3414            dynamic_tls_create,
3415            user_top,
3416            stack_size,
3417            tls_total,
3418            stack_owned,
3419            &mut stack_top,
3420            &mut tls_owned,
3421        )
3422    };
3423    if fs_base.is_null() {
3424        if stack_owned { sys_munmap(stack, stack_size); }
3425        release_thread_slot(slot);
3426        return EAGAIN;
3427    }
3428    let tls_base = if static_mode {
3429        fs_base.sub(STATIC_TLS_TP_OFFSET)
3430    } else {
3431        fs_base.sub(__keel_tls_base_offset())
3432    };
3433    let tls_size = if tls_owned { tls_total } else { 0 };
3434    init_thread_slot(slot, 1);
3435    (*slot).user_fn = start_routine;
3436    (*slot).user_arg = arg;
3437    (*slot).stack = stack;
3438    (*slot).stack_size = stack_size;
3439    (*slot).stack_owned = stack_owned;
3440    (*slot).fs_base = fs_base;
3441    (*slot).tls_base = tls_base;
3442    (*slot).tls_size = tls_size;
3443    let tid_ptr = &raw mut (*slot).tid;
3444    let flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD
3445        | CLONE_SYSVSEM | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SETTLS;
3446    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
3447    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);
3448    if tid < 0 {
3449        ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel);
3450        (*slot).tid = -1;
3451        if stack_owned { sys_munmap(stack, stack_size); }
3452        if tls_size > 0 { sys_munmap(tls_base, tls_size); }
3453        release_thread_slot(slot);
3454        return EAGAIN;
3455    }
3456    if !attr.is_null() && (*attr).__i[6] == PTHREAD_CREATE_DETACHED {
3457        (*slot).detach_state = DT_DETACHED;
3458    }
3459    *thread = slot as PthreadT;
3460    0
3461}
3462
3463/// Tear down a joined or detached thread slot. The TLS block is kept mapped:
3464/// some runtimes (notably V8) retain pointers into an exited thread's TLS
3465/// and dereference them during process teardown.
3466unsafe fn release_finished_slot(slot: *mut Thread) {
3467    let stack = (*slot).stack;
3468    let stack_size = (*slot).stack_size;
3469    let stack_owned = (*slot).stack_owned;
3470    (*slot).tid = -1;
3471    (*slot).detach_state = DT_JOINABLE;
3472    (*slot).result = core::ptr::null_mut();
3473    (*slot).stack = core::ptr::null_mut();
3474    (*slot).stack_size = 0;
3475    (*slot).stack_owned = false;
3476    (*slot).fs_base = core::ptr::null_mut();
3477    (*slot).tls_base = core::ptr::null_mut();
3478    (*slot).tls_size = 0;
3479    if stack_owned && !stack.is_null() && stack_size > 0 {
3480        sys_munmap(stack, stack_size);
3481    }
3482    release_thread_slot(slot);
3483}
3484
3485#[no_mangle]
3486pub unsafe extern "C" fn pthread_join(thread: PthreadT, retval: *mut *mut c_void) -> c_int {
3487    let slot = thread as *mut Thread;
3488    if slot.is_null() { return EINVAL; }
3489    if thread == pthread_self() { return EDEADLK; }
3490    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
3491    let tid_ptr = &raw mut (*slot).tid;
3492    loop {
3493        pthread_testcancel();
3494        let tid = core::ptr::read_volatile(tid_ptr);
3495        if tid == 0 { break; }
3496        if tid < 0 { return EINVAL; }
3497        sys_futex(tid_ptr, FUTEX_WAIT, tid, null_mut(), null_mut(), 0);
3498        pthread_testcancel();
3499    }
3500    if !retval.is_null() { *retval = (*slot).result; }
3501    release_finished_slot(slot);
3502    0
3503}
3504
3505#[no_mangle]
3506pub unsafe extern "C" fn pthread_detach(thread: PthreadT) -> c_int {
3507    let slot = thread as *mut Thread;
3508    if slot.is_null() { return EINVAL; }
3509    let old = a_cas(&raw mut (*slot).detach_state, DT_JOINABLE, DT_DETACHED);
3510    if old == DT_EXITED {
3511        release_finished_slot(slot);
3512    }
3513    0
3514}
3515
3516#[no_mangle]
3517pub unsafe extern "C" fn pthread_exit(retval: *mut c_void) -> ! {
3518    if let Some(slot) = find_thread() {
3519        thread_finish(slot, retval)
3520    }
3521    sys_exit_thread(0)
3522}
3523
3524// pthread_attr_t stores a usize stack size at __i[0..2], a usize guard at
3525// __i[2..4], the stack top pointer at __i[4..6], and scalar flags after it.
3526unsafe fn attr_stack_size(attr: *const pthread_attr_t) -> usize {
3527    *((*attr).__i.as_ptr() as *const usize)
3528}
3529unsafe fn attr_set_stack_size(attr: *mut pthread_attr_t, sz: usize) {
3530    *((*attr).__i.as_mut_ptr() as *mut usize) = sz;
3531}
3532unsafe fn attr_stack_top(attr: *const pthread_attr_t) -> *mut c_void {
3533    *((*attr).__i.as_ptr().add(4) as *const *mut c_void)
3534}
3535unsafe fn attr_set_stack_top(attr: *mut pthread_attr_t, top: *mut c_void) {
3536    *((*attr).__i.as_mut_ptr().add(4) as *mut *mut c_void) = top;
3537}
3538unsafe fn attr_guard_size(attr: *const pthread_attr_t) -> usize {
3539    *((*attr).__i.as_ptr().add(2) as *const usize)
3540}
3541unsafe fn attr_set_guard_size(attr: *mut pthread_attr_t, sz: usize) {
3542    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = sz;
3543}
3544
3545// --- pthread_attr_* ---
3546#[no_mangle]
3547pub unsafe extern "C" fn pthread_attr_init(attr: *mut pthread_attr_t) -> c_int {
3548    core::ptr::write_bytes(attr, 0, 1);
3549    attr_set_stack_size(attr, STACK_SIZE);
3550    attr_set_guard_size(attr, PAGE);
3551    (*attr).__i[6] = PTHREAD_CREATE_JOINABLE;
3552    (*attr).__i[7] = PTHREAD_INHERIT_SCHED;
3553    0
3554}
3555#[no_mangle]
3556pub unsafe extern "C" fn pthread_attr_destroy(_attr: *mut pthread_attr_t) -> c_int { 0 }
3557#[no_mangle]
3558pub unsafe extern "C" fn pthread_attr_setdetachstate(attr: *mut pthread_attr_t, s: c_int) -> c_int {
3559    if s != PTHREAD_CREATE_JOINABLE && s != PTHREAD_CREATE_DETACHED { return EINVAL; }
3560    (*attr).__i[6] = s; 0
3561}
3562#[no_mangle]
3563pub unsafe extern "C" fn pthread_attr_getdetachstate(attr: *const pthread_attr_t, s: *mut c_int) -> c_int {
3564    *s = (*attr).__i[6]; 0
3565}
3566#[no_mangle]
3567pub unsafe extern "C" fn pthread_attr_setstacksize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
3568    if sz < 2048 { return EINVAL; }
3569    attr_set_stack_size(attr, sz);
3570    attr_set_stack_top(attr, core::ptr::null_mut());
3571    0
3572}
3573#[no_mangle]
3574pub unsafe extern "C" fn pthread_attr_getstacksize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
3575    *sz = attr_stack_size(attr); 0
3576}
3577#[no_mangle]
3578pub unsafe extern "C" fn pthread_attr_setstack(attr: *mut pthread_attr_t, addr: *mut c_void, sz: usize) -> c_int {
3579    if sz < 2048 { return EINVAL; }
3580    attr_set_stack_size(attr, sz);
3581    // musl stores the top of the stack, not its base.
3582    attr_set_stack_top(attr, (addr as *mut u8).add(sz) as *mut c_void);
3583    0
3584}
3585#[no_mangle]
3586pub unsafe extern "C" fn pthread_attr_getstack(attr: *const pthread_attr_t, addr: *mut *mut c_void, sz: *mut usize) -> c_int {
3587    let size = attr_stack_size(attr);
3588    *sz = size;
3589    let top = attr_stack_top(attr);
3590    *addr = if top.is_null() {
3591        core::ptr::null_mut()
3592    } else {
3593        (top as *mut u8).sub(size) as *mut c_void
3594    };
3595    0
3596}
3597#[no_mangle]
3598pub unsafe extern "C" fn pthread_attr_setguardsize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
3599    attr_set_guard_size(attr, sz); 0
3600}
3601#[no_mangle]
3602pub unsafe extern "C" fn pthread_attr_getguardsize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
3603    *sz = attr_guard_size(attr); 0
3604}
3605#[no_mangle]
3606pub unsafe extern "C" fn pthread_attr_setscope(_attr: *mut pthread_attr_t, scope: c_int) -> c_int {
3607    if scope != PTHREAD_SCOPE_SYSTEM { return EINVAL; }
3608    0
3609}
3610#[no_mangle]
3611pub unsafe extern "C" fn pthread_attr_getscope(_attr: *const pthread_attr_t, scope: *mut c_int) -> c_int {
3612    *scope = PTHREAD_SCOPE_SYSTEM; 0
3613}
3614#[no_mangle]
3615pub unsafe extern "C" fn pthread_attr_setinheritsched(attr: *mut pthread_attr_t, inh: c_int) -> c_int {
3616    if inh != PTHREAD_INHERIT_SCHED && inh != PTHREAD_EXPLICIT_SCHED { return EINVAL; }
3617    (*attr).__i[7] = inh; 0
3618}
3619#[no_mangle]
3620pub unsafe extern "C" fn pthread_attr_getinheritsched(attr: *const pthread_attr_t, inh: *mut c_int) -> c_int {
3621    *inh = (*attr).__i[7]; 0
3622}
3623#[no_mangle]
3624pub unsafe extern "C" fn pthread_attr_setschedpolicy(attr: *mut pthread_attr_t, p: c_int) -> c_int {
3625    (*attr).__i[8] = p; 0
3626}
3627#[no_mangle]
3628pub unsafe extern "C" fn pthread_attr_getschedpolicy(attr: *const pthread_attr_t, p: *mut c_int) -> c_int {
3629    *p = (*attr).__i[8]; 0
3630}
3631#[no_mangle]
3632pub unsafe extern "C" fn pthread_attr_setschedparam(attr: *mut pthread_attr_t, param: *const sched_param) -> c_int {
3633    (*attr).__i[9] = (*param).sched_priority; 0
3634}
3635#[no_mangle]
3636pub unsafe extern "C" fn pthread_attr_getschedparam(attr: *const pthread_attr_t, param: *mut sched_param) -> c_int {
3637    (*param).sched_priority = (*attr).__i[9]; 0
3638}
3639
3640// --- pthread_mutexattr_* ---
3641#[no_mangle]
3642pub unsafe extern "C" fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> c_int {
3643    (*attr).__attr = 0; 0
3644}
3645#[no_mangle]
3646pub unsafe extern "C" fn pthread_mutexattr_destroy(_attr: *mut pthread_mutexattr_t) -> c_int { 0 }
3647#[no_mangle]
3648pub unsafe extern "C" fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, t: c_int) -> c_int {
3649    if (t as c_uint) > 2 { return EINVAL; }
3650    (*attr).__attr = ((*attr).__attr & !3) | t as c_uint; 0
3651}
3652#[no_mangle]
3653pub unsafe extern "C" fn pthread_mutexattr_gettype(attr: *const pthread_mutexattr_t, t: *mut c_int) -> c_int {
3654    *t = ((*attr).__attr & 3) as c_int; 0
3655}
3656#[no_mangle]
3657pub unsafe extern "C" fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, p: c_int) -> c_int {
3658    if (p as c_uint) > 1 { return EINVAL; }
3659    (*attr).__attr = ((*attr).__attr & !(MUTEX_PSHARED as c_uint)) | ((p as c_uint) << 7); 0
3660}
3661#[no_mangle]
3662pub unsafe extern "C" fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, p: *mut c_int) -> c_int {
3663    *p = (((*attr).__attr >> 7) & 1) as c_int; 0
3664}
3665
3666#[no_mangle]
3667pub unsafe extern "C" fn pthread_mutexattr_setprotocol(attr: *mut pthread_mutexattr_t, protocol: c_int) -> c_int {
3668    match protocol {
3669        0 => { (*attr).__attr &= !(MUTEX_PI as c_uint); 0 }
3670        1 => {
3671            let mut lk: c_int = 0;
3672            let r = sys_futex(&raw mut lk, FUTEX_LOCK_PI, 0, null_mut(), null_mut(), 0);
3673            if r < 0 { return (-r) as c_int; }
3674            sys_futex(&raw mut lk, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
3675            (*attr).__attr |= MUTEX_PI as c_uint;
3676            0
3677        }
3678        2 => ENOTSUP,
3679        _ => EINVAL,
3680    }
3681}
3682#[no_mangle]
3683pub unsafe extern "C" fn pthread_mutexattr_getprotocol(attr: *const pthread_mutexattr_t, protocol: *mut c_int) -> c_int {
3684    *protocol = (((*attr).__attr >> 3) & 3) as c_int; 0
3685}
3686
3687
3688#[no_mangle]
3689pub unsafe extern "C" fn pthread_mutexattr_setrobust(attr: *mut pthread_mutexattr_t, robust: c_int) -> c_int {
3690    if (robust as c_uint) > 1 { return EINVAL; }
3691    if robust != 0 {
3692        (*attr).__attr |= MUTEX_ROBUST as c_uint;
3693    } else {
3694        (*attr).__attr &= !(MUTEX_ROBUST as c_uint);
3695    }
3696    0
3697}
3698#[no_mangle]
3699pub unsafe extern "C" fn pthread_mutexattr_getrobust(attr: *const pthread_mutexattr_t, robust: *mut c_int) -> c_int {
3700    *robust = (((*attr).__attr >> 2) & 1) as c_int; 0
3701}
3702
3703#[no_mangle]
3704pub unsafe extern "C" fn pthread_mutex_consistent(m: *mut pthread_mutex_t) -> c_int {
3705    let old = a_load(&raw const (*m).__i[1]);
3706    let own = old & MUTEX_OWNER_MASK;
3707    if ((*m).__i[0] & MUTEX_ROBUST) == 0 || own == 0 || (old & MUTEX_ROBUST_PENDING) == 0 {
3708        return EINVAL;
3709    }
3710    let self_tid = sys_gettid() as c_int;
3711    if own != self_tid { return EPERM; }
3712    a_and(&raw mut (*m).__i[1], !(MUTEX_ROBUST_PENDING));
3713    0
3714}
3715
3716unsafe fn a_and(addr: *mut c_int, val: c_int) {
3717    let a = &*(addr as *const AtomicI32);
3718    a.fetch_and(val, Ordering::AcqRel);
3719}
3720
3721// --- pthread_mutex_* ---
3722const MUTEX_TYPE_MASK: c_int = 3;
3723const MUTEX_ROBUST: c_int = 4;
3724const MUTEX_PI: c_int = 8;
3725const MUTEX_PSHARED: c_int = 128;
3726const MUTEX_OWNER_MASK: c_int = 0x3fff_ffff;
3727const MUTEX_ROBUST_PENDING: c_int = 0x4000_0000;
3728const FUTEX_WAITER_BIT: c_int = 1i32 << 31;
3729
3730unsafe fn ensure_robust_list(slot: &mut Thread) {
3731    if slot.robust_list.futex_offset == 0 {
3732        slot.robust_list.futex_offset = -28;
3733        slot.robust_list.pending = core::ptr::null_mut();
3734        sys_set_robust_list(&mut slot.robust_list, 24);
3735    }
3736}
3737
3738unsafe fn mutex_trylock(m: *mut pthread_mutex_t) -> c_int {
3739    let type_ = (*m).__i[0];
3740    // Fast path: plain NORMAL only (no PI, no robust, no pshared).
3741    // A failed CAS must report EBUSY unconditionally: the old value may be
3742    // the waiter bit (0x80000000), whose low bits are zero, and masking it
3743    // with EBUSY would falsely report that the lock was acquired.
3744    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL {
3745        let old = a_cas(&raw mut (*m).__i[1], 0, EBUSY);
3746        return if old == 0 { 0 } else { EBUSY };
3747    }
3748    let base_type = type_ & MUTEX_TYPE_MASK;
3749    let self_tid = sys_gettid() as c_int;
3750    let old = a_load(&raw const (*m).__i[1]);
3751    let own = old & MUTEX_OWNER_MASK;
3752    if own == self_tid {
3753        if (type_ & MUTEX_PI) != 0 && (*m).__i[5] < 0 {
3754            (*m).__i[5] = 0;
3755            return 0;
3756        }
3757        if base_type == PTHREAD_MUTEX_RECURSIVE {
3758            if (*m).__i[5] >= c_int::MAX { return EAGAIN; }
3759            (*m).__i[5] += 1;
3760            return 0;
3761        }
3762        if base_type == PTHREAD_MUTEX_ERRORCHECK { return EDEADLK; }
3763        return EBUSY;
3764    }
3765    if own == MUTEX_OWNER_MASK { return ENOTRECOVERABLE; }
3766    if own != 0 || (old != 0 && (type_ & MUTEX_ROBUST) == 0) { return EBUSY; }
3767    let mut newtid = self_tid;
3768    if (type_ & MUTEX_ROBUST) != 0 {
3769        if (*m).__i[2] != 0 { newtid |= FUTEX_WAITER_BIT; }
3770        newtid |= old & MUTEX_ROBUST_PENDING;
3771    }
3772    if a_cas(&raw mut (*m).__i[1], old, newtid) == old {
3773        (*m).__i[5] = 0;
3774        if (type_ & MUTEX_ROBUST) != 0 {
3775            if let Some(slot) = find_thread() {
3776                ensure_robust_list(slot);
3777                let m_next = &raw mut (*m).__i[8] as *mut robust_list;
3778                let head = &mut slot.robust_list.list;
3779                (*m_next).next = head.next;
3780                head.next = m_next;
3781            }
3782        }
3783        if old != 0 { return EOWNERDEAD; }
3784        0
3785    } else { EBUSY }
3786}
3787
3788unsafe fn mutex_lock_internal(m: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3789    let type_ = (*m).__i[0];
3790    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL && a_cas(&raw mut (*m).__i[1], 0, EBUSY) == 0 {
3791        return 0;
3792    }
3793    let r = mutex_trylock(m);
3794    if r != EBUSY { return r; }
3795    if (type_ & MUTEX_PI) != 0 {
3796        let timeout_ptr = if abs_timeout.is_null() { core::ptr::null() } else { abs_timeout };
3797        loop {
3798            let e = futex_lock_pi(&raw mut (*m).__i[1], timeout_ptr);
3799            match e {
3800                0 => {
3801                    if (type_ & MUTEX_ROBUST) != 0 && (((*m).__i[1] & MUTEX_ROBUST_PENDING) != 0 || (*m).__i[2] != 0) {
3802                        (*m).__i[5] = -1;
3803                        let _ = mutex_trylock(m);
3804                        return EOWNERDEAD;
3805                    }
3806                    if (type_ & MUTEX_ROBUST) == 0 && (((*m).__i[1] & MUTEX_ROBUST_PENDING) != 0 || (*m).__i[2] != 0) {
3807                        (*m).__i[2] = -1;
3808                        futex_unlock_pi(&raw mut (*m).__i[1]);
3809                        return EBUSY;
3810                    }
3811                    (*m).__i[5] = -1;
3812                    let r2 = mutex_trylock(m);
3813                    if r2 == 0 { return 0; }
3814                    return r2;
3815                }
3816                EINTR => continue,
3817                EDEADLK => {
3818                    if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK { return e; }
3819                    loop { pause(); }
3820                }
3821                EOWNERDEAD => {
3822                    (*m).__i[5] = -1;
3823                    let _ = mutex_trylock(m);
3824                    return EOWNERDEAD;
3825                }
3826                _ => return e,
3827            }
3828        }
3829    }
3830    let mut spins = 100;
3831    while spins > 0 {
3832        let r = mutex_trylock(m);
3833        if r != EBUSY { return r; }
3834        core::hint::spin_loop();
3835        spins -= 1;
3836    }
3837    loop {
3838        let r = mutex_trylock(m);
3839        if r != EBUSY { return r; }
3840        if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK {
3841            let self_tid = sys_gettid() as c_int;
3842            if (a_load(&raw const (*m).__i[1]) & MUTEX_OWNER_MASK) == self_tid { return EDEADLK; }
3843        }
3844        a_fetch_add(&raw mut (*m).__i[2], 1);
3845        let val = a_load(&raw const (*m).__i[1]);
3846        // If the previous owner released the lock between trylock() and the
3847        // load above, retry instead of publishing a waiter-only lock word
3848        // (0x80000000) that no thread owns.
3849        if val == 0 {
3850            a_fetch_sub(&raw mut (*m).__i[2], 1);
3851            continue;
3852        }
3853        a_cas(&raw mut (*m).__i[1], val, val | FUTEX_WAITER_BIT);
3854        let e = futex_timedwait(&raw mut (*m).__i[1], val | FUTEX_WAITER_BIT, abs_timeout);
3855        a_fetch_sub(&raw mut (*m).__i[2], 1);
3856        if e != 0 && e != EINTR { return e; }
3857    }
3858}
3859
3860#[no_mangle]
3861pub unsafe extern "C" fn pthread_mutex_init(mutex: *mut pthread_mutex_t, attr: *const pthread_mutexattr_t) -> c_int {
3862    core::ptr::write_bytes(mutex, 0, 1);
3863    if !attr.is_null() { (*mutex).__i[0] = (*attr).__attr as c_int; }
3864    0
3865}
3866#[no_mangle]
3867pub unsafe extern "C" fn pthread_mutex_destroy(_mutex: *mut pthread_mutex_t) -> c_int { 0 }
3868#[no_mangle]
3869pub unsafe extern "C" fn pthread_mutex_lock(mutex: *mut pthread_mutex_t) -> c_int {
3870    mutex_lock_internal(mutex, core::ptr::null())
3871}
3872#[no_mangle]
3873pub unsafe extern "C" fn pthread_mutex_trylock(mutex: *mut pthread_mutex_t) -> c_int {
3874    mutex_trylock(mutex)
3875}
3876#[no_mangle]
3877pub unsafe extern "C" fn pthread_mutex_timedlock(mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3878    mutex_lock_internal(mutex, abs_timeout)
3879}
3880#[no_mangle]
3881pub unsafe extern "C" fn pthread_mutex_unlock(mutex: *mut pthread_mutex_t) -> c_int {
3882    let type_ = (*mutex).__i[0];
3883    let base_type = type_ & MUTEX_TYPE_MASK;
3884    let old = a_load(&raw const (*mutex).__i[1]);
3885    if base_type != PTHREAD_MUTEX_NORMAL {
3886        let self_tid = sys_gettid() as c_int;
3887        if (old & MUTEX_OWNER_MASK) != self_tid { return EPERM; }
3888        if base_type == PTHREAD_MUTEX_RECURSIVE && (*mutex).__i[5] > 0 {
3889            (*mutex).__i[5] -= 1;
3890            return 0;
3891        }
3892    }
3893    let mut new = 0;
3894    if (type_ & MUTEX_ROBUST) != 0 && (old & MUTEX_ROBUST_PENDING) != 0 {
3895        new = 0x7fffffff;
3896    }
3897    if (type_ & MUTEX_PI) != 0 {
3898        if old < 0 || a_cas(&raw mut (*mutex).__i[1], old, new) != old {
3899            if new != 0 { a_store(&raw mut (*mutex).__i[2], -1); }
3900            return futex_unlock_pi(&raw mut (*mutex).__i[1]);
3901        }
3902        return 0;
3903    }
3904    a_store(&raw mut (*mutex).__i[1], new);
3905    if new == 0 && (a_load(&raw const (*mutex).__i[2]) > 0 || old < 0) {
3906        futex_wake(&raw mut (*mutex).__i[1], 1);
3907    }
3908    0
3909}
3910
3911// --- pthread_condattr_* ---
3912#[no_mangle]
3913pub unsafe extern "C" fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> c_int {
3914    (*attr).__attr = 0; 0
3915}
3916#[no_mangle]
3917pub unsafe extern "C" fn pthread_condattr_destroy(_attr: *mut pthread_condattr_t) -> c_int { 0 }
3918#[no_mangle]
3919pub unsafe extern "C" fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, clk: c_int) -> c_int {
3920    if clk != CLOCK_REALTIME && clk != CLOCK_MONOTONIC { return EINVAL; }
3921    (*attr).__attr = ((*attr).__attr & 0x80000000) | clk as c_uint; 0
3922}
3923#[no_mangle]
3924pub unsafe extern "C" fn pthread_condattr_getclock(attr: *const pthread_condattr_t, clk: *mut c_int) -> c_int {
3925    *clk = ((*attr).__attr & 0x7fffffff) as c_int; 0
3926}
3927#[no_mangle]
3928pub unsafe extern "C" fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, p: c_int) -> c_int {
3929    if (p as c_uint) > 1 { return EINVAL; }
3930    (*attr).__attr = ((*attr).__attr & 0x7fffffff) | ((p as c_uint) << 31); 0
3931}
3932#[no_mangle]
3933pub unsafe extern "C" fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, p: *mut c_int) -> c_int {
3934    *p = ((*attr).__attr >> 31) as c_int; 0
3935}
3936
3937// --- pthread_cond_* ---
3938#[no_mangle]
3939pub unsafe extern "C" fn pthread_cond_init(cond: *mut pthread_cond_t, attr: *const pthread_condattr_t) -> c_int {
3940    core::ptr::write_bytes(cond, 0, 1);
3941    if !attr.is_null() {
3942        (*cond).__i[4] = ((*attr).__attr & 0x7fffffff) as c_int;
3943    }
3944    0
3945}
3946#[no_mangle]
3947pub unsafe extern "C" fn pthread_cond_destroy(_cond: *mut pthread_cond_t) -> c_int { 0 }
3948#[no_mangle]
3949pub unsafe extern "C" fn pthread_cond_wait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t) -> c_int {
3950    pthread_cond_timedwait(cond, mutex, core::ptr::null())
3951}
3952
3953
3954#[no_mangle]
3955pub unsafe extern "C" fn pthread_cond_timedwait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
3956    pthread_testcancel();
3957    let seq_ptr = &raw mut (*cond).__i[2];
3958    let waiters_ptr = &raw mut (*cond).__i[3];
3959    let seq = a_load(seq_ptr);
3960    a_fetch_add(waiters_ptr, 1);
3961    pthread_mutex_unlock(mutex);
3962    let e = futex_timedwait(seq_ptr, seq, abs_timeout);
3963    a_fetch_sub(waiters_ptr, 1);
3964    let r = pthread_mutex_lock(mutex);
3965    if r != 0 { return r; }
3966    if e == EINTR {
3967        pthread_testcancel();
3968    }
3969    if e != 0 && e != EINTR { return e; }
3970    0
3971}
3972#[no_mangle]
3973pub unsafe extern "C" fn pthread_cond_signal(cond: *mut pthread_cond_t) -> c_int {
3974    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
3975    a_fetch_add(&raw mut (*cond).__i[2], 1);
3976    futex_wake(&raw mut (*cond).__i[2], 1);
3977    0
3978}
3979#[no_mangle]
3980pub unsafe extern "C" fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> c_int {
3981    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
3982    a_fetch_add(&raw mut (*cond).__i[2], 1);
3983    futex_wake(&raw mut (*cond).__i[2], -1);
3984    0
3985}
3986
3987// --- pthread_rwlockattr_* ---
3988#[no_mangle]
3989pub unsafe extern "C" fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> c_int {
3990    (*attr).__attr = [0; 2]; 0
3991}
3992#[no_mangle]
3993pub unsafe extern "C" fn pthread_rwlockattr_destroy(_attr: *mut pthread_rwlockattr_t) -> c_int { 0 }
3994#[no_mangle]
3995pub unsafe extern "C" fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, p: c_int) -> c_int {
3996    if (p as c_uint) > 1 { return EINVAL; }
3997    (*attr).__attr[0] = ((*attr).__attr[0] & !128) | ((p as c_uint) << 7); 0
3998}
3999#[no_mangle]
4000pub unsafe extern "C" fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, p: *mut c_int) -> c_int {
4001    *p = (((*attr).__attr[0] >> 7) & 1) as c_int; 0
4002}
4003
4004// --- pthread_rwlock_* ---
4005unsafe fn rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int {
4006    loop {
4007        let val = a_load(&raw const (*rw).__i[0]);
4008        let cnt = val & 0x7fffffff;
4009        if cnt == 0x7fffffff { return EBUSY; }
4010        if cnt == 0x7ffffffe { return EAGAIN; }
4011        if a_cas(&raw mut (*rw).__i[0], val, val + 1) == val { return 0; }
4012    }
4013}
4014unsafe fn rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int {
4015    if a_cas(&raw mut (*rw).__i[0], 0, 0x7fffffff) == 0 { 0 } else { EBUSY }
4016}
4017unsafe fn rwlock_timedrdlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
4018    let r = rwlock_tryrdlock(rw);
4019    if r != EBUSY { return r; }
4020    let mut spins = 100;
4021    while spins > 0 { let r = rwlock_tryrdlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
4022    loop {
4023        let r = rwlock_tryrdlock(rw);
4024        if r != EBUSY { return r; }
4025        let val = a_load(&raw const (*rw).__i[0]);
4026        if val & 0x7fffffff != 0x7fffffff { continue; }
4027        a_fetch_add(&raw mut (*rw).__i[1], 1);
4028        a_cas(&raw mut (*rw).__i[0], val, val | FUTEX_WAITER_BIT);
4029        let e = futex_timedwait(&raw mut (*rw).__i[0], val | FUTEX_WAITER_BIT, abs_timeout);
4030        a_fetch_sub(&raw mut (*rw).__i[1], 1);
4031        if e != 0 && e != EINTR { return e; }
4032    }
4033}
4034unsafe fn rwlock_timedwrlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
4035    let r = rwlock_trywrlock(rw);
4036    if r != EBUSY { return r; }
4037    let mut spins = 100;
4038    while spins > 0 { let r = rwlock_trywrlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
4039    loop {
4040        let r = rwlock_trywrlock(rw);
4041        if r != EBUSY { return r; }
4042        let val = a_load(&raw const (*rw).__i[0]);
4043        if val == 0 { continue; }
4044        a_fetch_add(&raw mut (*rw).__i[1], 1);
4045        a_cas(&raw mut (*rw).__i[0], val, val | FUTEX_WAITER_BIT);
4046        let e = futex_timedwait(&raw mut (*rw).__i[0], val | FUTEX_WAITER_BIT, abs_timeout);
4047        a_fetch_sub(&raw mut (*rw).__i[1], 1);
4048        if e != 0 && e != EINTR { return e; }
4049    }
4050}
4051
4052#[no_mangle]
4053pub unsafe extern "C" fn pthread_rwlock_init(rw: *mut pthread_rwlock_t, attr: *const pthread_rwlockattr_t) -> c_int {
4054    core::ptr::write_bytes(rw, 0, 1);
4055    if !attr.is_null() { (*rw).__i[2] = (*attr).__attr[0] as c_int & 128; }
4056    0
4057}
4058#[no_mangle]
4059pub unsafe extern "C" fn pthread_rwlock_destroy(_rw: *mut pthread_rwlock_t) -> c_int { 0 }
4060#[no_mangle]
4061pub unsafe extern "C" fn pthread_rwlock_rdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedrdlock(rw, core::ptr::null()) }
4062#[no_mangle]
4063pub unsafe extern "C" fn pthread_rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_tryrdlock(rw) }
4064#[no_mangle]
4065pub unsafe extern "C" fn pthread_rwlock_timedrdlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedrdlock(rw, t) }
4066#[no_mangle]
4067pub unsafe extern "C" fn pthread_rwlock_wrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedwrlock(rw, core::ptr::null()) }
4068#[no_mangle]
4069pub unsafe extern "C" fn pthread_rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_trywrlock(rw) }
4070#[no_mangle]
4071pub unsafe extern "C" fn pthread_rwlock_timedwrlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedwrlock(rw, t) }
4072#[no_mangle]
4073pub unsafe extern "C" fn pthread_rwlock_unlock(rw: *mut pthread_rwlock_t) -> c_int {
4074    loop {
4075        let val = a_load(&raw const (*rw).__i[0]);
4076        let cnt = val & 0x7fffffff;
4077        let new_val = if cnt == 0x7fffffff || cnt == 1 { 0 } else { val - 1 };
4078        if a_cas(&raw mut (*rw).__i[0], val, new_val) == val {
4079            if new_val == 0 && (a_load(&raw const (*rw).__i[1]) > 0 || val < 0) {
4080                futex_wake(&raw mut (*rw).__i[0], cnt);
4081            }
4082            return 0;
4083        }
4084    }
4085}
4086
4087// --- pthread_barrierattr_* ---
4088#[no_mangle]
4089pub unsafe extern "C" fn pthread_barrierattr_init(attr: *mut pthread_barrierattr_t) -> c_int { (*attr).__attr = 0; 0 }
4090#[no_mangle]
4091pub unsafe extern "C" fn pthread_barrierattr_destroy(_attr: *mut pthread_barrierattr_t) -> c_int { 0 }
4092#[no_mangle]
4093pub unsafe extern "C" fn pthread_barrierattr_setpshared(attr: *mut pthread_barrierattr_t, p: c_int) -> c_int {
4094    if (p as c_uint) > 1 { return EINVAL; }
4095    (*attr).__attr = p as c_uint; 0
4096}
4097#[no_mangle]
4098pub unsafe extern "C" fn pthread_barrierattr_getpshared(attr: *const pthread_barrierattr_t, p: *mut c_int) -> c_int {
4099    *p = (*attr).__attr as c_int; 0
4100}
4101
4102// --- pthread_barrier_* ---
4103#[no_mangle]
4104pub unsafe extern "C" fn pthread_barrier_init(b: *mut pthread_barrier_t, _attr: *const pthread_barrierattr_t, count: c_uint) -> c_int {
4105    if count == 0 { return EINVAL; }
4106    core::ptr::write_bytes(b, 0, 1);
4107    (*b).__i[2] = count as c_int - 1;
4108    0
4109}
4110#[no_mangle]
4111pub unsafe extern "C" fn pthread_barrier_destroy(_b: *mut pthread_barrier_t) -> c_int { 0 }
4112#[no_mangle]
4113pub unsafe extern "C" fn pthread_barrier_wait(b: *mut pthread_barrier_t) -> c_int {
4114    let limit = (*b).__i[2];
4115    if limit == 0 { return PTHREAD_BARRIER_SERIAL_THREAD; }
4116    spinlock_lock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4117    let arrived = a_load(&raw const (*b).__i[3]) + 1;
4118    a_store(&raw mut (*b).__i[3], arrived);
4119    if arrived > limit {
4120        a_store(&raw mut (*b).__i[3], 0);
4121        let gen = a_load(&raw const (*b).__i[4]);
4122        a_store(&raw mut (*b).__i[4], gen + 1);
4123        spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4124        futex_wake(&raw mut (*b).__i[4], -1);
4125        return PTHREAD_BARRIER_SERIAL_THREAD;
4126    }
4127    let gen = a_load(&raw const (*b).__i[4]);
4128    spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
4129    while a_load(&raw const (*b).__i[4]) == gen {
4130        futex_wait(&raw mut (*b).__i[4], gen);
4131    }
4132    0
4133}
4134
4135// --- pthread_spin_* ---
4136#[no_mangle]
4137pub unsafe extern "C" fn pthread_spin_init(s: *mut pthread_spinlock_t, _pshared: c_int) -> c_int { a_store(s, 0); 0 }
4138#[no_mangle]
4139pub unsafe extern "C" fn pthread_spin_destroy(_s: *mut pthread_spinlock_t) -> c_int { 0 }
4140#[no_mangle]
4141pub unsafe extern "C" fn pthread_spin_lock(s: *mut pthread_spinlock_t) -> c_int {
4142    while a_load(s) != 0 || a_cas(s, 0, EBUSY) != 0 { core::hint::spin_loop(); }
4143    0
4144}
4145#[no_mangle]
4146pub unsafe extern "C" fn pthread_spin_trylock(s: *mut pthread_spinlock_t) -> c_int { a_cas(s, 0, EBUSY) }
4147#[no_mangle]
4148pub unsafe extern "C" fn pthread_spin_unlock(s: *mut pthread_spinlock_t) -> c_int { a_store(s, 0); 0 }
4149
4150// --- sem_* ---
4151#[no_mangle]
4152pub unsafe extern "C" fn sem_init(sem: *mut sem_t, pshared: c_int, value: c_uint) -> c_int {
4153    if value > SEM_VALUE_MAX as c_uint { return EINVAL; }
4154    (*sem).__val[0] = value as c_int;
4155    (*sem).__val[1] = 0;
4156    (*sem).__val[2] = if pshared != 0 { 0 } else { 128 };
4157    0
4158}
4159#[no_mangle]
4160pub unsafe extern "C" fn sem_destroy(_sem: *mut sem_t) -> c_int { 0 }
4161
4162unsafe fn sem_trywait_internal(sem: *mut sem_t) -> c_int {
4163    loop {
4164        let val = a_load(&raw const (*sem).__val[0]);
4165        if val & SEM_VALUE_MAX == 0 { return EAGAIN; }
4166        if a_cas(&raw mut (*sem).__val[0], val, val - 1) == val { return 0; }
4167    }
4168}
4169
4170#[no_mangle]
4171pub unsafe extern "C" fn sem_trywait(sem: *mut sem_t) -> c_int {
4172    if sem_trywait_internal(sem) == 0 { 0 } else { ERRNO!() = EAGAIN; -1 }
4173}
4174unsafe fn sem_wait_common(sem: *mut sem_t, abs_timeout: *const timespec) -> c_int {
4175    pthread_testcancel();
4176    if sem_trywait_internal(sem) == 0 { return 0; }
4177    let mut spins = 100;
4178    while spins > 0 {
4179        if sem_trywait_internal(sem) == 0 { return 0; }
4180        core::hint::spin_loop();
4181        spins -= 1;
4182    }
4183    loop {
4184        pthread_testcancel();
4185        if sem_trywait_internal(sem) == 0 { return 0; }
4186        let val = a_load(&raw const (*sem).__val[0]);
4187        if val & SEM_VALUE_MAX != 0 { continue; }
4188        a_cas(&raw mut (*sem).__val[0], val, val | FUTEX_WAITER_BIT);
4189        a_fetch_add(&raw mut (*sem).__val[1], 1);
4190        let e = if abs_timeout.is_null() {
4191            futex_wait(&raw mut (*sem).__val[0], FUTEX_WAITER_BIT);
4192            0
4193        } else {
4194            futex_timedwait(&raw mut (*sem).__val[0], FUTEX_WAITER_BIT, abs_timeout)
4195        };
4196        a_fetch_sub(&raw mut (*sem).__val[1], 1);
4197        if e != 0 && e != EINTR { ERRNO!() = e; return -1; }
4198    }
4199}
4200
4201#[no_mangle]
4202pub unsafe extern "C" fn sem_wait(sem: *mut sem_t) -> c_int {
4203    sem_wait_common(sem, core::ptr::null())
4204}
4205
4206#[no_mangle]
4207pub unsafe extern "C" fn sem_timedwait(sem: *mut sem_t, abs_timeout: *const timespec) -> c_int {
4208    sem_wait_common(sem, abs_timeout)
4209}
4210
4211#[no_mangle]
4212pub unsafe extern "C" fn sem_post(sem: *mut sem_t) -> c_int {
4213    loop {
4214        let val = a_load(&raw const (*sem).__val[0]);
4215        if (val & SEM_VALUE_MAX) == SEM_VALUE_MAX { ERRNO!() = EOVERFLOW; return -1; }
4216        let mut new = val + 1;
4217        let waiters = a_load(&raw const (*sem).__val[1]);
4218        if waiters <= 1 { new &= !FUTEX_WAITER_BIT; }
4219        if a_cas(&raw mut (*sem).__val[0], val, new) == val {
4220            if val < 0 || waiters > 0 {
4221                futex_wake(&raw mut (*sem).__val[0], if waiters > 1 { 1 } else { -1 });
4222            }
4223            return 0;
4224        }
4225    }
4226}
4227#[no_mangle]
4228pub unsafe extern "C" fn sem_getvalue(sem: *mut sem_t, sval: *mut c_int) -> c_int {
4229    *sval = a_load(&raw const (*sem).__val[0]) & SEM_VALUE_MAX;
4230    0
4231}
4232
4233// ============================================================
4234// POSIX shared memory + named semaphores
4235// ============================================================
4236
4237const NAME_MAX: usize = 255;
4238const SEM_NSEMS_MAX: usize = 256;
4239
4240// global spinlock for semtab, upgrade to per-entry if contention matters
4241static SEMTAB_LOCK: AtomicI32 = AtomicI32::new(0);
4242
4243struct SemEntry {
4244    ino: u64,
4245    sem: *mut sem_t,
4246    refcnt: u32,
4247}
4248
4249// zero-init is fine for static mut (all-zero = free slots)
4250static mut SEMTAB: [SemEntry; SEM_NSEMS_MAX] = {
4251    const ZERO: SemEntry = SemEntry { ino: 0, sem: core::ptr::null_mut(), refcnt: 0 };
4252    [ZERO; SEM_NSEMS_MAX]
4253};
4254
4255unsafe fn semtab_lock() {
4256    while SEMTAB_LOCK.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed).is_err() {
4257        core::hint::spin_loop();
4258    }
4259}
4260
4261unsafe fn semtab_unlock() {
4262    SEMTAB_LOCK.store(0, Ordering::Release);
4263}
4264
4265// Validate shm/sem name and construct /dev/shm/<name> path.
4266// Returns path length or -1 with ERRNO set.
4267unsafe fn shm_mapname(name: *const c_char, buf: *mut u8) -> c_int {
4268    let mut p = name;
4269    // strip leading /
4270    while *p == b'/' as c_char { p = p.add(1); }
4271    let start = p;
4272    // find end of first component
4273    while *p != 0 && *p != b'/' as c_char { p = p.add(1); }
4274    let len = p.offset_from(start) as usize;
4275    // no trailing /, not empty, not "." or ".."
4276    if len == 0 || *p != 0 {
4277        ERRNO!() = EINVAL;
4278        return -1;
4279    }
4280    if len == 1 && *start == b'.' as c_char {
4281        ERRNO!() = EINVAL;
4282        return -1;
4283    }
4284    if len == 2 && *start == b'.' as c_char && *start.add(1) == b'.' as c_char {
4285        ERRNO!() = EINVAL;
4286        return -1;
4287    }
4288    if len > NAME_MAX {
4289        ERRNO!() = ENAMETOOLONG;
4290        return -1;
4291    }
4292    // build /dev/shm/<name>
4293    let prefix = b"/dev/shm/\0";
4294    let mut i = 0;
4295    while prefix[i] != 0 {
4296        *buf.add(i) = prefix[i];
4297        i += 1;
4298    }
4299    let mut j = 0;
4300    while j < len {
4301        *buf.add(i + j) = *start.add(j) as u8;
4302        j += 1;
4303    }
4304    *buf.add(i + j) = 0;
4305    (i + j) as c_int
4306}
4307
4308#[no_mangle]
4309pub unsafe extern "C" fn shm_open(name: *const c_char, flags: c_int, mode: mode_t) -> c_int {
4310    let mut buf = [0u8; 16 + NAME_MAX + 1];
4311    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
4312    let fd = sys_open(buf.as_ptr(), (flags | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
4313    if fd < 0 { ERRNO!() = (-fd) as c_int; return -1; }
4314    fd as c_int
4315}
4316
4317#[no_mangle]
4318pub unsafe extern "C" fn shm_unlink(name: *const c_char) -> c_int {
4319    let mut buf = [0u8; 16 + NAME_MAX + 1];
4320    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
4321    let r = sys_unlink(buf.as_ptr());
4322    syscall_ret(r) as c_int
4323}
4324
4325#[no_mangle]
4326pub unsafe extern "C" fn sem_open(name: *const c_char, flags: c_int, mut args: ...) -> *mut sem_t {
4327    let mut buf = [0u8; 16 + NAME_MAX + 1];
4328    if shm_mapname(name, buf.as_mut_ptr()).is_negative() {
4329        return core::ptr::null_mut(); // SEM_FAILED
4330    }
4331
4332    let oflags = flags & (O_CREAT | O_EXCL);
4333
4334    semtab_lock();
4335
4336    // find a free slot
4337    let mut slot: c_int = -1;
4338    for i in 0..SEMTAB_LEN {
4339        if SEMTAB[i].sem.is_null() && slot < 0 { slot = i as c_int; }
4340    }
4341    if slot < 0 {
4342        ERRNO!() = EMFILE;
4343        semtab_unlock();
4344        return core::ptr::null_mut();
4345    }
4346    // reserve slot
4347    SEMTAB[slot as usize].sem = !0usize as *mut sem_t; // sentinel
4348    semtab_unlock();
4349
4350    // extract va_args for O_CREAT
4351    let mut mode: mode_t = 0;
4352    let mut value: c_uint = 0;
4353    if oflags & O_CREAT != 0 {
4354        mode = args.next_arg::<mode_t>() & 0o666;
4355        value = args.next_arg::<c_uint>();
4356        if value > SEM_VALUE_MAX as c_uint {
4357            ERRNO!() = EINVAL;
4358            semtab_lock();
4359            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4360            semtab_unlock();
4361            return core::ptr::null_mut();
4362        }
4363    }
4364
4365    // try opening existing first (unless O_CREAT|O_EXCL)
4366    if oflags != O_CREAT | O_EXCL {
4367        let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
4368        if fd >= 0 {
4369            let map = sys_mmap(
4370                core::ptr::null_mut(),
4371                core::mem::size_of::<sem_t>(),
4372                PROT_READ | PROT_WRITE,
4373                MAP_SHARED,
4374                fd as i32,
4375                0,
4376            );
4377            sys_close(fd);
4378            if map != MMAP_FAILED {
4379                let st_ino = get_ino(fd as c_int, buf.as_ptr());
4380                return sem_register(map as *mut sem_t, st_ino, slot);
4381            }
4382        }
4383        if oflags == 0 {
4384            // no O_CREAT and file doesn't exist
4385            semtab_lock();
4386            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4387            semtab_unlock();
4388            return core::ptr::null_mut();
4389        }
4390    }
4391
4392    // create: write sem_t to temp file, mmap, link
4393    let mut tmp = [0u8; 32];
4394    let tmpname = b"/dev/shm/tmp-XXXXXX\0";
4395    tmp[..tmpname.len()].copy_from_slice(tmpname);
4396    // use clock for unique name
4397    let mut ts: timespec = core::mem::zeroed();
4398    sys_clock_gettime(0, &mut ts);
4399    // append ns to tmp name
4400    let mut n = ts.tv_nsec;
4401    let mut pos = tmpname.len() - 1;
4402    tmp[pos] = 0;
4403    pos -= 1;
4404    loop {
4405        tmp[pos] = b'0' + (n % 10) as u8;
4406        n /= 10;
4407        if n == 0 || pos == 0 { break; }
4408        pos -= 1;
4409    }
4410        // shift to start of number part
4411        let tmp_path = tmp.as_ptr();
4412
4413    let mut newsem: sem_t = core::mem::zeroed();
4414    newsem.__val[0] = value as c_int;
4415    newsem.__val[1] = 0;
4416    newsem.__val[2] = 128; // pshared=0 flag
4417
4418    let mut attempts = 0usize;
4419    loop {
4420        let fd = sys_open(tmp_path as *const u8, (O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
4421        if fd < 0 {
4422            if (-fd) as c_int == EEXIST {
4423                attempts += 1;
4424                if attempts >= 16 {
4425                    ERRNO!() = EEXIST;
4426                    semtab_lock();
4427                    SEMTAB[slot as usize].sem = core::ptr::null_mut();
4428                    semtab_unlock();
4429                    return core::ptr::null_mut();
4430                }
4431                continue;
4432            }
4433            semtab_lock();
4434            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4435            semtab_unlock();
4436            return core::ptr::null_mut();
4437        }
4438        let written = sys_write(fd, &newsem as *const sem_t as *const u8, core::mem::size_of::<sem_t>());
4439        if written != core::mem::size_of::<sem_t>() as i64 {
4440            sys_close(fd);
4441            sys_unlink(tmp_path);
4442            semtab_lock();
4443            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4444            semtab_unlock();
4445            return core::ptr::null_mut();
4446        }
4447        let map = sys_mmap(
4448            core::ptr::null_mut(),
4449            core::mem::size_of::<sem_t>(),
4450            PROT_READ | PROT_WRITE,
4451            MAP_SHARED,
4452            fd as i32,
4453            0,
4454        );
4455        sys_close(fd);
4456        if map == MMAP_FAILED {
4457            sys_unlink(tmp_path);
4458            semtab_lock();
4459            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4460            semtab_unlock();
4461            return core::ptr::null_mut();
4462        }
4463        // link to final name
4464        let r = sys_linkat(AT_FDCWD, tmp_path, AT_FDCWD, buf.as_ptr(), 0);
4465        let e = if r < 0 { (-r) as c_int } else { 0 };
4466        sys_unlink(tmp_path);
4467        if e == 0 {
4468            let st_ino = get_ino(-1, buf.as_ptr());
4469            return sem_register(map as *mut sem_t, st_ino, slot);
4470        }
4471        sys_munmap(map, core::mem::size_of::<sem_t>());
4472        if e != EEXIST || oflags == O_CREAT | O_EXCL {
4473            ERRNO!() = e;
4474            semtab_lock();
4475            SEMTAB[slot as usize].sem = core::ptr::null_mut();
4476            semtab_unlock();
4477            return core::ptr::null_mut();
4478        }
4479        // EEXIST without O_EXCL: retry open existing
4480        break;
4481    }
4482
4483    // fallthrough: try opening the existing file that won the race
4484    let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
4485    if fd < 0 {
4486        semtab_lock();
4487        SEMTAB[slot as usize].sem = core::ptr::null_mut();
4488        semtab_unlock();
4489        return core::ptr::null_mut();
4490    }
4491    let map = sys_mmap(
4492        core::ptr::null_mut(),
4493        core::mem::size_of::<sem_t>(),
4494        PROT_READ | PROT_WRITE,
4495        MAP_SHARED,
4496        fd as i32,
4497        0,
4498    );
4499    sys_close(fd);
4500    if map == MMAP_FAILED {
4501        semtab_lock();
4502        SEMTAB[slot as usize].sem = core::ptr::null_mut();
4503        semtab_unlock();
4504        return core::ptr::null_mut();
4505    }
4506    let st_ino = get_ino(-1, buf.as_ptr());
4507    sem_register(map as *mut sem_t, st_ino, slot)
4508}
4509
4510unsafe fn get_ino(_fd_hint: c_int, path: *const u8) -> u64 {
4511    let mut st: Stat = core::mem::zeroed();
4512    if sys_newfstatat(AT_FDCWD, path as *const c_char, &mut st as *mut Stat as *mut u8, 0) == 0 {
4513        st.st_ino
4514    } else {
4515        0
4516    }
4517}
4518
4519unsafe fn sem_register(map: *mut sem_t, ino: u64, slot_hint: c_int) -> *mut sem_t {
4520    semtab_lock();
4521    // check if already mapped (by inode)
4522    for i in 0..SEMTAB_LEN {
4523        if SEMTAB[i].ino == ino && !SEMTAB[i].sem.is_null() && SEMTAB[i].sem != !0usize as *mut sem_t {
4524            // already mapped: unmap new, use existing, release hint slot
4525            sys_munmap(map as *mut u8, core::mem::size_of::<sem_t>());
4526            SEMTAB[slot_hint as usize].sem = core::ptr::null_mut();
4527            SEMTAB[i].refcnt += 1;
4528            let ret = SEMTAB[i].sem;
4529            semtab_unlock();
4530            return ret;
4531        }
4532    }
4533    // new entry
4534    SEMTAB[slot_hint as usize].sem = map;
4535    SEMTAB[slot_hint as usize].ino = ino;
4536    SEMTAB[slot_hint as usize].refcnt = 1;
4537    semtab_unlock();
4538    map
4539}
4540
4541const SEMTAB_LEN: usize = SEM_NSEMS_MAX;
4542
4543#[no_mangle]
4544pub unsafe extern "C" fn sem_close(sem: *mut sem_t) -> c_int {
4545    if sem.is_null() {
4546        ERRNO!() = EINVAL;
4547        return -1;
4548    }
4549    semtab_lock();
4550    for i in 0..SEMTAB_LEN {
4551        if SEMTAB[i].sem == sem {
4552            if SEMTAB[i].refcnt == 0 {
4553                semtab_unlock();
4554                ERRNO!() = EINVAL;
4555                return -1;
4556            }
4557            SEMTAB[i].refcnt -= 1;
4558            if SEMTAB[i].refcnt == 0 {
4559                SEMTAB[i].sem = core::ptr::null_mut();
4560                SEMTAB[i].ino = 0;
4561                semtab_unlock();
4562                sys_munmap(sem as *mut u8, core::mem::size_of::<sem_t>());
4563                return 0;
4564            }
4565            semtab_unlock();
4566            return 0;
4567        }
4568    }
4569    semtab_unlock();
4570    ERRNO!() = EINVAL;
4571    -1
4572}
4573
4574#[no_mangle]
4575pub unsafe extern "C" fn sem_unlink(name: *const c_char) -> c_int {
4576    shm_unlink(name)
4577}
4578
4579// --- pthread_once ---
4580#[no_mangle]
4581pub unsafe extern "C" fn pthread_once(control: *mut pthread_once_t, init_routine: Option<unsafe extern "C" fn()>) -> c_int {
4582    if a_load(control) == 2 { return 0; }
4583    loop {
4584        match a_cas(control, 0, 1) {
4585            0 => {
4586                if let Some(f) = init_routine { f(); }
4587                if a_swap(control, 2) == 3 { futex_wake(control, -1); }
4588                return 0;
4589            }
4590            1 => { a_cas(control, 1, 3); }
4591            3 => { futex_wait(control, 3); }
4592            _ => { return 0; }
4593        }
4594    }
4595}
4596
4597// --- pthread_key_* ---
4598#[no_mangle]
4599pub unsafe extern "C" fn pthread_key_create(key: *mut pthread_key_t, dtor: Option<unsafe extern "C" fn(*mut c_void)>) -> c_int {
4600    let start = NEXT_KEY.load(Ordering::Relaxed);
4601    let mut j = start;
4602    loop {
4603        if KEY_DTORS[j].is_none() {
4604            KEY_DTORS[j] = dtor;
4605            NEXT_KEY.store((j + 1) % PTHREAD_KEYS_MAX, Ordering::Relaxed);
4606            *key = j as pthread_key_t;
4607            return 0;
4608        }
4609        j = (j + 1) % PTHREAD_KEYS_MAX;
4610        if j == start { return EAGAIN; }
4611    }
4612}
4613#[no_mangle]
4614pub unsafe extern "C" fn pthread_key_delete(key: pthread_key_t) -> c_int {
4615    if key as usize >= PTHREAD_KEYS_MAX {
4616        return EINVAL;
4617    }
4618    KEY_DTORS[key as usize] = None;
4619    let count = thread_slot_count();
4620    let mut i = 0usize;
4621    while i < count {
4622        let slot = thread_slot_at(i);
4623        if !slot.is_null() && core::ptr::read_volatile(&raw const (*slot).tid) > 0 {
4624            (*slot).tsd[key as usize] = core::ptr::null_mut();
4625        }
4626        i += 1;
4627    }
4628    0
4629}
4630#[no_mangle]
4631pub unsafe extern "C" fn pthread_getspecific(key: pthread_key_t) -> *mut c_void {
4632    if key as usize >= PTHREAD_KEYS_MAX {
4633        return core::ptr::null_mut();
4634    }
4635    if let Some(slot) = find_thread() { slot.tsd[key as usize] } else { core::ptr::null_mut() }
4636}
4637#[no_mangle]
4638pub unsafe extern "C" fn pthread_setspecific(key: pthread_key_t, value: *const c_void) -> c_int {
4639    if key as usize >= PTHREAD_KEYS_MAX {
4640        ERRNO!() = EINVAL;
4641        return EINVAL;
4642    }
4643    if let Some(slot) = find_thread() {
4644        slot.tsd[key as usize] = value as *mut c_void;
4645        0
4646    } else { EINVAL }
4647}
4648
4649// --- pthread_cancel/state ---
4650unsafe fn run_cleanup_handlers(slot: &mut Thread) {
4651    let mut cb = slot.cancelbuf;
4652    while !cb.is_null() {
4653        let cur = &*cb;
4654        let f = cur.__f;
4655        let x = cur.__x;
4656        cb = cur.__next;
4657        if let Some(func) = f {
4658            func(x);
4659        }
4660    }
4661    slot.cancelbuf = core::ptr::null_mut();
4662}
4663
4664unsafe fn do_cancel() -> ! {
4665    if let Some(slot) = find_thread() {
4666        run_cleanup_handlers(slot);
4667        slot.result = !0usize as *mut c_void; // PTHREAD_CANCELED
4668        slot.detach_state = DT_EXITED;
4669        futex_wake(&raw mut slot.detach_state, 1);
4670    }
4671    sys_exit_thread(0);
4672}
4673
4674extern "C" fn cancel_handler(_sig: c_int) {
4675    unsafe {
4676        if let Some(slot) = find_thread() {
4677            // In asynchronous mode, cancel immediately from the signal handler.
4678            // In deferred mode, the signal just interrupts blocking syscalls so
4679            // the next cancellation point can act on the pending request.
4680            if slot.cancel != 0
4681                && slot.cancel_state == PTHREAD_CANCEL_ENABLE
4682                && slot.cancel_type == PTHREAD_CANCEL_ASYNCHRONOUS
4683            {
4684                do_cancel();
4685            }
4686        }
4687    }
4688}
4689
4690static CANCEL_INIT: AtomicI32 = AtomicI32::new(0);
4691
4692unsafe fn ensure_cancel_handler() {
4693    if CANCEL_INIT.swap(1, Ordering::AcqRel) == 0 {
4694        let act = KSigAction {
4695            sa_handler: cancel_handler as *const () as usize,
4696            sa_flags: SA_RESTORER,
4697            sa_restorer: sig_restorer as *const () as usize,
4698            sa_mask: [!0u64],
4699        };
4700        sys_rt_sigaction(SIGCANCEL, &act as *const KSigAction, core::ptr::null_mut(), 8);
4701    }
4702}
4703
4704#[no_mangle]
4705pub unsafe extern "C" fn pthread_cancel(thread: PthreadT) -> c_int {
4706    let slot = thread as *mut Thread;
4707    if slot.is_null() { return EINVAL; }
4708    ensure_cancel_handler();
4709    a_store(&raw mut (*slot).cancel, 1);
4710    let tid = (*slot).tid;
4711    if tid > 0 {
4712        sys_tgkill(sys_getpid() as c_int, tid, SIGCANCEL);
4713    }
4714    0
4715}
4716#[no_mangle]
4717pub unsafe extern "C" fn pthread_setcancelstate(state: c_int, oldstate: *mut c_int) -> c_int {
4718    if state != PTHREAD_CANCEL_ENABLE && state != PTHREAD_CANCEL_DISABLE { return EINVAL; }
4719    if let Some(slot) = find_thread() {
4720        if !oldstate.is_null() { *oldstate = slot.cancel_state; }
4721        slot.cancel_state = state;
4722        0
4723    } else { EINVAL }
4724}
4725#[no_mangle]
4726pub unsafe extern "C" fn pthread_setcanceltype(type_: c_int, oldtype: *mut c_int) -> c_int {
4727    if type_ != PTHREAD_CANCEL_DEFERRED && type_ != PTHREAD_CANCEL_ASYNCHRONOUS { return EINVAL; }
4728    if let Some(slot) = find_thread() {
4729        if !oldtype.is_null() { *oldtype = slot.cancel_type; }
4730        slot.cancel_type = type_;
4731        0
4732    } else { EINVAL }
4733}
4734#[no_mangle]
4735pub unsafe extern "C" fn pthread_testcancel() {
4736    if let Some(slot) = find_thread() {
4737        if slot.cancel != 0 && slot.cancel_state == PTHREAD_CANCEL_ENABLE {
4738            do_cancel();
4739        }
4740    }
4741}
4742
4743#[no_mangle]
4744pub unsafe extern "C" fn _pthread_cleanup_push(cb: *mut __ptcb, f: Option<unsafe extern "C" fn(*mut c_void)>, x: *mut c_void) {
4745    (*cb).__f = f;
4746    (*cb).__x = x;
4747    if let Some(slot) = find_thread() {
4748        (*cb).__next = slot.cancelbuf;
4749        slot.cancelbuf = cb;
4750    } else {
4751        (*cb).__next = core::ptr::null_mut();
4752    }
4753}
4754
4755#[no_mangle]
4756pub unsafe extern "C" fn _pthread_cleanup_pop(cb: *mut __ptcb, run: c_int) {
4757    if let Some(slot) = find_thread() {
4758        slot.cancelbuf = (*cb).__next;
4759    }
4760    if run != 0 {
4761        if let Some(f) = (*cb).__f {
4762            f((*cb).__x);
4763        }
4764    }
4765}
4766
4767#[no_mangle]
4768pub unsafe extern "C" fn pthread_kill(thread: PthreadT, sig: c_int) -> c_int {
4769    let slot = thread as *mut Thread;
4770    if slot.is_null() { return EINVAL; }
4771    let tid = (*slot).tid;
4772    if tid <= 0 { return EINVAL; }
4773    if sys_tgkill(sys_getpid() as c_int, tid, sig) < 0 { -1 } else { 0 }
4774}
4775
4776#[no_mangle]
4777pub unsafe extern "C" fn pthread_sigmask(how: c_int, set: *const SigSetT, oldset: *mut SigSetT) -> c_int {
4778    // POSIX pthread functions return the error number itself, not -1/errno.
4779    if sigprocmask(how, set, oldset) < 0 { ERRNO!() } else { 0 }
4780}
4781
4782
4783#[repr(C)]
4784pub struct lconv {
4785    pub decimal_point: *mut c_char,
4786    pub thousands_sep: *mut c_char,
4787    pub grouping: *mut c_char,
4788    pub int_curr_symbol: *mut c_char,
4789    pub currency_symbol: *mut c_char,
4790    pub mon_decimal_point: *mut c_char,
4791    pub mon_thousands_sep: *mut c_char,
4792    pub mon_grouping: *mut c_char,
4793    pub positive_sign: *mut c_char,
4794    pub negative_sign: *mut c_char,
4795    pub int_frac_digits: c_char,
4796    pub frac_digits: c_char,
4797    pub p_cs_precedes: c_char,
4798    pub p_sep_by_space: c_char,
4799    pub n_cs_precedes: c_char,
4800    pub n_sep_by_space: c_char,
4801    pub p_sign_posn: c_char,
4802    pub n_sign_posn: c_char,
4803    pub int_p_cs_precedes: c_char,
4804    pub int_p_sep_by_space: c_char,
4805    pub int_n_cs_precedes: c_char,
4806    pub int_n_sep_by_space: c_char,
4807    pub int_p_sign_posn: c_char,
4808    pub int_n_sign_posn: c_char,
4809}
4810
4811static UTF8_NAME: [u8; 6] = [b'U', b'T', b'F', b'-', b'8', 0];
4812static C_NAME: [u8; 2] = [b'C', 0];
4813static mut LOCALE_NAME: *const c_char = C_NAME.as_ptr() as *const c_char;
4814static mut LOCALE_CTYPE_UTF8: bool = true;
4815static mut EMPTY_STR: [c_char; 1] = [0];
4816static mut DECIMAL_POINT: [c_char; 2] = [b'.' as c_char, 0];
4817static mut LCONV: lconv = lconv {
4818    decimal_point: core::ptr::null_mut(),
4819    thousands_sep: core::ptr::null_mut(),
4820    grouping: core::ptr::null_mut(),
4821    int_curr_symbol: core::ptr::null_mut(),
4822    currency_symbol: core::ptr::null_mut(),
4823    mon_decimal_point: core::ptr::null_mut(),
4824    mon_thousands_sep: core::ptr::null_mut(),
4825    mon_grouping: core::ptr::null_mut(),
4826    positive_sign: core::ptr::null_mut(),
4827    negative_sign: core::ptr::null_mut(),
4828    int_frac_digits: (-1i32) as c_char,
4829    frac_digits: (-1i32) as c_char,
4830    p_cs_precedes: (-1i32) as c_char,
4831    p_sep_by_space: (-1i32) as c_char,
4832    n_cs_precedes: (-1i32) as c_char,
4833    n_sep_by_space: (-1i32) as c_char,
4834    p_sign_posn: (-1i32) as c_char,
4835    n_sign_posn: (-1i32) as c_char,
4836    int_p_cs_precedes: (-1i32) as c_char,
4837    int_p_sep_by_space: (-1i32) as c_char,
4838    int_n_cs_precedes: (-1i32) as c_char,
4839    int_n_sep_by_space: (-1i32) as c_char,
4840    int_p_sign_posn: (-1i32) as c_char,
4841    int_n_sign_posn: (-1i32) as c_char,
4842};
4843
4844unsafe fn cstr_contains_ci(s: *const u8, needle: &[u8]) -> bool {
4845    let len = strlen(s as *const c_char) as usize;
4846    let s_slice = core::slice::from_raw_parts(s, len);
4847    if needle.len() > len { return false; }
4848    for i in 0..=len - needle.len() {
4849        if s_slice[i..i + needle.len()].eq_ignore_ascii_case(needle) {
4850            return true;
4851        }
4852    }
4853    false
4854}
4855
4856#[no_mangle]
4857pub unsafe extern "C" fn setlocale(_category: c_int, locale: *const c_char) -> *mut c_char {
4858    if locale.is_null() || *locale == 0 {
4859        return LOCALE_NAME as *mut c_char;
4860    }
4861    let name = locale as *const u8;
4862    if strcmp(name, b"C\0".as_ptr()) == 0 || strcmp(name, b"POSIX\0".as_ptr()) == 0 {
4863        LOCALE_CTYPE_UTF8 = false;
4864        return LOCALE_NAME as *mut c_char;
4865    }
4866    if cstr_contains_ci(name, b"UTF-8") || cstr_contains_ci(name, b"UTF8") {
4867        LOCALE_CTYPE_UTF8 = true;
4868        return LOCALE_NAME as *mut c_char;
4869    }
4870    core::ptr::null_mut()
4871}
4872
4873#[no_mangle]
4874pub unsafe extern "C" fn localeconv() -> *mut lconv {
4875    let empty = core::ptr::addr_of_mut!(EMPTY_STR) as *mut c_char;
4876    let lconv = core::ptr::addr_of_mut!(LCONV);
4877    (*lconv).decimal_point = core::ptr::addr_of_mut!(DECIMAL_POINT) as *mut c_char;
4878    (*lconv).thousands_sep = empty;
4879    (*lconv).grouping = empty;
4880    (*lconv).int_curr_symbol = empty;
4881    (*lconv).currency_symbol = empty;
4882    (*lconv).mon_decimal_point = empty;
4883    (*lconv).mon_thousands_sep = empty;
4884    (*lconv).mon_grouping = empty;
4885    (*lconv).positive_sign = empty;
4886    (*lconv).negative_sign = empty;
4887    lconv
4888}
4889
4890pub type locale_t = *mut c_void;
4891static mut CURRENT_LOCALE: locale_t = LC_GLOBAL_LOCALE;
4892
4893static mut C_LOCALE_STORAGE: c_int = 0;
4894const C_LOCALE: locale_t = core::ptr::addr_of_mut!(C_LOCALE_STORAGE) as locale_t;
4895const LC_GLOBAL_LOCALE: locale_t = usize::MAX as locale_t;
4896
4897#[no_mangle]
4898pub unsafe extern "C" fn newlocale(_mask: c_int, name: *const c_char, base: locale_t) -> locale_t {
4899    if !name.is_null() && *name != 0 {
4900        let n = name as *const u8;
4901        if strcmp(n, b"C\0".as_ptr()) != 0
4902            && strcmp(n, b"POSIX\0".as_ptr()) != 0
4903        {
4904            return core::ptr::null_mut();
4905        }
4906    }
4907    if base.is_null() || base == C_LOCALE || base == LC_GLOBAL_LOCALE {
4908        C_LOCALE
4909    } else {
4910        core::ptr::null_mut()
4911    }
4912}
4913
4914#[no_mangle]
4915pub unsafe extern "C" fn freelocale(_loc: locale_t) {}
4916
4917#[no_mangle]
4918pub unsafe extern "C" fn uselocale(loc: locale_t) -> locale_t {
4919    let old = CURRENT_LOCALE;
4920    if !loc.is_null() {
4921        CURRENT_LOCALE = loc;
4922    }
4923    old
4924}
4925
4926#[no_mangle]
4927pub unsafe extern "C" fn duplocale(loc: locale_t) -> locale_t {
4928    if loc.is_null() {
4929        return core::ptr::null_mut();
4930    }
4931    C_LOCALE
4932}
4933
4934const NL_ITEM_CODESET: c_int = 14;
4935const NL_ITEM_RADIXCHAR: c_int = 0x10000;
4936const NL_ITEM_THOUSEP: c_int = 0x10001;
4937const NL_ITEM_YESEXPR: c_int = 0x50000;
4938const NL_ITEM_NOEXPR: c_int = 0x50001;
4939
4940const C_TIME_STRINGS: &[u8] = b"Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat\0\
4941Sunday\0Monday\0Tuesday\0Wednesday\0Thursday\0Friday\0Saturday\0\
4942Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec\0\
4943January\0February\0March\0April\0May\0June\0July\0August\0\
4944September\0October\0November\0December\0\
4945AM\0PM\0\
4946%a %b %e %T %Y\0%m/%d/%y\0%H:%M:%S\0%I:%M:%S %p\0\
4947\0\0%m/%d/%y\00123456789\0%a %b %e %T %Y\0%H:%M:%S\0";
4948
4949const C_NUMERIC_STRINGS: &[u8] = b".\0\0";
4950const C_MESSAGES_STRINGS: &[u8] = b"^[yY]\0^[nN]\0";
4951
4952unsafe fn langinfo_str(table: *const u8, mut idx: c_int) -> *mut c_char {
4953    let mut p = table;
4954    while idx > 0 {
4955        while *p != 0 { p = p.add(1); }
4956        p = p.add(1);
4957        idx -= 1;
4958    }
4959    p as *mut c_char
4960}
4961
4962#[no_mangle]
4963pub unsafe extern "C" fn nl_langinfo(item: c_int) -> *mut c_char {
4964    if item == NL_ITEM_CODESET {
4965        return if LOCALE_CTYPE_UTF8 {
4966            b"UTF-8\0".as_ptr() as *mut c_char
4967        } else {
4968            b"US-ASCII\0".as_ptr() as *mut c_char
4969        };
4970    }
4971    let cat = item >> 16;
4972    let idx = item & 0xFFFF;
4973    match cat {
4974        1 => {
4975            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
4976            langinfo_str(C_NUMERIC_STRINGS.as_ptr(), idx)
4977        }
4978        2 => {
4979            if idx > 49 { return b"\0".as_ptr() as *mut c_char; }
4980            langinfo_str(C_TIME_STRINGS.as_ptr(), idx)
4981        }
4982        5 => {
4983            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
4984            langinfo_str(C_MESSAGES_STRINGS.as_ptr(), idx)
4985        }
4986        _ => b"\0".as_ptr() as *mut c_char,
4987    }
4988}
4989
4990pub type nl_catd = *mut c_void;
4991
4992#[no_mangle]
4993pub unsafe extern "C" fn catopen(_name: *const c_char, _oflag: c_int) -> nl_catd {
4994    !0usize as nl_catd
4995}
4996
4997#[no_mangle]
4998pub unsafe extern "C" fn catclose(_catd: nl_catd) -> c_int { 0 }
4999
5000#[no_mangle]
5001pub unsafe extern "C" fn catgets(catd: nl_catd, _set_id: c_int, _msg_id: c_int, s: *const c_char) -> *mut c_char {
5002    if catd == !0usize as nl_catd {
5003        ERRNO!() = EBADF;
5004        return s as *mut c_char;
5005    }
5006    s as *mut c_char
5007}
5008
5009pub type IconvT = *mut c_void;
5010
5011const UNICODE_SURROGATE_START: u32 = 0xD800;
5012const UNICODE_HIGH_SURROGATE_END: u32 = 0xDBFF;
5013const UNICODE_LOW_SURROGATE_START: u32 = 0xDC00;
5014const UNICODE_SURROGATE_END: u32 = 0xDFFF;
5015const UNICODE_SURROGATE_END_EXCL: u32 = 0xE000;
5016const UNICODE_SUPPLEMENTARY_BASE: u32 = 0x10000;
5017const UNICODE_SUPPLEMENTARY_SIZE: u32 = 0x100000;
5018const UNICODE_MAX: u32 = 0x110000;
5019
5020const ENC_UTF8: i32 = 1;
5021const ENC_UTF16LE: i32 = 2;
5022const ENC_UTF16BE: i32 = 3;
5023const ENC_UTF32LE: i32 = 4;
5024const ENC_UTF32BE: i32 = 5;
5025const ENC_WCHAR_T: i32 = 6;
5026const ENC_ASCII: i32 = 7;
5027const ENC_LATIN1: i32 = 8;
5028const ENC_WIN1252: i32 = 9;
5029const ENC_WIN1251: i32 = 10;
5030const ENC_KOI8R: i32 = 11;
5031const ENC_GBK: i32 = 12;
5032const ENC_GB2312: i32 = 13;
5033const ENC_BIG5: i32 = 14;
5034const ENC_EUCJP: i32 = 15;
5035const ENC_SHIFTJIS: i32 = 16;
5036const ENC_ISO8859_2: i32 = 17;
5037const ENC_ISO8859_3: i32 = 18;
5038const ENC_ISO8859_4: i32 = 19;
5039const ENC_ISO8859_5: i32 = 20;
5040const ENC_ISO8859_6: i32 = 21;
5041const ENC_ISO8859_7: i32 = 22;
5042const ENC_ISO8859_8: i32 = 23;
5043const ENC_ISO8859_9: i32 = 24;
5044const ENC_ISO8859_10: i32 = 25;
5045const ENC_ISO8859_11: i32 = 26;
5046const ENC_ISO8859_13: i32 = 27;
5047const ENC_ISO8859_14: i32 = 28;
5048const ENC_ISO8859_15: i32 = 29;
5049const ENC_ISO8859_16: i32 = 30;
5050
5051include!("iconv_iso8859.rs");
5052
5053fn make_cd(from: i32, to: i32) -> IconvT {
5054    ((from as usize) << 16 | (to as usize) << 1 | 1) as IconvT
5055}
5056fn extract_from(cd: IconvT) -> i32 {
5057    ((cd as usize) >> 16) as i32
5058}
5059fn extract_to(cd: IconvT) -> i32 {
5060    (((cd as usize) >> 1) & 0x7fff) as i32
5061}
5062
5063unsafe fn match_name(input: *const u8, target: &[u8]) -> bool {
5064    let mut i = input;
5065    let mut j = 0;
5066    while *i != 0 && j < target.len() {
5067        let mut c = *i;
5068        if !c.is_ascii_alphanumeric() { i = i.add(1); continue; }
5069        c = c.to_ascii_lowercase();
5070        if c != target[j] { return false; }
5071        i = i.add(1);
5072        j += 1;
5073    }
5074    while *i != 0 && !(*i).is_ascii_alphanumeric() { i = i.add(1); }
5075    *i == 0 && j == target.len()
5076}
5077
5078const ENCODING_ALIASES: &[(&[&[u8]], i32)] = &[
5079    (&[b"utf8", b"utf-8", b"char"], ENC_UTF8),
5080    (&[b"utf16le", b"utf-16le"], ENC_UTF16LE),
5081    (&[b"utf16be", b"utf-16be"], ENC_UTF16BE),
5082    (&[b"utf32le", b"utf-32le", b"ucs4le"], ENC_UTF32LE),
5083    (&[b"utf32be", b"utf-32be", b"ucs4be"], ENC_UTF32BE),
5084    (&[b"wchart", b"wchar-t"], ENC_WCHAR_T),
5085    (&[b"ascii", b"usascii", b"iso646"], ENC_ASCII),
5086    (&[b"iso88591", b"iso-8859-1", b"latin1"], ENC_LATIN1),
5087    (&[b"iso88592", b"iso-8859-2"], ENC_ISO8859_2),
5088    (&[b"iso88593", b"iso-8859-3"], ENC_ISO8859_3),
5089    (&[b"iso88594", b"iso-8859-4"], ENC_ISO8859_4),
5090    (&[b"iso88595", b"iso-8859-5"], ENC_ISO8859_5),
5091    (&[b"iso88596", b"iso-8859-6"], ENC_ISO8859_6),
5092    (&[b"iso88597", b"iso-8859-7"], ENC_ISO8859_7),
5093    (&[b"iso88598", b"iso-8859-8"], ENC_ISO8859_8),
5094    (&[b"iso88599", b"iso-8859-9"], ENC_ISO8859_9),
5095    (&[b"iso885910", b"iso-8859-10"], ENC_ISO8859_10),
5096    (&[b"iso885911", b"iso-8859-11", b"tis620"], ENC_ISO8859_11),
5097    (&[b"iso885913", b"iso-8859-13"], ENC_ISO8859_13),
5098    (&[b"iso885914", b"iso-8859-14"], ENC_ISO8859_14),
5099    (&[b"iso885915", b"iso-8859-15"], ENC_ISO8859_15),
5100    (&[b"iso885916", b"iso-8859-16"], ENC_ISO8859_16),
5101    (&[b"cp1252", b"windows1252", b"windows-1252"], ENC_WIN1252),
5102    (&[b"cp1251", b"windows1251", b"windows-1251"], ENC_WIN1251),
5103    (&[b"koi8r", b"koi8-r"], ENC_KOI8R),
5104    (&[b"gbk", b"cp936"], ENC_GBK),
5105    (&[b"gb2312"], ENC_GB2312),
5106    (&[b"big5", b"bigfive", b"cp950"], ENC_BIG5),
5107    (&[b"eucjp", b"euc-jp"], ENC_EUCJP),
5108    (&[b"shiftjis", b"sjis", b"cp932"], ENC_SHIFTJIS),
5109];
5110
5111unsafe fn find_encoding(name: *const u8) -> i32 {
5112    if name.is_null() { return -1; }
5113    for &(aliases, enc) in ENCODING_ALIASES {
5114        for alias in aliases {
5115            if match_name(name, alias) {
5116                return enc;
5117            }
5118        }
5119    }
5120    -1
5121}
5122
5123fn uni_to_jis(c: u32) -> u16 {
5124    let mut b = 0usize;
5125    let mut nel = REV_JIS.len();
5126    loop {
5127        let i = nel / 2;
5128        let j = REV_JIS[b + i] as usize;
5129        let row = j / 256;
5130        let col = j % 256;
5131        let d = JIS0208[row * 94 + col] as u32;
5132        if d == c { return (j as u16) + 0x2121; }
5133        if nel == 1 { return 0; }
5134        if c < d { nel /= 2; }
5135        else { b += i; nel -= nel / 2; }
5136    }
5137}
5138
5139fn iso8859_decode_table(enc: i32) -> Option<&'static [u32; 128]> {
5140    match enc {
5141        ENC_ISO8859_2 => Some(&ISO8859_2_TO_U),
5142        ENC_ISO8859_3 => Some(&ISO8859_3_TO_U),
5143        ENC_ISO8859_4 => Some(&ISO8859_4_TO_U),
5144        ENC_ISO8859_5 => Some(&ISO8859_5_TO_U),
5145        ENC_ISO8859_6 => Some(&ISO8859_6_TO_U),
5146        ENC_ISO8859_7 => Some(&ISO8859_7_TO_U),
5147        ENC_ISO8859_8 => Some(&ISO8859_8_TO_U),
5148        ENC_ISO8859_9 => Some(&ISO8859_9_TO_U),
5149        ENC_ISO8859_10 => Some(&ISO8859_10_TO_U),
5150        ENC_ISO8859_11 => Some(&ISO8859_11_TO_U),
5151        ENC_ISO8859_13 => Some(&ISO8859_13_TO_U),
5152        ENC_ISO8859_14 => Some(&ISO8859_14_TO_U),
5153        ENC_ISO8859_15 => Some(&ISO8859_15_TO_U),
5154        ENC_ISO8859_16 => Some(&ISO8859_16_TO_U),
5155        _ => None,
5156    }
5157}
5158
5159unsafe fn iconv_decode(enc: i32, src: *const u8, src_left: usize) -> (u32, usize, c_int) {
5160    if src_left == 0 { return (0, 0, EINVAL); }
5161    if let Some(table) = iso8859_decode_table(enc) {
5162        return (iso8859_to_u(table, *src), 1, 0);
5163    }
5164    match enc {
5165        ENC_UTF8 => {
5166            let c = *src;
5167            if c < 128 { return (c as u32, 1, 0); }
5168            if c < 0xC2 { return (0, 0, EILSEQ); }
5169            if c < 0xE0 {
5170                if src_left < 2 || (*src.add(1) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
5171                return (((c as u32 & 0x1F) << 6) | (*src.add(1) as u32 & 0x3F), 2, 0);
5172            }
5173            if c < 0xF0 {
5174                if src_left < 3 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
5175                let cp = ((c as u32 & 0x0F) << 12) | ((*src.add(1) as u32 & 0x3F) << 6) | (*src.add(2) as u32 & 0x3F);
5176                if cp < 0x800 { return (0, 0, EILSEQ); }
5177                return (cp, 3, 0);
5178            }
5179            if c < 0xF8 {
5180                if src_left < 4 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 || (*src.add(3) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
5181                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);
5182                if cp < UNICODE_SUPPLEMENTARY_BASE || cp >= UNICODE_MAX { return (0, 0, EILSEQ); }
5183                return (cp, 4, 0);
5184            }
5185            (0, 0, EILSEQ)
5186        }
5187        ENC_UTF16LE => {
5188            if src_left < 2 { return (0, 0, EINVAL); }
5189            let c = (*src as u32) | ((*src.add(1) as u32) << 8);
5190            if c >= UNICODE_SURROGATE_START && c <= UNICODE_HIGH_SURROGATE_END {
5191                if src_left < 4 { return (0, 0, EINVAL); }
5192                let d = (*src.add(2) as u32) | ((*src.add(3) as u32) << 8);
5193                if d < UNICODE_LOW_SURROGATE_START || d > UNICODE_SURROGATE_END { return (0, 0, EILSEQ); }
5194                return (((c - UNICODE_SURROGATE_START) << 10) + (d - UNICODE_LOW_SURROGATE_START) + UNICODE_SUPPLEMENTARY_BASE, 4, 0);
5195            }
5196            if c >= UNICODE_LOW_SURROGATE_START && c <= UNICODE_SURROGATE_END { return (0, 0, EILSEQ); }
5197            (c, 2, 0)
5198        }
5199        ENC_UTF16BE => {
5200            if src_left < 2 { return (0, 0, EINVAL); }
5201            let c = ((*src as u32) << 8) | (*src.add(1) as u32);
5202            if c >= UNICODE_SURROGATE_START && c <= UNICODE_HIGH_SURROGATE_END {
5203                if src_left < 4 { return (0, 0, EINVAL); }
5204                let d = ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
5205                if d < UNICODE_LOW_SURROGATE_START || d > UNICODE_SURROGATE_END { return (0, 0, EILSEQ); }
5206                return (((c - UNICODE_SURROGATE_START) << 10) + (d - UNICODE_LOW_SURROGATE_START) + UNICODE_SUPPLEMENTARY_BASE, 4, 0);
5207            }
5208            if c >= UNICODE_LOW_SURROGATE_START && c <= UNICODE_SURROGATE_END { return (0, 0, EILSEQ); }
5209            (c, 2, 0)
5210        }
5211        ENC_UTF32LE => {
5212            if src_left < 4 { return (0, 0, EINVAL); }
5213            let c = (*src as u32) | ((*src.add(1) as u32) << 8) | ((*src.add(2) as u32) << 16) | ((*src.add(3) as u32) << 24);
5214            if c >= UNICODE_SURROGATE_START && c < UNICODE_SURROGATE_END_EXCL { return (0, 0, EILSEQ); }
5215            if c >= UNICODE_MAX { return (0, 0, EILSEQ); }
5216            (c, 4, 0)
5217        }
5218        ENC_UTF32BE => {
5219            if src_left < 4 { return (0, 0, EINVAL); }
5220            let c = ((*src as u32) << 24) | ((*src.add(1) as u32) << 16) | ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
5221            if c >= UNICODE_SURROGATE_START && c < UNICODE_SURROGATE_END_EXCL { return (0, 0, EILSEQ); }
5222            if c >= UNICODE_MAX { return (0, 0, EILSEQ); }
5223            (c, 4, 0)
5224        }
5225        ENC_WCHAR_T => {
5226            if src_left < 4 { return (0, 0, EINVAL); }
5227            let c = core::ptr::read_unaligned(src as *const u32);
5228            if c >= UNICODE_SURROGATE_START && c < UNICODE_SURROGATE_END_EXCL { return (0, 0, EILSEQ); }
5229            if c >= UNICODE_MAX { return (0, 0, EILSEQ); }
5230            (c, 4, 0)
5231        }
5232        ENC_ASCII => {
5233            let c = *src as u32;
5234            if c >= 128 { return (0, 0, EILSEQ); }
5235            (c, 1, 0)
5236        }
5237        ENC_LATIN1 => (*src as u32, 1, 0),
5238        ENC_WIN1252 => {
5239            let b = *src;
5240            if b < 128 { return (b as u32, 1, 0); }
5241            (WIN1252_TO_U[b as usize - 128], 1, 0)
5242        }
5243        ENC_GBK | ENC_GB2312 => {
5244            let c = *src;
5245            if c < 128 { return (c as u32, 1, 0); }
5246            if c == 128 { return (0x20AC, 1, 0); }
5247            if src_left < 2 { return (0, 0, EINVAL); }
5248            let d = *src.add(1);
5249            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
5250            let row = (c as usize).wrapping_sub(0x81);
5251            if row >= 126 { return (0, 0, EILSEQ); }
5252            let mut col = (d as usize) - 0x40;
5253            if col > 63 { col -= 1; }
5254            let cp = GB18030_TABLE[row * 190 + col] as u32;
5255            if cp == 0 { return (0, 0, EILSEQ); }
5256            (cp, 2, 0)
5257        }
5258        ENC_BIG5 => {
5259            let c = *src;
5260            if c < 128 { return (c as u32, 1, 0); }
5261            if src_left < 2 { return (0, 0, EINVAL); }
5262            let d = *src.add(1);
5263            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
5264            let mut col = (d as usize) - 0x40;
5265            if col > 0x3E { col -= 0x22; }
5266            if c >= 0xA1 && c < 0xFA {
5267                let row = (c as usize) - 0xA1;
5268                if row >= 89 { return (0, 0, EILSEQ); }
5269                let cp = BIG5_TABLE[row * 157 + col] as u32;
5270                if cp == 0 { return (0, 0, EILSEQ); }
5271                return (cp, 2, 0);
5272            }
5273            (0, 0, EILSEQ)
5274        }
5275        ENC_EUCJP => {
5276            let c = *src;
5277            if c < 128 { return (c as u32, 1, 0); }
5278            if c == 0x8E {
5279                if src_left < 2 { return (0, 0, EINVAL); }
5280                let d = *src.add(1);
5281                if d < 0xA1 || d > 0xDF { return (0, 0, EILSEQ); }
5282                return ((d as u32) + 0xFF61 - 0xA1, 2, 0);
5283            }
5284            if c < 0xA1 { return (0, 0, EILSEQ); }
5285            if src_left < 2 { return (0, 0, EINVAL); }
5286            let d = *src.add(1);
5287            if d < 0xA1 || d > 0xFE { return (0, 0, EILSEQ); }
5288            let row = (c as usize) - 0xA1;
5289            let col = (d as usize) - 0xA1;
5290            if row >= 84 || col >= 94 { return (0, 0, EILSEQ); }
5291            let cp = JIS0208[row * 94 + col] as u32;
5292            if cp == 0 { return (0, 0, EILSEQ); }
5293            (cp, 2, 0)
5294        }
5295        ENC_SHIFTJIS => {
5296            let c = *src;
5297            if c < 128 { return (c as u32, 1, 0); }
5298            if c >= 0xA1 && c <= 0xDF { return ((c as u32) + 0xFF61 - 0xA1, 1, 0); }
5299            if src_left < 2 { return (0, 0, EINVAL); }
5300            let d = *src.add(1);
5301            if d < 0x40 || d == 0x7F || d > 0xFC { return (0, 0, EILSEQ); }
5302            let row = if c >= 129 && c <= 159 { (c as usize) - 129 }
5303                      else if c >= 224 && c <= 239 { (c as usize) - 193 }
5304                      else { return (0, 0, EILSEQ); };
5305            let (col, row_adj) = if d >= 64 && d <= 158 && d != 127 {
5306                let mut dd = d as usize;
5307                if dd > 127 { dd -= 1; }
5308                (dd - 64, row * 2)
5309            } else if d >= 159 && d <= 252 {
5310                ((d as usize) - 159, row * 2 + 1)
5311            } else {
5312                return (0, 0, EILSEQ);
5313            };
5314            if row_adj >= 84 { return (0, 0, EILSEQ); }
5315            let cp = JIS0208[row_adj * 94 + col] as u32;
5316            if cp == 0 { return (0, 0, EILSEQ); }
5317            (cp, 2, 0)
5318        }
5319        _ => (0, 0, EILSEQ),
5320    }
5321}
5322
5323unsafe fn encode_single_byte(
5324    table: &[u32; 128],
5325    c: u32,
5326    dst: *mut u8,
5327    dst_left: usize,
5328) -> (usize, c_int) {
5329    if let Some(b) = u_to_iso8859(table, c) {
5330        if dst_left < 1 { return (0, E2BIG); }
5331        *dst = b;
5332        (1, 0)
5333    } else {
5334        (0, EILSEQ)
5335    }
5336}
5337
5338unsafe fn iconv_encode(enc: i32, c: u32, dst: *mut u8, dst_left: usize) -> (usize, c_int) {
5339    // All ISO-8859 tables, Windows-1251 and KOI8-R share the same
5340    // ASCII-passthrough + reverse-table encoding.
5341    let single_byte_table = match enc {
5342        ENC_ISO8859_2 => Some(&ISO8859_2_TO_U),
5343        ENC_ISO8859_3 => Some(&ISO8859_3_TO_U),
5344        ENC_ISO8859_4 => Some(&ISO8859_4_TO_U),
5345        ENC_ISO8859_5 => Some(&ISO8859_5_TO_U),
5346        ENC_ISO8859_6 => Some(&ISO8859_6_TO_U),
5347        ENC_ISO8859_7 => Some(&ISO8859_7_TO_U),
5348        ENC_ISO8859_8 => Some(&ISO8859_8_TO_U),
5349        ENC_ISO8859_9 => Some(&ISO8859_9_TO_U),
5350        ENC_ISO8859_10 => Some(&ISO8859_10_TO_U),
5351        ENC_ISO8859_11 => Some(&ISO8859_11_TO_U),
5352        ENC_ISO8859_13 => Some(&ISO8859_13_TO_U),
5353        ENC_ISO8859_14 => Some(&ISO8859_14_TO_U),
5354        ENC_ISO8859_15 => Some(&ISO8859_15_TO_U),
5355        ENC_ISO8859_16 => Some(&ISO8859_16_TO_U),
5356        ENC_WIN1251 => Some(&WIN1251_TO_U),
5357        ENC_KOI8R => Some(&KOI8R_TO_U),
5358        _ => None,
5359    };
5360    if let Some(table) = single_byte_table {
5361        return encode_single_byte(table, c, dst, dst_left);
5362    }
5363
5364    match enc {
5365        ENC_UTF8 => {
5366            if c < 0x80 {
5367                if dst_left < 1 { return (0, E2BIG); }
5368                *dst = c as u8; return (1, 0);
5369            }
5370            if c < 0x800 {
5371                if dst_left < 2 { return (0, E2BIG); }
5372                *dst = (0xC0 | (c >> 6)) as u8;
5373                *dst.add(1) = (0x80 | (c & 0x3F)) as u8;
5374                return (2, 0);
5375            }
5376            if c < 0x10000 {
5377                if dst_left < 3 { return (0, E2BIG); }
5378                *dst = (0xE0 | (c >> 12)) as u8;
5379                *dst.add(1) = (0x80 | ((c >> 6) & 0x3F)) as u8;
5380                *dst.add(2) = (0x80 | (c & 0x3F)) as u8;
5381                return (3, 0);
5382            }
5383            if dst_left < 4 { return (0, E2BIG); }
5384            *dst = (0xF0 | (c >> 18)) as u8;
5385            *dst.add(1) = (0x80 | ((c >> 12) & 0x3F)) as u8;
5386            *dst.add(2) = (0x80 | ((c >> 6) & 0x3F)) as u8;
5387            *dst.add(3) = (0x80 | (c & 0x3F)) as u8;
5388            (4, 0)
5389        }
5390        ENC_UTF16LE => {
5391            if c < UNICODE_SUPPLEMENTARY_BASE {
5392                if dst_left < 2 { return (0, E2BIG); }
5393                *dst = (c & 0xFF) as u8;
5394                *dst.add(1) = (c >> 8) as u8;
5395                return (2, 0);
5396            }
5397            if dst_left < 4 { return (0, E2BIG); }
5398            let c = c - UNICODE_SUPPLEMENTARY_BASE;
5399            let hi = ((c >> 10) + UNICODE_SURROGATE_START) as u16;
5400            let lo = ((c & 0x3FF) + UNICODE_LOW_SURROGATE_START) as u16;
5401            *dst = (hi & 0xFF) as u8; *dst.add(1) = (hi >> 8) as u8;
5402            *dst.add(2) = (lo & 0xFF) as u8; *dst.add(3) = (lo >> 8) as u8;
5403            (4, 0)
5404        }
5405        ENC_UTF16BE => {
5406            if c < UNICODE_SUPPLEMENTARY_BASE {
5407                if dst_left < 2 { return (0, E2BIG); }
5408                *dst = (c >> 8) as u8;
5409                *dst.add(1) = (c & 0xFF) as u8;
5410                return (2, 0);
5411            }
5412            if dst_left < 4 { return (0, E2BIG); }
5413            let c = c - UNICODE_SUPPLEMENTARY_BASE;
5414            let hi = ((c >> 10) + UNICODE_SURROGATE_START) as u16;
5415            let lo = ((c & 0x3FF) + UNICODE_LOW_SURROGATE_START) as u16;
5416            *dst = (hi >> 8) as u8; *dst.add(1) = (hi & 0xFF) as u8;
5417            *dst.add(2) = (lo >> 8) as u8; *dst.add(3) = (lo & 0xFF) as u8;
5418            (4, 0)
5419        }
5420        ENC_UTF32LE => {
5421            if dst_left < 4 { return (0, E2BIG); }
5422            *dst = (c & 0xFF) as u8; *dst.add(1) = ((c >> 8) & 0xFF) as u8;
5423            *dst.add(2) = ((c >> 16) & 0xFF) as u8; *dst.add(3) = (c >> 24) as u8;
5424            (4, 0)
5425        }
5426        ENC_UTF32BE => {
5427            if dst_left < 4 { return (0, E2BIG); }
5428            *dst = (c >> 24) as u8; *dst.add(1) = ((c >> 16) & 0xFF) as u8;
5429            *dst.add(2) = ((c >> 8) & 0xFF) as u8; *dst.add(3) = (c & 0xFF) as u8;
5430            (4, 0)
5431        }
5432        ENC_WCHAR_T => {
5433            if dst_left < 4 { return (0, E2BIG); }
5434            core::ptr::write_unaligned(dst as *mut u32, c);
5435            (4, 0)
5436        }
5437        ENC_ASCII => {
5438            if c < 128 {
5439                if dst_left < 1 { return (0, E2BIG); }
5440                *dst = c as u8; return (1, 0);
5441            }
5442            (0, EILSEQ)
5443        }
5444        ENC_LATIN1 => {
5445            if c < 256 {
5446                if dst_left < 1 { return (0, E2BIG); }
5447                *dst = c as u8; return (1, 0);
5448            }
5449            (0, EILSEQ)
5450        }
5451        ENC_WIN1252 => {
5452            if c < 128 {
5453                if dst_left < 1 { return (0, E2BIG); }
5454                *dst = c as u8; return (1, 0);
5455            }
5456            if c >= 0xA0 && c <= 0xFF && WIN1252_TO_U[c as usize - 128] == c {
5457                if dst_left < 1 { return (0, E2BIG); }
5458                *dst = c as u8; return (1, 0);
5459            }
5460            for i in 0..128usize {
5461                if WIN1252_TO_U[i] == c {
5462                    if dst_left < 1 { return (0, E2BIG); }
5463                    *dst = (i + 128) as u8; return (1, 0);
5464                }
5465            }
5466            (0, EILSEQ)
5467        }
5468        ENC_GBK | ENC_GB2312 => {
5469            if c < 128 {
5470                if dst_left < 1 { return (0, E2BIG); }
5471                *dst = c as u8; return (1, 0);
5472            }
5473            if c == 0x20AC {
5474                if dst_left < 1 { return (0, E2BIG); }
5475                *dst = 128; return (1, 0);
5476            }
5477            for row in 0..126usize {
5478                for col in 0..190usize {
5479                    if GB18030_TABLE[row * 190 + col] as u32 == c {
5480                        if dst_left < 2 { return (0, E2BIG); }
5481                        *dst = (row + 0x81) as u8;
5482                        *dst.add(1) = if col <= 62 { (col + 0x40) as u8 } else { (col + 0x41) as u8 };
5483                        return (2, 0);
5484                    }
5485                }
5486            }
5487            (0, EILSEQ)
5488        }
5489        ENC_BIG5 => {
5490            if c < 128 {
5491                if dst_left < 1 { return (0, E2BIG); }
5492                *dst = c as u8; return (1, 0);
5493            }
5494            for row in 0..89usize {
5495                for col in 0..157usize {
5496                    if BIG5_TABLE[row * 157 + col] as u32 == c {
5497                        if dst_left < 2 { return (0, E2BIG); }
5498                        *dst = (row + 0xA1) as u8;
5499                        *dst.add(1) = if col <= 0x3E { (col + 0x40) as u8 } else { (col + 0x62) as u8 };
5500                        return (2, 0);
5501                    }
5502                }
5503            }
5504            (0, EILSEQ)
5505        }
5506        ENC_EUCJP => {
5507            if c < 128 {
5508                if dst_left < 1 { return (0, E2BIG); }
5509                *dst = c as u8; return (1, 0);
5510            }
5511            if c >= 0xFF61 && c <= 0xFF9F {
5512                if dst_left < 2 { return (0, E2BIG); }
5513                *dst = 0x8E;
5514                *dst.add(1) = (c - 0xFF61 + 0xA1) as u8;
5515                return (2, 0);
5516            }
5517            let jis = uni_to_jis(c);
5518            if jis == 0 { return (0, EILSEQ); }
5519            if dst_left < 2 { return (0, E2BIG); }
5520            *dst = ((jis >> 8) as u8).wrapping_add(0x80);
5521            *dst.add(1) = ((jis & 0xFF) as u8).wrapping_add(0x80);
5522            (2, 0)
5523        }
5524        ENC_SHIFTJIS => {
5525            if c < 128 {
5526                if dst_left < 1 { return (0, E2BIG); }
5527                *dst = c as u8; return (1, 0);
5528            }
5529            if c >= 0xFF61 && c <= 0xFF9F {
5530                if dst_left < 1 { return (0, E2BIG); }
5531                *dst = (c - 0xFF61 + 0xA1) as u8;
5532                return (1, 0);
5533            }
5534            let jis = uni_to_jis(c);
5535            if jis == 0 { return (0, EILSEQ); }
5536            if dst_left < 2 { return (0, E2BIG); }
5537            let r = (jis >> 8) as usize;
5538            let d = (jis & 0xFF) as usize;
5539            *dst = ((r + 1) / 2 + if r < 95 { 112 } else { 176 }) as u8;
5540            *dst.add(1) = if r % 2 == 1 { (d + 31 + d / 96) as u8 } else { (d + 126) as u8 };
5541            (2, 0)
5542        }
5543        _ => (0, EILSEQ),
5544    }
5545}
5546
5547#[no_mangle]
5548pub unsafe extern "C" fn iconv_open(tocode: *const c_char, fromcode: *const c_char) -> IconvT {
5549    let to = find_encoding(tocode as *const u8);
5550    let from = find_encoding(fromcode as *const u8);
5551    if to < 0 || from < 0 {
5552        ERRNO!() = EINVAL;
5553        return !0usize as IconvT;
5554    }
5555    make_cd(from, to)
5556}
5557
5558#[no_mangle]
5559pub unsafe extern "C" fn iconv(
5560    cd: IconvT,
5561    inbuf: *mut *mut c_char,
5562    inbytesleft: *mut SizeT,
5563    outbuf: *mut *mut c_char,
5564    outbytesleft: *mut SizeT,
5565) -> SizeT {
5566    if cd == !0usize as IconvT {
5567        ERRNO!() = EINVAL;
5568        return !0usize;
5569    }
5570    // A null inbuf is the state-reset call; all converters are stateless.
5571    if inbuf.is_null() { return 0; }
5572    if inbytesleft.is_null() || outbuf.is_null() || outbytesleft.is_null() {
5573        ERRNO!() = EINVAL;
5574        return !0usize;
5575    }
5576    let from = extract_from(cd);
5577    let to = extract_to(cd);
5578    let mut src = *inbuf as *const u8;
5579    let mut dst = *outbuf as *mut u8;
5580    let mut src_left = *inbytesleft;
5581    let mut dst_left = *outbytesleft;
5582    let mut subst = 0usize;
5583    while src_left > 0 {
5584        let (cp, consumed, err) = iconv_decode(from, src, src_left);
5585        if err != 0 {
5586            if err == EINVAL { break; }
5587            ERRNO!() = err;
5588            return !0usize;
5589        }
5590        let (written, err) = iconv_encode(to, cp, dst, dst_left);
5591        if err != 0 {
5592            if err == E2BIG {
5593                ERRNO!() = E2BIG;
5594                return !0usize;
5595            }
5596            if dst_left < 1 {
5597                ERRNO!() = E2BIG;
5598                return !0usize;
5599            }
5600            *dst = b'*';
5601            dst = dst.add(1);
5602            dst_left -= 1;
5603            subst += 1;
5604        } else {
5605            dst = dst.add(written);
5606            dst_left -= written;
5607        }
5608        src = src.add(consumed);
5609        src_left -= consumed;
5610    }
5611    *inbuf = src as *mut c_char;
5612    *outbuf = dst as *mut c_char;
5613    *inbytesleft = src_left;
5614    *outbytesleft = dst_left;
5615    subst
5616}
5617
5618#[no_mangle]
5619pub unsafe extern "C" fn iconv_close(_cd: IconvT) -> c_int { 0 }
5620
5621// ============================================================
5622// Syscall wrappers as public C ABI
5623// ============================================================
5624
5625#[no_mangle]
5626pub unsafe extern "C" fn write(fd: c_int, buf: *const c_void, count: SizeT) -> SSizeT {
5627    syscall_ret(sys_write(fd as i64, buf as *const u8, count)) as SSizeT
5628}
5629
5630#[no_mangle]
5631pub unsafe extern "C" fn read(fd: c_int, buf: *mut c_void, count: SizeT) -> SSizeT {
5632    syscall_ret(sys_read(fd as i64, buf as *mut u8, count)) as SSizeT
5633}
5634
5635#[no_mangle]
5636pub unsafe extern "C" fn open(path: *const c_char, flags: c_int, mode: c_int) -> c_int {
5637    syscall_ret(sys_open(path as *const u8, flags as i64, mode as i64)) as c_int
5638}
5639
5640#[no_mangle]
5641pub unsafe extern "C" fn close(fd: c_int) -> c_int {
5642    syscall_ret(sys_close(fd as i64)) as c_int
5643}
5644
5645#[no_mangle]
5646pub unsafe extern "C" fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64 {
5647    syscall_ret(sys_lseek(fd as i64, offset, whence as i64))
5648}
5649
5650// ============================================================
5651// Additional syscall wrappers for stdio
5652// ============================================================
5653
5654const O_RDONLY: i32 = 0;
5655const O_WRONLY: i32 = 1;
5656const O_RDWR: i32 = 2;
5657const O_CREAT: i32 = 64;
5658const O_TRUNC: i32 = 512;
5659const O_APPEND: i32 = 1024;
5660const O_EXCL: i32 = 128;
5661const O_NONBLOCK: i32 = 2048;
5662const O_NOFOLLOW: i32 = if cfg!(target_arch = "aarch64") { 0o100000 } else { 0o400000 };
5663const O_DIRECTORY: i32 = if cfg!(target_arch = "aarch64") { 0o40000 } else { 0o200000 };
5664const O_CLOEXEC: i32 = 0x80000;
5665
5666const F_GETFD: i32 = 1;
5667const F_GETFL: i32 = 3;
5668const F_GETOWN: i32 = 9;
5669const F_GETSIG: i32 = 11;
5670const F_GETLEASE: i32 = 1025;
5671const F_GETPIPE_SZ: i32 = 1032;
5672const F_GET_SEALS: i32 = 1034;
5673const F_SETFD: i32 = 2;
5674const F_SETFL: i32 = 4;
5675const F_GETLK: i32 = 5;
5676const F_SETLK: i32 = 6;
5677const F_SETLKW: i32 = 7;
5678const F_DUPFD: i32 = 0;
5679const F_DUPFD_CLOEXEC: i32 = 1030;
5680const FD_CLOEXEC: i32 = 1;
5681
5682const TIOCGWINSZ: u32 = 0x5413;
5683
5684#[repr(C)]
5685struct winsize {
5686    ws_row: u16,
5687    ws_col: u16,
5688    ws_xpixel: u16,
5689    ws_ypixel: u16,
5690}
5691
5692#[inline]
5693unsafe fn sys_pipe2(fds: *mut c_int, flags: i32) -> i64 {
5694    <Arch as Syscalls>::syscall2(SYS_PIPE2, fds as i64, flags as i64)
5695}
5696
5697#[inline]
5698unsafe fn sys_dup3(oldfd: i32, newfd: i32, flags: i32) -> i64 {
5699    <Arch as Syscalls>::syscall3(SYS_DUP3, oldfd as i64, newfd as i64, flags as i64)
5700}
5701
5702#[inline]
5703unsafe fn sys_fcntl(fd: i32, cmd: i32, arg: i64) -> i64 {
5704    <Arch as Syscalls>::syscall3(SYS_FCNTL, fd as i64, cmd as i64, arg as i64)
5705}
5706
5707#[inline]
5708unsafe fn sys_ioctl(fd: c_int, request: u32, arg: *mut u8) -> i64 {
5709    <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg as i64)
5710}
5711
5712#[inline]
5713unsafe fn sys_unlinkat(dirfd: i32, path: *const u8, flags: i32) -> i64 {
5714    <Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, path as i64, flags as i64)
5715}
5716
5717#[inline]
5718unsafe fn sys_renameat2(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: u32) -> i64 {
5719    <Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
5720}
5721
5722// ============================================================
5723// FILE / stdio (buffered, musl-compatible layout)
5724// ============================================================
5725
5726const UNGET: usize = 8;
5727const F_PERM: u32 = 1;
5728const F_NORD: u32 = 4;
5729const F_NOWR: u32 = 8;
5730const F_EOF: u32 = 16;
5731const F_ERR: u32 = 32;
5732const F_SVB: u32 = 64;
5733const F_APP: u32 = 128;
5734
5735const BUFSIZ: usize = 1024;
5736
5737const _IOFBF: c_int = 0;
5738const _IOLBF: c_int = 1;
5739const _IONBF: c_int = 2;
5740
5741const SEEK_SET: c_int = 0;
5742const SEEK_CUR: c_int = 1;
5743const SEEK_END: c_int = 2;
5744
5745// Buffered FILE using musl's 64-bit layout.
5746#[repr(C)]
5747pub struct FILE {
5748    flags: c_uint,
5749    rpos: *mut u8,
5750    rend: *mut u8,
5751    close: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
5752    wend: *mut u8,
5753    wpos: *mut u8,
5754    mustbezero_1: *mut u8,
5755    wbase: *mut u8,
5756    read_fn: Option<unsafe extern "C" fn(*mut FILE, *mut u8, usize) -> usize>,
5757    write_fn: Option<unsafe extern "C" fn(*mut FILE, *const u8, usize) -> usize>,
5758    seek_fn: Option<unsafe extern "C" fn(*mut FILE, i64, c_int) -> i64>,
5759    buf: *mut u8,
5760    buf_size: usize,
5761    prev: *mut FILE,
5762    next: *mut FILE,
5763    fd: c_int,
5764    pipe_pid: c_int,
5765    lockcount: c_long,
5766    mode: c_int,
5767    lock: c_int,
5768    lbf: c_int,
5769    cookie: *mut c_void,
5770    off: i64,
5771    getln_buf: *mut c_char,
5772    mustbezero_2: *mut c_void,
5773    shend: *mut u8,
5774    shlim: i64,
5775    shcnt: i64,
5776    ungotten: [c_int; UNGET],
5777    ungotten_count: c_int,
5778    _eof: c_int,
5779    _err: c_int,
5780}
5781
5782static mut STDIN_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5783static mut STDOUT_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5784static mut STDERR_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
5785
5786static mut STDIN_FILE: FILE = FILE {
5787    flags: 0, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5788    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5789    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5790    read_fn: None, write_fn: None, seek_fn: None,
5791    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5792    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5793    fd: 0, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5794    cookie: core::ptr::null_mut(), off: 0,
5795    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5796    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5797    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5798};
5799static mut STDOUT_FILE: FILE = FILE {
5800    flags: F_NOWR as u32 + F_SVB as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5801    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5802    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5803    read_fn: None, write_fn: None, seek_fn: None,
5804    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5805    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5806    fd: 1, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5807    cookie: core::ptr::null_mut(), off: 0,
5808    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5809    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5810    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5811};
5812static mut STDERR_FILE: FILE = FILE {
5813    flags: F_NOWR as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
5814    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
5815    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
5816    read_fn: None, write_fn: None, seek_fn: None,
5817    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
5818    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
5819    fd: 2, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
5820    cookie: core::ptr::null_mut(), off: 0,
5821    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
5822    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
5823    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
5824};
5825
5826#[no_mangle]
5827pub static mut stdin: *mut FILE = &raw mut STDIN_FILE as *mut FILE;
5828#[no_mangle]
5829pub static mut stdout: *mut FILE = &raw mut STDOUT_FILE as *mut FILE;
5830#[no_mangle]
5831pub static mut stderr: *mut FILE = &raw mut STDERR_FILE as *mut FILE;
5832
5833// All open streams, so fflush(NULL) can flush everything and fclose can
5834// unlink/free dynamically allocated FILEs.
5835static mut OFL_HEAD: *mut FILE = core::ptr::null_mut();
5836
5837unsafe fn ofl_add(f: *mut FILE) {
5838    (*f).prev = core::ptr::null_mut();
5839    (*f).next = OFL_HEAD;
5840    if !OFL_HEAD.is_null() {
5841        (*OFL_HEAD).prev = f;
5842    }
5843    OFL_HEAD = f;
5844}
5845
5846unsafe fn ofl_remove(f: *mut FILE) {
5847    let prev = (*f).prev;
5848    let next = (*f).next;
5849    if prev.is_null() {
5850        OFL_HEAD = next;
5851    } else {
5852        (*prev).next = next;
5853    }
5854    if !next.is_null() {
5855        (*next).prev = prev;
5856    }
5857    (*f).prev = core::ptr::null_mut();
5858    (*f).next = core::ptr::null_mut();
5859}
5860
5861// ============================================================
5862// FILE helpers
5863// ============================================================
5864
5865unsafe fn __stdio_init() {
5866    STDIN_FILE.buf = core::ptr::addr_of_mut!(STDIN_BUF) as *mut u8;
5867    STDIN_FILE.buf_size = BUFSIZ;
5868    STDIN_FILE.read_fn = Some(__stdio_read);
5869    STDIN_FILE.write_fn = Some(__stdio_write);
5870    STDIN_FILE.seek_fn = Some(__stdio_seek);
5871    STDOUT_FILE.buf = core::ptr::addr_of_mut!(STDOUT_BUF) as *mut u8;
5872    STDOUT_FILE.buf_size = BUFSIZ;
5873    STDOUT_FILE.lbf = b'\n' as c_int;
5874    STDOUT_FILE.read_fn = Some(__stdio_read);
5875    STDOUT_FILE.write_fn = Some(__stdio_write);
5876    STDOUT_FILE.seek_fn = Some(__stdio_seek);
5877    STDERR_FILE.buf = core::ptr::addr_of_mut!(STDERR_BUF) as *mut u8;
5878    STDERR_FILE.buf_size = BUFSIZ;
5879    STDERR_FILE.read_fn = Some(__stdio_read);
5880    STDERR_FILE.write_fn = Some(__stdio_write);
5881    STDERR_FILE.seek_fn = Some(__stdio_seek);
5882    STDIN_FILE.flags |= F_PERM;
5883    STDOUT_FILE.flags |= F_PERM;
5884    STDERR_FILE.flags |= F_PERM;
5885    STDIN_FILE.close = Some(__stdio_close);
5886    STDOUT_FILE.close = Some(__stdio_close);
5887    STDERR_FILE.close = Some(__stdio_close);
5888    ofl_add(&raw mut STDIN_FILE as *mut FILE);
5889    ofl_add(&raw mut STDOUT_FILE as *mut FILE);
5890    ofl_add(&raw mut STDERR_FILE as *mut FILE);
5891}
5892
5893unsafe fn buf_ptr(f: *mut FILE) -> *mut u8 {
5894    (f as *mut u8).add(core::mem::size_of::<FILE>())
5895}
5896
5897unsafe extern "C" fn __stdio_read(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
5898    let n = sys_read((*f).fd as i64, buf, len);
5899    if n <= 0 {
5900        if n == 0 { (*f).flags |= F_EOF; } else { (*f).flags |= F_ERR; (*f)._err = 1; }
5901        return 0;
5902    }
5903    n as usize
5904}
5905
5906unsafe extern "C" fn __stdio_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
5907    let l = (*f).wpos as usize - (*f).wbase as usize;
5908    let mut iov = [
5909        ((*f).wbase as *const u8, l),
5910        (buf, len),
5911    ];
5912    if iov[0].1 == 0 { iov = [iov[1], (core::ptr::null(), 0)]; }
5913    if (*f).flags & F_APP != 0 {
5914        let _ = sys_lseek((*f).fd as i64, 0, SEEK_END as i64);
5915    }
5916    let mut rem = iov[0].1 + iov[1].1;
5917    let mut idx = 0usize;
5918    while rem > 0 {
5919        let ptr = iov[idx].0;
5920        let cnt = iov[idx].1;
5921        if cnt == 0 { idx += 1; continue; }
5922        let n = sys_write((*f).fd as i64, ptr, cnt);
5923        if n <= 0 {
5924            (*f).wpos = core::ptr::null_mut();
5925            (*f).wbase = core::ptr::null_mut();
5926            (*f).wend = core::ptr::null_mut();
5927            (*f).flags |= F_ERR;
5928            return if iov[idx].0 == buf { 0 } else { len };
5929        }
5930        rem -= n as usize;
5931        iov[idx].0 = iov[idx].0.add(n as usize);
5932        iov[idx].1 -= n as usize;
5933        if iov[idx].1 == 0 { idx += 1; }
5934    }
5935    (*f).wend = (*f).buf.add((*f).buf_size);
5936    (*f).wbase = (*f).buf;
5937    (*f).wpos = (*f).buf;
5938    len
5939}
5940
5941unsafe extern "C" fn __stdio_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
5942    sys_lseek((*f).fd as i64, off, whence as i64)
5943}
5944
5945unsafe fn init_file(
5946    f: *mut FILE,
5947    fd: c_int,
5948    mode: *const c_char,
5949    close_fn: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
5950    buf_area: *mut u8,
5951    buf_sz: usize,
5952) {
5953    core::ptr::write_bytes(f as *mut u8, 0, core::mem::size_of::<FILE>());
5954    (*f).fd = fd;
5955    (*f).close = close_fn;
5956    (*f).lock = 0;
5957    (*f).lbf = -1;
5958    (*f).buf = buf_area;
5959    (*f).buf_size = buf_sz;
5960    (*f).read_fn = Some(__stdio_read);
5961    (*f).write_fn = Some(__stdio_write);
5962    (*f).seek_fn = Some(__stdio_seek);
5963    let m = *mode;
5964    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
5965    if m == b'r' as c_char && !has_plus {
5966        (*f).flags = F_NORD;
5967    } else if !has_plus {
5968        (*f).flags = F_NOWR;
5969    }
5970    ofl_add(f);
5971}
5972
5973unsafe extern "C" fn __stdio_close(f: *mut FILE) -> c_int {
5974    sys_close((*f).fd as i64);
5975    0
5976}
5977
5978unsafe fn fmodeflags(mode: *const c_char) -> c_int {
5979    let mut flags: c_int;
5980    let m = *mode;
5981    if !strchr(mode as *const u8, b'+' as c_int).is_null() {
5982        flags = O_RDWR;
5983    } else if m == b'r' as c_char {
5984        flags = O_RDONLY;
5985    } else {
5986        flags = O_WRONLY;
5987    }
5988    if !strchr(mode as *const u8, b'x' as c_int).is_null() { flags |= O_EXCL; }
5989    if !strchr(mode as *const u8, b'e' as c_int).is_null() { flags |= O_CLOEXEC; }
5990    if m != b'r' as c_char { flags |= O_CREAT; }
5991    if m == b'w' as c_char { flags |= O_TRUNC; }
5992    if m == b'a' as c_char { flags |= O_APPEND; }
5993    flags
5994}
5995
5996const O_ACCMODE: c_int = O_RDONLY | O_WRONLY | O_RDWR;
5997
5998unsafe fn flush_buf(f: *mut FILE) -> c_int {
5999    if (*f).wpos == (*f).wbase {
6000        if !(*f).wpos.is_null() {
6001            (*f).wend = (*f).buf.add((*f).buf_size);
6002            (*f).wpos = (*f).wbase;
6003        }
6004        return 0;
6005    }
6006    if let Some(wfunc) = (*f).write_fn {
6007        let ret = wfunc(f, core::ptr::null(), 0);
6008        if ret == 0 && (*f).wpos.is_null() { return -1; }
6009        return 0;
6010    }
6011    (*f).flags |= F_ERR;
6012    -1
6013}
6014
6015// ============================================================
6016// fopen / fdopen / freopen / fclose
6017// ============================================================
6018
6019#[no_mangle]
6020pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE {
6021    if filename.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
6022    let m = *mode;
6023    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
6024        ERRNO!() = EINVAL; return core::ptr::null_mut();
6025    }
6026    let flags = fmodeflags(mode);
6027    let fd = sys_open(filename as *const u8, flags as i64, 0o666);
6028    if fd < 0 { ERRNO!() = (-fd) as c_int; return core::ptr::null_mut(); }
6029    let f = fdopen(fd as c_int, mode);
6030    if f.is_null() {
6031        sys_close(fd);
6032    }
6033    f
6034}
6035
6036#[no_mangle]
6037pub unsafe extern "C" fn fdopen(fd: c_int, mode: *const c_char) -> *mut FILE {
6038    if fd < 0 || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
6039    let m = *mode;
6040    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
6041        ERRNO!() = EINVAL; return core::ptr::null_mut();
6042    }
6043    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
6044    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
6045    let buf = buf_ptr(f);
6046    init_file(f, fd, mode, Some(__stdio_close), buf, BUFSIZ);
6047    if !strchr(mode as *const u8, b'a' as c_int).is_null() { (*f).flags |= F_APP; }
6048    if !strchr(mode as *const u8, b'e' as c_int).is_null() { sys_fcntl(fd, F_SETFD, FD_CLOEXEC as i64); }
6049    if (*f).flags & F_NOWR == 0 {
6050        let mut ws: winsize = core::mem::zeroed();
6051        if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 {
6052            (*f).lbf = b'\n' as c_int;
6053        }
6054    }
6055    f
6056}
6057
6058#[no_mangle]
6059pub unsafe extern "C" fn freopen(
6060    filename: *const c_char, mode: *const c_char, f: *mut FILE,
6061) -> *mut FILE {
6062    fflush(f);
6063    if (*f).pipe_pid > 0 { let _ = __stdio_close(f); }
6064    if filename.is_null() {
6065        let m = *mode;
6066        if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
6067            ERRNO!() = EINVAL;
6068            return core::ptr::null_mut();
6069        }
6070        let flags = fmodeflags(mode);
6071        let mut fl = flags & !(O_CREAT | O_EXCL | O_CLOEXEC);
6072        if (*f).flags & F_APP != 0 { fl = (fl & !O_ACCMODE) | O_WRONLY | O_APPEND; }
6073        if sys_fcntl((*f).fd, F_SETFL, fl as i64) < 0 { return core::ptr::null_mut(); }
6074        let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
6075        if has_plus {
6076            (*f).flags &= !(F_NORD | F_NOWR);
6077        } else if *mode == b'r' as c_char {
6078            (*f).flags = ((*f).flags & !F_NOWR) | F_NORD;
6079        } else {
6080            (*f).flags = ((*f).flags & !F_NORD) | F_NOWR;
6081        }
6082        return f;
6083    }
6084    let new_f = fopen(filename, mode);
6085    if new_f.is_null() { let _ = __stdio_close(f); return core::ptr::null_mut(); }
6086    if (*new_f).fd == (*f).fd {
6087        (*new_f).fd = -1;
6088    } else {
6089        sys_dup3((*new_f).fd, (*f).fd, 0);
6090        let _ = __stdio_close(new_f);
6091    }
6092    (*f).flags = (*new_f).flags;
6093    (*f).rpos = core::ptr::null_mut();
6094    (*f).rend = core::ptr::null_mut();
6095    (*f).wpos = core::ptr::null_mut();
6096    (*f).wbase = core::ptr::null_mut();
6097    (*f).wend = core::ptr::null_mut();
6098    (*f).lbf = (*new_f).lbf;
6099    (*f).pipe_pid = 0;
6100    ofl_remove(new_f);
6101    free(new_f as *mut c_void);
6102    f
6103}
6104
6105#[no_mangle]
6106pub unsafe extern "C" fn fclose(f: *mut FILE) -> c_int {
6107    if f.is_null() {
6108        ERRNO!() = EINVAL;
6109        return -1;
6110    }
6111    let r = fflush(f);
6112    let close_r = if let Some(close_fn) = (*f).close { close_fn(f) } else { 0 };
6113    let permanent = (*f).flags & F_PERM != 0;
6114    let allocated_buf = if (*f).flags & F_SVB != 0 { (*f).buf } else { core::ptr::null_mut() };
6115    let getln = (*f).getln_buf;
6116    ofl_remove(f);
6117    if !permanent {
6118        if !allocated_buf.is_null() { free(allocated_buf as *mut c_void); }
6119        if !getln.is_null() { free(getln as *mut c_void); }
6120        free(f as *mut c_void);
6121    }
6122    if r != 0 || close_r != 0 { -1 } else { 0 }
6123}
6124
6125// ============================================================
6126// setvbuf / setbuf / setbuffer / fflush
6127// ============================================================
6128
6129#[no_mangle]
6130pub unsafe extern "C" fn setvbuf(f: *mut FILE, buf: *mut c_char, mode: c_int, size: usize) -> c_int {
6131    if f.is_null() || (mode != _IOFBF && mode != _IOLBF && mode != _IONBF) {
6132        ERRNO!() = EINVAL;
6133        return -1;
6134    }
6135    fflush(f);
6136    (*f).rpos = core::ptr::null_mut();
6137    (*f).rend = core::ptr::null_mut();
6138    (*f).wpos = core::ptr::null_mut();
6139    (*f).wbase = core::ptr::null_mut();
6140    (*f).wend = core::ptr::null_mut();
6141    if mode == _IONBF {
6142        (*f).buf = core::ptr::null_mut();
6143        (*f).buf_size = 0;
6144    } else {
6145        let wanted = if size == 0 { BUFSIZ } else { size };
6146        let actual = if buf.is_null() {
6147            let p = malloc(wanted) as *mut c_char;
6148            if p.is_null() {
6149                ERRNO!() = ENOMEM;
6150                return -1;
6151            }
6152            (*f).flags |= F_SVB;
6153            p
6154        } else {
6155            (*f).flags &= !F_SVB;
6156            buf
6157        };
6158        (*f).buf = actual as *mut u8;
6159        (*f).buf_size = wanted;
6160    }
6161    (*f).lbf = if mode == _IOLBF { b'\n' as c_int } else { -1 };
6162    0
6163}
6164
6165#[no_mangle]
6166pub unsafe extern "C" fn setbuf(f: *mut FILE, buf: *mut c_char) {
6167    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
6168    else { setvbuf(f, buf, _IOFBF, BUFSIZ); }
6169}
6170
6171#[no_mangle]
6172pub unsafe extern "C" fn setbuffer(f: *mut FILE, buf: *mut c_char, size: usize) {
6173    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
6174    else { setvbuf(f, buf, _IOFBF, size); }
6175}
6176
6177#[no_mangle]
6178pub unsafe extern "C" fn fflush(f: *mut FILE) -> c_int {
6179    if f.is_null() {
6180        let mut r = 0;
6181        let mut cur = OFL_HEAD;
6182        while !cur.is_null() {
6183            let next = (*cur).next;
6184            if !(*cur).wpos.is_null() && (*cur).wpos != (*cur).wbase {
6185                if flush_buf(cur) != 0 { r = -1; }
6186            }
6187            cur = next;
6188        }
6189        return r;
6190    }
6191    if !(*f).wpos.is_null() && (*f).wpos != (*f).wbase {
6192        return flush_buf(f);
6193    }
6194    0
6195}
6196
6197// ============================================================
6198// fwide / feof / ferror / clearerr / fileno
6199// ============================================================
6200
6201#[no_mangle]
6202pub unsafe extern "C" fn fwide(_f: *mut FILE, mode: c_int) -> c_int { mode }
6203
6204#[no_mangle]
6205pub unsafe extern "C" fn feof(f: *mut FILE) -> c_int { if (*f)._eof != 0 { 1 } else { 0 } }
6206
6207#[no_mangle]
6208pub unsafe extern "C" fn ferror(f: *mut FILE) -> c_int { if (*f)._err != 0 { 1 } else { 0 } }
6209
6210#[no_mangle]
6211pub unsafe extern "C" fn clearerr(f: *mut FILE) { (*f)._eof = 0; (*f)._err = 0; }
6212
6213#[no_mangle]
6214pub unsafe extern "C" fn fileno(f: *mut FILE) -> c_int { (*f).fd }
6215
6216// ============================================================
6217// fseek / ftell / rewind / fseeko / ftello / fgetpos / fsetpos
6218// ============================================================
6219
6220#[no_mangle]
6221pub unsafe extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int {
6222    fseeko(stream, offset as i64, whence)
6223}
6224
6225#[no_mangle]
6226pub unsafe extern "C" fn ftell(stream: *mut FILE) -> c_long {
6227    ftello(stream) as c_long
6228}
6229
6230#[no_mangle]
6231pub unsafe extern "C" fn rewind(stream: *mut FILE) {
6232    fseek(stream, 0, SEEK_SET);
6233    (*stream)._eof = 0;
6234    (*stream)._err = 0;
6235}
6236
6237#[no_mangle]
6238pub unsafe extern "C" fn fseeko(stream: *mut FILE, offset: i64, whence: c_int) -> c_int {
6239    if whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END {
6240        ERRNO!() = EINVAL;
6241        return -1;
6242    }
6243    let f = &mut *stream;
6244    let mut adj_offset = offset;
6245    if whence == SEEK_CUR {
6246        if !f.rpos.is_null() {
6247            let buffered = f.rend as i64 - f.rpos as i64;
6248            if adj_offset < i64::MIN + buffered {
6249                ERRNO!() = EOVERFLOW;
6250                return -1;
6251            }
6252            adj_offset -= buffered;
6253        }
6254        if adj_offset < i64::MIN + f.ungotten_count as i64 {
6255            ERRNO!() = EOVERFLOW;
6256            return -1;
6257        }
6258        adj_offset -= f.ungotten_count as i64;
6259    }
6260    if !f.wpos.is_null() && f.wpos != f.wbase {
6261        if flush_buf(stream) != 0 { return -1; }
6262    }
6263    f.wpos = core::ptr::null_mut();
6264    f.wbase = core::ptr::null_mut();
6265    f.wend = core::ptr::null_mut();
6266    if let Some(sfunc) = f.seek_fn {
6267        let r = sfunc(stream, adj_offset, whence);
6268        if r < 0 { return -1; }
6269    } else {
6270        ERRNO!() = EINVAL;
6271        return -1;
6272    }
6273    f.rpos = core::ptr::null_mut();
6274    f.rend = core::ptr::null_mut();
6275    f._eof = 0;
6276    f.ungotten_count = 0;
6277    0
6278}
6279
6280#[no_mangle]
6281pub unsafe extern "C" fn ftello(stream: *mut FILE) -> i64 {
6282    let f = &mut *stream;
6283    if f.flags & F_APP != 0 && !f.wpos.is_null() && f.wpos != f.wbase {
6284        if fflush(stream) != 0 { return -1; }
6285    }
6286    let sfunc = match f.seek_fn { Some(s) => s, None => return -1 };
6287    let pos = sfunc(stream, 0,
6288        if (f.flags & F_APP) != 0 && !f.wpos.is_null() && f.wpos != f.wbase { SEEK_END } else { SEEK_CUR });
6289    if pos < 0 { return -1; }
6290    let mut pos = pos;
6291    if !f.rpos.is_null() {
6292        pos += f.rpos as i64 - f.rend as i64;
6293    } else if !f.wbase.is_null() {
6294        let buffered = f.wpos as i64 - f.wbase as i64;
6295        if buffered > i64::MAX - pos {
6296            ERRNO!() = EOVERFLOW;
6297            return -1;
6298        }
6299        pos += buffered;
6300    }
6301    pos - f.ungotten_count as i64
6302}
6303
6304#[no_mangle]
6305pub unsafe extern "C" fn fgetpos(stream: *mut FILE, pos: *mut i64) -> c_int {
6306    let off = ftello(stream);
6307    if off < 0 { return -1; }
6308    *pos = off;
6309    0
6310}
6311
6312#[no_mangle]
6313pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const i64) -> c_int {
6314    fseeko(stream, *pos, SEEK_SET)
6315}
6316
6317// ============================================================
6318// fgetc / getc / getchar / ungetc
6319// ============================================================
6320
6321#[no_mangle]
6322pub unsafe extern "C" fn fgetc(stream: *mut FILE) -> c_int {
6323    let f = &mut *stream;
6324    if f.ungotten_count > 0 {
6325        f.ungotten_count -= 1;
6326        return f.ungotten[f.ungotten_count as usize];
6327    }
6328    if !f.rpos.is_null() && f.rpos < f.rend {
6329        let c = *f.rpos;
6330        f.rpos = f.rpos.add(1);
6331        return c as c_int;
6332    }
6333    if f._eof != 0 { return -1; }
6334    if let Some(rfunc) = f.read_fn {
6335        // Fill the stdio buffer in one read. Reading one byte per syscall is
6336        // not only slow, it is wrong for procfs files that only return their
6337        // contents on the first read: a second one-byte read sees EOF.
6338        if !f.buf.is_null() && f.buf_size > 1 {
6339            let n = rfunc(stream, f.buf, f.buf_size);
6340            if n == 0 {
6341                if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
6342                return -1;
6343            }
6344            f.rpos = f.buf;
6345            f.rend = f.buf.add(n);
6346            let c = *f.rpos;
6347            f.rpos = f.rpos.add(1);
6348            return c as c_int;
6349        }
6350        let mut buf = [0u8; 1];
6351        let n = rfunc(stream, buf.as_mut_ptr(), 1);
6352        if n == 0 {
6353            if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
6354            return -1;
6355        }
6356        buf[0] as c_int
6357    } else {
6358        f._eof = 1;
6359        -1
6360    }
6361}
6362
6363#[no_mangle]
6364pub unsafe extern "C" fn getc(stream: *mut FILE) -> c_int { fgetc(stream) }
6365
6366#[no_mangle]
6367pub unsafe extern "C" fn getchar() -> c_int { fgetc(stdin) }
6368
6369#[no_mangle]
6370pub unsafe extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int {
6371    if c == -1 { return -1; }
6372    let f = &mut *stream;
6373    if f.ungotten_count >= UNGET as c_int { return -1; }
6374    f.ungotten[f.ungotten_count as usize] = c;
6375    f.ungotten_count += 1;
6376    f._eof = 0;
6377    c
6378}
6379
6380// ============================================================
6381// fgets / fread
6382// ============================================================
6383
6384unsafe fn fgets_common(s: *mut c_char, max: usize, stream: *mut FILE, keep_newline: bool) -> *mut c_char {
6385    let mut i = 0usize;
6386    while i < max {
6387        let c = fgetc(stream);
6388        if c == -1 {
6389            if i == 0 { return null_mut(); }
6390            break;
6391        }
6392        if c == b'\n' as c_int && !keep_newline { break; }
6393        *s.add(i) = c as c_char;
6394        i += 1;
6395        if c == b'\n' as c_int { break; }
6396    }
6397    *s.add(i) = 0;
6398    s
6399}
6400
6401#[no_mangle]
6402pub unsafe extern "C" fn fgets(s: *mut c_char, n: c_int, stream: *mut FILE) -> *mut c_char {
6403    if n <= 0 { return null_mut(); }
6404    fgets_common(s, (n - 1) as usize, stream, true)
6405}
6406
6407// gets() was removed from C11 and POSIX.1-2008; it remains an unbounded
6408// convenience wrapper for legacy callers.
6409#[no_mangle]
6410pub unsafe extern "C" fn gets(s: *mut c_char) -> *mut c_char {
6411    fgets_common(s, usize::MAX, stdin, false)
6412}
6413
6414#[no_mangle]
6415pub unsafe extern "C" fn fopen64(filename: *const c_char, mode: *const c_char) -> *mut FILE {
6416    fopen(filename, mode)
6417}
6418
6419// perror(): minimal implementation printing "msg: errno\n".
6420const PERROR_BUF_SIZE: usize = 64;
6421static mut PERROR_BUF: [u8; PERROR_BUF_SIZE] = [0; PERROR_BUF_SIZE];
6422
6423#[no_mangle]
6424pub unsafe extern "C" fn perror(msg: *const c_char) {
6425    let fd = (*stderr).fd;
6426    if !msg.is_null() && *msg != 0 {
6427        let len = strlen(msg as *const c_char);
6428        write_str(fd, msg as *const u8, len);
6429        write_str(fd, b": ".as_ptr(), 2);
6430    }
6431    let e = ERRNO!();
6432    let text = strerror(e) as *const u8;
6433    write_str(fd, text, strlen(text as *const c_char));
6434    write_str(fd, b"\n".as_ptr(), 1);
6435}
6436
6437#[no_mangle]
6438pub unsafe extern "C" fn fread(
6439    ptr: *mut c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
6440) -> SizeT {
6441    if size == 0 || nmemb == 0 { return 0; }
6442    let total = match size.checked_mul(nmemb) {
6443        Some(v) => v,
6444        None => { ERRNO!() = EINVAL; return 0; }
6445    };
6446    let mut rd = 0usize;
6447    while rd < total {
6448        let c = fgetc(stream);
6449        if c == -1 { break; }
6450        *(ptr as *mut u8).add(rd) = c as u8;
6451        rd += 1;
6452    }
6453    rd / size
6454}
6455
6456// ============================================================
6457// puts / fputs / fputc / putc / putchar / fwrite
6458// ============================================================
6459
6460unsafe fn write_str(fd: c_int, s: *const u8, len: usize) {
6461    let mut written = 0usize;
6462    while written < len {
6463        let n = sys_write(fd as i64, s.add(written), len - written);
6464        if n <= 0 { break; }
6465        written += n as usize;
6466    }
6467}
6468
6469#[no_mangle]
6470pub unsafe extern "C" fn __overflow(f: *mut FILE, c: c_int) -> c_int {
6471    if (*f).wpos.is_null() {
6472        (*f).wbase = (*f).buf;
6473        (*f).wpos = (*f).buf;
6474        (*f).wend = (*f).buf.add((*f).buf_size);
6475    }
6476    if flush_buf(f) == -1 { return -1; }
6477    if (*f).wpos >= (*f).wend {
6478        if let Some(wfunc) = (*f).write_fn {
6479            let byte = c as u8;
6480            let ret = wfunc(f, &byte as *const u8, 1);
6481            if ret == 0 { return -1; }
6482        }
6483        return c;
6484    }
6485    *(*f).wpos = c as u8;
6486    (*f).wpos = (*f).wpos.add(1);
6487    if c == (*f).lbf || (*f).wpos >= (*f).wend { let _ = flush_buf(f); }
6488    c
6489}
6490
6491#[no_mangle]
6492pub unsafe extern "C" fn puts(s: *const c_char) -> c_int {
6493    let len = strlen(s as *const c_char);
6494    let _ = fwrite(s as *const c_void, 1, len, stdout);
6495    let _ = fwrite(b"\n".as_ptr() as *const c_void, 1, 1, stdout);
6496    let f = &mut *stdout;
6497    if f.lbf >= 0 { let _ = flush_buf(stdout); }
6498    (len + 1) as c_int
6499}
6500
6501#[no_mangle]
6502pub unsafe extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int {
6503    let len = strlen(s as *const c_char);
6504    fwrite(s as *const c_void, 1, len, stream) as c_int
6505}
6506
6507#[no_mangle]
6508pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int {
6509    let f = &mut *stream;
6510    if f.wpos.is_null() || f.wpos >= f.wend {
6511        if __overflow(f, c) == -1 { return -1; }
6512        return c;
6513    }
6514    *f.wpos = c as u8;
6515    f.wpos = f.wpos.add(1);
6516    if c == f.lbf || f.wpos >= f.wend { let _ = flush_buf(f); }
6517    c
6518}
6519
6520#[no_mangle]
6521pub unsafe extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int { fputc(c, stream) }
6522
6523#[no_mangle]
6524pub unsafe extern "C" fn putchar(c: c_int) -> c_int { fputc(c, stdout) }
6525
6526#[no_mangle]
6527pub unsafe extern "C" fn fwrite(
6528    ptr: *const c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
6529) -> SizeT {
6530    if size == 0 || nmemb == 0 { return 0; }
6531    let total = match size.checked_mul(nmemb) {
6532        Some(v) => v,
6533        None => { ERRNO!() = EINVAL; return 0; }
6534    };
6535    let f = &mut *stream;
6536    if f.buf_size == 0 {
6537        if let Some(wfunc) = f.write_fn {
6538            let ret = wfunc(stream, ptr as *const u8, total);
6539            if ret < total { f._err = 1; f.flags |= F_ERR; }
6540            return ret / size;
6541        }
6542        f._err = 1;
6543        f.flags |= F_ERR;
6544        return 0;
6545    }
6546    if f.wpos.is_null() {
6547        f.wbase = f.buf;
6548        f.wpos = f.buf;
6549        f.wend = f.buf.add(f.buf_size);
6550    }
6551    let mut remaining = total;
6552    let mut src = ptr as *const u8;
6553    while remaining > 0 {
6554        let space = f.wend as usize - f.wpos as usize;
6555        if space == 0 {
6556            if flush_buf(f as *mut FILE) == -1 { break; }
6557            continue;
6558        }
6559        let n = if remaining < space { remaining } else { space };
6560        core::ptr::copy_nonoverlapping(src, f.wpos, n);
6561        f.wpos = f.wpos.add(n);
6562        src = src.add(n);
6563        remaining -= n;
6564        if f.wpos >= f.wend { let _ = flush_buf(f as *mut FILE); }
6565    }
6566    if f.lbf >= 0 { let _ = flush_buf(f as *mut FILE); }
6567    (total - remaining) / size
6568}
6569
6570// ============================================================
6571// printf / fprintf / vprintf / vfprintf / dprintf / vdprintf
6572// ============================================================
6573
6574unsafe fn wide_to_mb(dst: *mut u8, cap: usize, src: *const wchar_t) -> usize {
6575    let mut o = 0usize;
6576    let mut i = 0usize;
6577    let mut st: c_uint = 0;
6578    while i < cap && *src.add(i) != 0 {
6579        let mut tmp = [0u8; 8];
6580        let n = wcrtomb(tmp.as_mut_ptr() as *mut c_char, *src.add(i), &mut st);
6581        if n == !0usize || n == 0 { break; }
6582        if o + n > cap { break; }
6583        core::ptr::copy_nonoverlapping(tmp.as_ptr(), dst.add(o), n);
6584        o += n;
6585        i += 1;
6586    }
6587    o
6588}
6589
6590const FMT_MAX_WIDTH: usize = 4096;
6591const FMT_MAX_PRECISION: i32 = 4096;
6592const FMT_MAX_INT_PRECISION: i32 = 1022;
6593const FMT_MAX_FLOAT_PRECISION: i32 = 1099;
6594const FMT_MAX_EG_PRECISION: i32 = 18;
6595const FMT_INT_BUF: usize = 4224;
6596const FMT_FLOAT_BUF: usize = 4224;
6597const FMT_WRITE_BUF: usize = 4096;
6598
6599#[inline]
6600fn fmt_width(width: usize) -> usize {
6601    if width > FMT_MAX_WIDTH { FMT_MAX_WIDTH } else { width }
6602}
6603
6604#[inline]
6605fn fmt_precision(precision: i32) -> i32 {
6606    if precision > FMT_MAX_PRECISION { FMT_MAX_PRECISION } else { precision }
6607}
6608
6609#[inline]
6610fn fmt_star_width(width: c_int, flags: &mut u8) -> usize {
6611    if width < 0 {
6612        *flags |= FLAG_MINUS;
6613        fmt_width(width.unsigned_abs() as usize)
6614    } else {
6615        fmt_width(width as usize)
6616    }
6617}
6618
6619/// Parsed conversion specifier shared by the narrow and wide formatters.
6620struct FormatSpec {
6621    flags: u8,
6622    width: usize,
6623    precision: i32,
6624    len1: u8,
6625    len2: u8,
6626    spec: u8,
6627    /// Index of the conversion character; the caller advances past it.
6628    next: usize,
6629}
6630
6631/// Parse flags, width, precision and the length modifier at `i` (the first
6632/// byte after `%`).  `*` width/precision arguments are consumed from `args`.
6633unsafe fn parse_format_spec(
6634    fmt: *const u8,
6635    mut i: usize,
6636    args: &mut VaList<'_>,
6637) -> FormatSpec {
6638    let mut flags: u8 = 0;
6639    loop {
6640        match *fmt.add(i) {
6641            b'-' => { flags |= FLAG_MINUS; i += 1; }
6642            b'+' => { flags |= FLAG_PLUS; i += 1; }
6643            b' ' => { flags |= FLAG_SPACE; i += 1; }
6644            b'0' => { flags |= FLAG_ZERO; i += 1; }
6645            b'#' => { flags |= FLAG_HASH; i += 1; }
6646            _ => break,
6647        }
6648    }
6649    let mut width: usize = 0;
6650    if *fmt.add(i) == b'*' {
6651        width = fmt_star_width(args.next_arg::<c_int>(), &mut flags);
6652        i += 1;
6653    } else {
6654        while *fmt.add(i) >= b'0' && *fmt.add(i) <= b'9' {
6655            width = width.saturating_mul(10).saturating_add((*fmt.add(i) - b'0') as usize);
6656            i += 1;
6657        }
6658    }
6659    width = fmt_width(width);
6660    let mut precision: i32 = -1;
6661    if *fmt.add(i) == b'.' {
6662        i += 1;
6663        if *fmt.add(i) == b'*' {
6664            let p = args.next_arg::<c_int>();
6665            precision = if p < 0 { -1 } else { fmt_precision(p) };
6666            i += 1;
6667        } else {
6668            precision = 0;
6669            while *fmt.add(i) >= b'0' && *fmt.add(i) <= b'9' {
6670                precision = precision.saturating_mul(10).saturating_add((*fmt.add(i) - b'0') as i32);
6671                i += 1;
6672            }
6673            precision = fmt_precision(precision);
6674        }
6675    }
6676    let mut len1 = 0u8;
6677    let mut len2 = 0u8;
6678    let c = *fmt.add(i);
6679    if c == b'h' || c == b'l' || c == b'j' || c == b'z' || c == b't' || c == b'L' {
6680        len1 = c;
6681        i += 1;
6682        let c2 = *fmt.add(i);
6683        if (c == b'h' && c2 == b'h') || (c == b'l' && c2 == b'l') {
6684            len2 = c2;
6685            i += 1;
6686        }
6687    }
6688    FormatSpec { flags, width, precision, len1, len2, spec: *fmt.add(i), next: i }
6689}
6690
6691macro_rules! impl_format {
6692    ($fmt:expr, $args:expr, $write_char:expr, $write_str:expr) => {{
6693        let fmt = $fmt;
6694        let args = &mut $args;
6695        let mut count: usize = 0;
6696        let mut i = 0usize;
6697        loop {
6698            let c = *fmt.add(i) as u8;
6699            if c == 0 { break; }
6700            if c != b'%' {
6701                ($write_char)(c);
6702                count += 1; i += 1; continue;
6703            }
6704            i += 1;
6705            let fs = parse_format_spec(fmt as *const u8, i, args);
6706            let flags = fs.flags;
6707            let width = fs.width;
6708            let precision = fs.precision;
6709            let len_mod = fs.len1;
6710            let spec = fs.spec;
6711            i = fs.next;
6712            if fs.len2 != 0 {
6713                let len_mod2 = fs.len2;
6714                // Handle double-length modifiers
6715                match (len_mod, len_mod2, spec) {
6716                        (b'h', b'h', b'n') => {
6717                            let p = args.next_arg::<*mut c_void>();
6718                            if !p.is_null() { *(p as *mut u8) = count as u8; }
6719                        }
6720                        (b'l', b'l', b'n') => {
6721                            let p = args.next_arg::<*mut c_void>();
6722                            if !p.is_null() { *(p as *mut c_longlong) = count as c_longlong; }
6723                        }
6724                        (b'h', b'h', b'd') | (b'h', b'h', b'i') => {
6725                            let mut fbuf = [0u8; FMT_INT_BUF];
6726                            let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_int>() as i8 as i64, precision, width, flags);
6727                            ($write_str)(fbuf.as_ptr(), len); count += len;
6728                        }
6729                        (b'h', b'h', b'u') => {
6730                            let mut fbuf = [0u8; FMT_INT_BUF];
6731                            let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u8 as u64, precision, width, flags);
6732                            ($write_str)(fbuf.as_ptr(), len); count += len;
6733                        }
6734                        (b'h', b'h', b'x') => {
6735                            let mut fbuf = [0u8; FMT_INT_BUF];
6736                            let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u8 as u64, false, precision, width, flags);
6737                            ($write_str)(fbuf.as_ptr(), len); count += len;
6738                        }
6739                        (b'h', b'h', b'X') => {
6740                            let mut fbuf = [0u8; FMT_INT_BUF];
6741                            let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u8 as u64, true, precision, width, flags);
6742                            ($write_str)(fbuf.as_ptr(), len); count += len;
6743                        }
6744                        (b'h', b'h', b'o') => {
6745                            let mut fbuf = [0u8; FMT_INT_BUF];
6746                            let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u8 as u64, precision, width, flags);
6747                            ($write_str)(fbuf.as_ptr(), len); count += len;
6748                        }
6749                        (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
6750                            let mut fbuf = [0u8; FMT_INT_BUF];
6751                            let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_longlong>() as i64, precision, width, flags);
6752                            ($write_str)(fbuf.as_ptr(), len); count += len;
6753                        }
6754                        (b'l', b'l', b'u') => {
6755                            let mut fbuf = [0u8; FMT_INT_BUF];
6756                            let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulonglong>() as u64, precision, width, flags);
6757                            ($write_str)(fbuf.as_ptr(), len); count += len;
6758                        }
6759                        (b'l', b'l', b'o') => {
6760                            let mut fbuf = [0u8; FMT_INT_BUF];
6761                            let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulonglong>() as u64, precision, width, flags);
6762                            ($write_str)(fbuf.as_ptr(), len); count += len;
6763                        }
6764                        (b'l', b'l', b'x') => {
6765                            let mut fbuf = [0u8; FMT_INT_BUF];
6766                            let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulonglong>() as u64, false, precision, width, flags);
6767                            ($write_str)(fbuf.as_ptr(), len); count += len;
6768                        }
6769                        (b'l', b'l', b'X') => {
6770                            let mut fbuf = [0u8; FMT_INT_BUF];
6771                            let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulonglong>() as u64, true, precision, width, flags);
6772                            ($write_str)(fbuf.as_ptr(), len); count += len;
6773                        }
6774                        _ => { ($write_char)(b'%'); ($write_char)(len_mod); ($write_char)(len_mod2); ($write_char)(spec); count += 4; }
6775                    }
6776                } else if len_mod != 0 {
6777                    // size_t/ptrdiff_t are 64-bit on all supported targets;
6778                    // treat %z/%t integer conversions like %l.
6779                    let lm = match len_mod {
6780                        b'z' | b't' if spec != b'n' => b'l',
6781                        // intmax_t is long on every target keel supports.
6782                        b'j' if spec != b'n' => b'l',
6783                        _ => len_mod,
6784                    };
6785                    match (lm, spec) {
6786                        (b'h', b'n') => {
6787                            let p = args.next_arg::<*mut c_void>();
6788                            if !p.is_null() { *(p as *mut u16) = count as u16; }
6789                        }
6790                        (b'l', b'n') => {
6791                            let p = args.next_arg::<*mut c_void>();
6792                            if !p.is_null() { *(p as *mut c_long) = count as c_long; }
6793                        }
6794                        (b'z', b'n') | (b't', b'n') => {
6795                            let p = args.next_arg::<*mut c_void>();
6796                            if !p.is_null() { *(p as *mut usize) = count; }
6797                        }
6798                        (b'j', b'n') => {
6799                            let p = args.next_arg::<*mut c_void>();
6800                            if !p.is_null() { *(p as *mut c_ulonglong) = count as c_ulonglong; }
6801                        }
6802                        (b'h', b'd') | (b'h', b'i') => {
6803                            let mut fbuf = [0u8; FMT_INT_BUF];
6804                            let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_int>() as i16 as i64, precision, width, flags);
6805                            ($write_str)(fbuf.as_ptr(), len); count += len;
6806                        }
6807                        (b'h', b'u') => {
6808                            let mut fbuf = [0u8; FMT_INT_BUF];
6809                            let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u16 as u64, precision, width, flags);
6810                            ($write_str)(fbuf.as_ptr(), len); count += len;
6811                        }
6812                        (b'h', b'x') => {
6813                            let mut fbuf = [0u8; FMT_INT_BUF];
6814                            let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u16 as u64, false, precision, width, flags);
6815                            ($write_str)(fbuf.as_ptr(), len); count += len;
6816                        }
6817                        (b'h', b'X') => {
6818                            let mut fbuf = [0u8; FMT_INT_BUF];
6819                            let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u16 as u64, true, precision, width, flags);
6820                            ($write_str)(fbuf.as_ptr(), len); count += len;
6821                        }
6822                        (b'h', b'o') => {
6823                            let mut fbuf = [0u8; FMT_INT_BUF];
6824                            let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u16 as u64, precision, width, flags);
6825                            ($write_str)(fbuf.as_ptr(), len); count += len;
6826                        }
6827                        (b'l', b'd') | (b'l', b'i') => {
6828                            let mut fbuf = [0u8; FMT_INT_BUF];
6829                            let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_long>() as i64, precision, width, flags);
6830                            ($write_str)(fbuf.as_ptr(), len); count += len;
6831                        }
6832                        (b'l', b'u') => {
6833                            let mut fbuf = [0u8; FMT_INT_BUF];
6834                            let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulong>() as u64, precision, width, flags);
6835                            ($write_str)(fbuf.as_ptr(), len); count += len;
6836                        }
6837                        (b'l', b's') => {
6838                            let p = args.next_arg::<*const wchar_t>();
6839                            if p.is_null() {
6840                                let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
6841                                let pad = width.saturating_sub(slen);
6842                                if flags & FLAG_MINUS != 0 { ($write_str)(b"(null)".as_ptr(), slen); for _ in 0..pad { ($write_char)(b' '); } }
6843                                else { for _ in 0..pad { ($write_char)(b' '); } ($write_str)(b"(null)".as_ptr(), slen); }
6844                                count += slen + pad;
6845                            } else {
6846                                let mut mb = [0u8; 4096];
6847                                let mut n = wide_to_mb(mb.as_mut_ptr(), mb.len(), p);
6848                                if precision >= 0 && (precision as usize) < n { n = precision as usize; }
6849                                let pad = width.saturating_sub(n);
6850                                if flags & FLAG_MINUS != 0 { ($write_str)(mb.as_ptr(), n); for _ in 0..pad { ($write_char)(b' '); } }
6851                                else { for _ in 0..pad { ($write_char)(b' '); } ($write_str)(mb.as_ptr(), n); }
6852                                count += n + pad;
6853                            }
6854                        }
6855                        (b'l', b'c') => {
6856                            let ch = args.next_arg::<c_int>();
6857                            let mut mb = [0u8; 8];
6858                            let mut st: c_uint = 0;
6859                            let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, ch, &mut st);
6860                            if n != !0usize {
6861                                let pad = width.saturating_sub(n);
6862                                if flags & FLAG_MINUS != 0 {
6863                                    ($write_str)(mb.as_ptr(), n);
6864                                    for _ in 0..pad { ($write_char)(b' '); }
6865                                } else {
6866                                    for _ in 0..pad { ($write_char)(b' '); }
6867                                    ($write_str)(mb.as_ptr(), n);
6868                                }
6869                                count += n + pad;
6870                            }
6871                        }
6872                        (b'l', b'x') => {
6873                            let mut fbuf = [0u8; FMT_INT_BUF];
6874                            let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulong>() as u64, false, precision, width, flags);
6875                            ($write_str)(fbuf.as_ptr(), len); count += len;
6876                        }
6877                        (b'l', b'X') => {
6878                            let mut fbuf = [0u8; FMT_INT_BUF];
6879                            let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulong>() as u64, true, precision, width, flags);
6880                            ($write_str)(fbuf.as_ptr(), len); count += len;
6881                        }
6882                        (b'l', b'o') => {
6883                            let mut fbuf = [0u8; FMT_INT_BUF];
6884                            let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulong>() as u64, precision, width, flags);
6885                            ($write_str)(fbuf.as_ptr(), len); count += len;
6886                        }
6887                        (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
6888                        | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
6889                            let mut wbuf = [0u8; FMT_FLOAT_BUF];
6890                            let total = format_float_into(wbuf.as_mut_ptr(), args.next_arg::<f64>(), spec, precision, width, flags);
6891                            ($write_str)(wbuf.as_ptr(), total); count += total;
6892                        }
6893                        (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
6894                        | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
6895                            #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
6896                            let val = f128_to_f64(valist_read_f128(args));
6897                            #[cfg(target_arch = "x86_64")]
6898                            let val = args.next_arg::<f64>();
6899                            let mut wbuf = [0u8; FMT_FLOAT_BUF];
6900                            let total = format_float_into(wbuf.as_mut_ptr(), val, spec, precision, width, flags);
6901                            ($write_str)(wbuf.as_ptr(), total); count += total;
6902                        }
6903                        _ => { ($write_char)(b'%'); ($write_char)(len_mod); ($write_char)(spec); count += 3; }
6904                    }
6905                } else {
6906                match spec {
6907                    b's' => {
6908                        let s = args.next_arg::<*const c_char>();
6909                        if s.is_null() {
6910                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
6911                            let padded_len = if width > slen { width } else { slen };
6912                            let pad = padded_len - slen;
6913                            if flags & FLAG_MINUS != 0 {
6914                                ($write_str)(b"(null)".as_ptr(), slen);
6915                                for _ in 0..pad { ($write_char)(b' '); }
6916                            } else {
6917                                for _ in 0..pad { ($write_char)(b' '); }
6918                                ($write_str)(b"(null)".as_ptr(), slen);
6919                            }
6920                            count += padded_len;
6921                        } else {
6922                            let full_len = strlen(s as *const c_char);
6923                            let slen = if precision >= 0 { (precision as usize).min(full_len) } else { full_len };
6924                            let padded_len = if width > slen { width } else { slen };
6925                            let pad = padded_len - slen;
6926                            if flags & FLAG_MINUS != 0 {
6927                                ($write_str)(s as *const u8, slen);
6928                                for _ in 0..pad { ($write_char)(b' '); }
6929                            } else {
6930                                for _ in 0..pad { ($write_char)(b' '); }
6931                                ($write_str)(s as *const u8, slen);
6932                            }
6933                            count += padded_len;
6934                        }
6935                    }
6936                    b'd' | b'i' => {
6937                        let mut fbuf = [0u8; FMT_INT_BUF];
6938                        let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_int>() as i64, precision, width, flags);
6939                        ($write_str)(fbuf.as_ptr(), len); count += len;
6940                    }
6941                    b'u' => {
6942                        let mut fbuf = [0u8; FMT_INT_BUF];
6943                        let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u64, precision, width, flags);
6944                        ($write_str)(fbuf.as_ptr(), len); count += len;
6945                    }
6946                    b'x' => {
6947                        let mut fbuf = [0u8; FMT_INT_BUF];
6948                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u64, false, precision, width, flags);
6949                        ($write_str)(fbuf.as_ptr(), len); count += len;
6950                    }
6951                    b'X' => {
6952                        let mut fbuf = [0u8; FMT_INT_BUF];
6953                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u64, true, precision, width, flags);
6954                        ($write_str)(fbuf.as_ptr(), len); count += len;
6955                    }
6956                    b'o' => {
6957                        let mut fbuf = [0u8; FMT_INT_BUF];
6958                        let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u64, precision, width, flags);
6959                        ($write_str)(fbuf.as_ptr(), len); count += len;
6960                    }
6961                    b'c' => {
6962                        let ch = args.next_arg::<c_int>();
6963                        if width > 1 {
6964                            let pad = width - 1;
6965                            if flags & FLAG_MINUS != 0 {
6966                                ($write_char)(ch as u8); count += 1;
6967                                for _ in 0..pad { ($write_char)(b' '); count += 1; }
6968                            } else {
6969                                for _ in 0..pad { ($write_char)(b' '); count += 1; }
6970                                ($write_char)(ch as u8); count += 1;
6971                            }
6972                        } else {
6973                            ($write_char)(ch as u8); count += 1;
6974                        }
6975                    }
6976                    b'p' => {
6977                        let p = args.next_arg::<*const c_void>();
6978                        let mut fbuf = [0u8; 20];
6979                        fbuf[0] = b'0'; fbuf[1] = b'x';
6980                        let b = format_hex(p as u64, false);
6981                        core::ptr::copy_nonoverlapping(b.0.as_ptr(), fbuf.as_mut_ptr().add(2), b.1);
6982                        ($write_str)(fbuf.as_ptr(), b.1 + 2); count += b.1 + 2;
6983                    }
6984                    b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
6985                        let mut wbuf = [0u8; FMT_FLOAT_BUF];
6986                        let total = format_float_into(wbuf.as_mut_ptr(), args.next_arg::<f64>(), spec, precision, width, flags);
6987                        ($write_str)(wbuf.as_ptr(), total); count += total;
6988                    }
6989                    b'%' => { ($write_char)(b'%'); count += 1; }
6990                    b'n' => {
6991                        let p = args.next_arg::<*mut c_void>();
6992                        if !p.is_null() { *(p as *mut c_int) = count as c_int; }
6993                    }
6994                    _ => { ($write_char)(b'%'); ($write_char)(spec); count += 2; }
6995                }
6996            }
6997            i += 1;
6998        }
6999        count as c_int
7000    }};
7001}
7002
7003unsafe fn format_u64(mut val: u64) -> ([u8; 20], usize) {
7004    let mut buf = [0u8; 20];
7005    if val == 0 { buf[0] = b'0'; return (buf, 1); }
7006    let mut tmp = [0u8; 20];
7007    let mut pos = 20;
7008    while val > 0 { pos -= 1; tmp[pos] = b'0' + (val % 10) as u8; val /= 10; }
7009    let len = 20 - pos;
7010    core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
7011    (buf, len)
7012}
7013
7014
7015unsafe fn format_hex(mut val: u64, uppercase: bool) -> ([u8; 16], usize) {
7016    let digits = if uppercase { b"0123456789ABCDEF" } else { b"0123456789abcdef" };
7017    let mut buf = [0u8; 16];
7018    if val == 0 { buf[0] = b'0'; return (buf, 1); }
7019    let mut tmp = [0u8; 16];
7020    let mut pos = 16;
7021    while val > 0 { pos -= 1; tmp[pos] = digits[(val & 0xf) as usize]; val >>= 4; }
7022    let len = 16 - pos;
7023    core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
7024    (buf, len)
7025}
7026
7027unsafe fn format_octal(mut val: u64, alt: bool) -> ([u8; 24], usize) {
7028    let mut buf = [0u8; 24];
7029    if val == 0 {
7030        buf[0] = b'0';
7031        return (buf, 1);
7032    }
7033    let mut tmp = [0u8; 24];
7034    let mut pos = 24;
7035    while val > 0 {
7036        pos -= 1;
7037        tmp[pos] = b'0' + (val & 7) as u8;
7038        val >>= 3;
7039    }
7040    let len = 24 - pos;
7041    if alt {
7042        tmp[pos - 1] = b'0';
7043        core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos - 1), buf.as_mut_ptr(), len + 1);
7044        (buf, len + 1)
7045    } else {
7046        core::ptr::copy_nonoverlapping(tmp.as_ptr().add(pos), buf.as_mut_ptr(), len);
7047        (buf, len)
7048    }
7049}
7050
7051unsafe fn format_int(
7052    dst: *mut u8,
7053    digits: *const u8,
7054    digits_len: usize,
7055    sign: Option<u8>,
7056    prefix: Option<u8>,
7057    precision: i32,
7058    width: usize,
7059    flags: u8,
7060    octal_alt: bool,
7061) -> usize {
7062    let precision = if precision > FMT_MAX_INT_PRECISION { FMT_MAX_INT_PRECISION } else { precision };
7063    let num_digits = if precision == 0 && digits_len == 1 && *digits == b'0' && !octal_alt {
7064        0
7065    } else {
7066        digits_len
7067    };
7068    let prec = precision as usize;
7069    let zero_pad = if precision >= 0 && prec > num_digits { prec - num_digits } else { 0 };
7070
7071    let sign_len = sign.map_or(0, |_| 1);
7072    let prefix_len = prefix.map_or(0, |_| 2);
7073    let content_len = sign_len + prefix_len + zero_pad + num_digits;
7074
7075    let mut buf = [0u8; FMT_INT_BUF];
7076    let mut pos = 0usize;
7077    if let Some(c) = sign { buf[pos] = c; pos += 1; }
7078    if let Some(c) = prefix { buf[pos] = b'0'; pos += 1; buf[pos] = c; pos += 1; }
7079    for _ in 0..zero_pad { buf[pos] = b'0'; pos += 1; }
7080    if num_digits > 0 {
7081        core::ptr::copy_nonoverlapping(digits, buf.as_mut_ptr().add(pos), num_digits);
7082    }
7083
7084    if content_len >= width {
7085        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, content_len);
7086        return content_len;
7087    }
7088    let pad = width - content_len;
7089    if flags & FLAG_MINUS != 0 {
7090        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, content_len);
7091        for i in 0..pad { *dst.add(content_len + i) = b' '; }
7092    } else if flags & FLAG_ZERO != 0 && precision < 0 {
7093        let fixed = sign_len + prefix_len;
7094        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, fixed);
7095        for i in fixed..width - num_digits { *dst.add(i) = b'0'; }
7096        if num_digits > 0 {
7097            core::ptr::copy_nonoverlapping(digits, dst.add(width - num_digits), num_digits);
7098        }
7099    } else {
7100        for i in 0..pad { *dst.add(i) = b' '; }
7101        core::ptr::copy_nonoverlapping(buf.as_ptr(), dst.add(pad), content_len);
7102    }
7103    width
7104}
7105
7106// Render one integer conversion into `dst` (an FMT_INT_BUF-sized scratch
7107// buffer) and return its length.  The wide and narrow formatters share the
7108// same conversion rules; only the final character sink differs.
7109unsafe fn format_signed_into(dst: *mut u8, val: i64, precision: i32, width: usize, flags: u8) -> usize {
7110    let neg = val < 0;
7111    let abs = if neg { val.wrapping_neg() as u64 } else { val as u64 };
7112    let b = format_u64(abs);
7113    let sign = if neg { Some(b'-') } else if flags & FLAG_PLUS != 0 { Some(b'+') } else if flags & FLAG_SPACE != 0 { Some(b' ') } else { None };
7114    format_int(dst, b.0.as_ptr(), b.1, sign, None, precision, width, flags, false)
7115}
7116
7117unsafe fn format_unsigned_into(dst: *mut u8, val: u64, precision: i32, width: usize, flags: u8) -> usize {
7118    let b = format_u64(val);
7119    format_int(dst, b.0.as_ptr(), b.1, None, None, precision, width, flags, false)
7120}
7121
7122unsafe fn format_hex_into(dst: *mut u8, val: u64, upper: bool, precision: i32, width: usize, flags: u8) -> usize {
7123    let b = format_hex(val, upper);
7124    let prefix = if flags & FLAG_HASH != 0 && !(b.1 == 1 && b.0[0] == b'0') {
7125        Some(if upper { b'X' } else { b'x' })
7126    } else {
7127        None
7128    };
7129    format_int(dst, b.0.as_ptr(), b.1, None, prefix, precision, width, flags, false)
7130}
7131
7132unsafe fn format_octal_into(dst: *mut u8, val: u64, precision: i32, width: usize, flags: u8) -> usize {
7133    let alt = flags & FLAG_HASH != 0;
7134    let b = format_octal(val, alt);
7135    format_int(dst, b.0.as_ptr(), b.1, None, None, precision, width, flags, alt)
7136}
7137
7138unsafe fn format_float_into(dst: *mut u8, val: f64, spec: u8, precision: i32, width: usize, flags: u8) -> usize {
7139    let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
7140    let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
7141    let mut fbuf = [0u8; FMT_FLOAT_BUF];
7142    let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
7143    apply_width_flags(dst, fbuf.as_ptr(), flen, width, flags)
7144}
7145
7146
7147// Float format specifier type
7148const FMT_F: u8 = 0;
7149const FMT_E: u8 = 1;
7150const FMT_G: u8 = 2;
7151const FMT_A: u8 = 3;
7152
7153const FLAG_HASH: u8 = 1;
7154const FLAG_PLUS: u8 = 2;
7155const FLAG_SPACE: u8 = 4;
7156const FLAG_ZERO: u8 = 8;
7157const FLAG_MINUS: u8 = 16;
7158
7159// === %f formatting helpers ===
7160
7161/// Convert (mant << shift) to decimal string. Returns byte count written to buf.
7162/// mant is a 53-bit significand, shift is the left-shift amount (can be 0..~971).
7163unsafe fn bigint_to_decimal(buf: *mut u8, mant: u64, shift: u32) -> usize {
7164    // Store as little-endian u32 limbs. Max bits: 53 + 971 ≈ 1024 → 32 limbs.
7165    let nlimbs = (2 + (shift + 31) / 32) as usize;
7166    let mut limbs = [0u32; 36];
7167    limbs[0] = mant as u32;
7168    limbs[1] = (mant >> 32) as u32;
7169
7170    let ws = (shift / 32) as usize;
7171    let bs = shift % 32;
7172
7173    // Word-level shift left
7174    if ws > 0 {
7175        let mut i = 1usize;
7176        loop {
7177            limbs[i + ws] = limbs[i];
7178            if i == 0 { break; }
7179            i -= 1;
7180        }
7181        for j in 0..ws { limbs[j] = 0; }
7182    }
7183    // Bit-level shift left
7184    if bs > 0 {
7185        let mut carry = 0u32;
7186        let end = nlimbs.min(ws + 3);
7187        for i in ws..end {
7188            let new_val = (limbs[i] << bs) | carry;
7189            carry = limbs[i] >> (32 - bs);
7190            limbs[i] = new_val;
7191        }
7192    }
7193
7194    // Find highest non-zero limb
7195    let mut used = nlimbs;
7196    while used > 0 && limbs[used - 1] == 0 { used -= 1; }
7197    if used == 0 { *buf = b'0'; return 1; }
7198
7199    // Repeated division by 10 to extract decimal digits
7200    let mut digits = [0u8; 400];
7201    let mut nd = 0usize;
7202    loop {
7203        let mut all_zero = true;
7204        for i in 0..used { if limbs[i] != 0 { all_zero = false; break; } }
7205        if all_zero { break; }
7206        let mut rem = 0u64;
7207        for i in (0..used).rev() {
7208            let val = (rem << 32) | limbs[i] as u64;
7209            limbs[i] = (val / 10) as u32;
7210            rem = val % 10;
7211        }
7212        digits[nd] = rem as u8;
7213        nd += 1;
7214    }
7215    // Write digits in big-endian order
7216    for i in 0..nd { *buf.add(i) = b'0' + digits[nd - 1 - i]; }
7217    nd
7218}
7219
7220/// Compute `count` fractional digits of frac_bits / 2^shift using u128 arithmetic.
7221/// shift must be <= 124. Returns true if any value remains after the last digit.
7222unsafe fn frac_digits_u128(buf: *mut u8, frac_bits: u64, shift: u32, count: usize) -> bool {
7223    let mask: u128 = (1u128 << shift) - 1;
7224    let mut rem = frac_bits as u128;
7225    for i in 0..count {
7226        rem *= 10;
7227        let digit = (rem >> shift) as u8;
7228        rem &= mask;
7229        *buf.add(i) = digit;
7230    }
7231    rem != 0
7232}
7233
7234/// Compute `count` fractional digits of frac_bits / 2^shift using big-integer arithmetic.
7235/// For shift > 124 (up to ~1074). Returns true if any value remains after the last digit.
7236unsafe fn frac_digits_bigint(buf: *mut u8, frac_bits: u64, shift: u32, count: usize) -> bool {
7237    let nlimbs = ((shift + 31) / 32) as usize;
7238    let mut rem = [0u32; 36]; // enough for shift up to 1088
7239    rem[0] = frac_bits as u32;
7240    if nlimbs > 1 { rem[1] = (frac_bits >> 32) as u32; }
7241    // Mask to exactly `shift` bits
7242    let hi_word = (shift / 32) as usize;
7243    let hi_bit = shift % 32;
7244    if hi_bit > 0 && hi_word < nlimbs {
7245        rem[hi_word] &= (1u32 << hi_bit) - 1;
7246    }
7247    // Zero upper limbs beyond shift
7248    let clear_from = if hi_bit > 0 { hi_word + 1 } else { hi_word };
7249    for j in clear_from..nlimbs { rem[j] = 0; }
7250
7251    for i in 0..count {
7252        // Multiply remainder by 10
7253        let mut carry = 0u64;
7254        for j in 0..nlimbs {
7255            let val = rem[j] as u64 * 10 + carry;
7256            rem[j] = val as u32;
7257            carry = val >> 32;
7258        }
7259        // Extract digit from bit position `shift`
7260        let digit: u32;
7261        if hi_bit == 0 {
7262            digit = if hi_word < nlimbs { rem[hi_word] } else { carry as u32 };
7263        } else {
7264            let mut d = if hi_word < nlimbs { rem[hi_word] >> hi_bit } else { 0 };
7265            if hi_word + 1 < nlimbs {
7266                d |= rem[hi_word + 1] << (32 - hi_bit);
7267            } else if carry > 0 {
7268                d |= (carry as u32) << (32 - hi_bit);
7269            }
7270            digit = d;
7271        }
7272        *buf.add(i) = digit.min(9) as u8;
7273        // Clear bits from position `shift` upward (keep remainder < 2^shift)
7274        if hi_bit == 0 {
7275            if hi_word < nlimbs { rem[hi_word] = 0; }
7276        } else {
7277            if hi_word < nlimbs {
7278                rem[hi_word] &= (1u32 << hi_bit) - 1;
7279            }
7280            for j in (hi_word + 1)..nlimbs { rem[j] = 0; }
7281        }
7282    }
7283    // Check if remainder is non-zero
7284    for i in 0..nlimbs { if rem[i] != 0 { return true; } }
7285    false
7286}
7287
7288/// Increment a decimal string stored at buf[0..*len] in-place.
7289unsafe fn increment_decimal(buf: *mut u8, len: &mut usize) {
7290    let mut j = *len;
7291    loop {
7292        if j == 0 {
7293            // Shift right and prepend '1'
7294            let l = *len;
7295            for i in (0..l).rev() { *buf.add(i + 1) = *buf.add(i); }
7296            *buf = b'1';
7297            *len = l + 1;
7298            return;
7299        }
7300        j -= 1;
7301        let d = *buf.add(j);
7302        if d < b'9' { *buf.add(j) = d + 1; return; }
7303        *buf.add(j) = b'0';
7304    }
7305}
7306
7307// Write float to dst. Returns bytes written. Does NOT handle width/flags padding.
7308unsafe fn format_f64_full(
7309    dst: *mut u8, val: f64, fmt_type: u8, precision: i32, flags: u8, uppercase: bool,
7310) -> usize {
7311    let precision = match fmt_type {
7312        FMT_E | FMT_G => precision.min(FMT_MAX_EG_PRECISION),
7313        _ => precision.min(FMT_MAX_FLOAT_PRECISION),
7314    };
7315    let mut pos = 0usize;
7316
7317    // NaN
7318    if val.is_nan() {
7319        let nan_s: &[u8] = if uppercase { b"NAN" } else { b"nan" };
7320        core::ptr::copy_nonoverlapping(nan_s.as_ptr(), dst, 3);
7321        return 3;
7322    }
7323    let neg = val.is_sign_negative();
7324    let v = if neg { -val } else { val };
7325
7326    // Inf
7327    if v.is_infinite() {
7328        if neg { *dst.add(pos) = b'-'; pos += 1; }
7329        else if flags & FLAG_PLUS != 0 { *dst.add(pos) = b'+'; pos += 1; }
7330        else if flags & FLAG_SPACE != 0 { *dst.add(pos) = b' '; pos += 1; }
7331        let inf_s: &[u8] = if uppercase { b"INF" } else { b"inf" };
7332        core::ptr::copy_nonoverlapping(inf_s.as_ptr(), dst.add(pos), 3);
7333        return pos + 3;
7334    }
7335
7336    // Sign
7337    if neg { *dst.add(pos) = b'-'; pos += 1; }
7338    else if flags & FLAG_PLUS != 0 { *dst.add(pos) = b'+'; pos += 1; }
7339    else if flags & FLAG_SPACE != 0 { *dst.add(pos) = b' '; pos += 1; }
7340
7341    // === Hex float ===
7342    if fmt_type == FMT_A {
7343        return pos + fmt_hex_float(dst.add(pos), val, precision, flags, uppercase);
7344    }
7345
7346    // === Decimal formats ===
7347    let p: usize;
7348    let mut exp: i32;
7349    let use_f: bool;
7350
7351    match fmt_type {
7352        FMT_G => {
7353            let gp = if precision < 0 { 6usize } else if precision == 0 { 1usize } else { precision as usize };
7354            exp = if v > 0.0 { compute_exp10(v) } else { 0 };
7355            use_f = exp >= -4 && exp < gp as i32;
7356            if use_f {
7357                p = if exp < 0 { gp + ((-exp) as usize - 1) }
7358                    else if (exp as usize) < gp { gp - exp as usize - 1 }
7359                    else { 0 };
7360            } else {
7361                p = gp - 1;
7362            }
7363        }
7364        FMT_E => {
7365            p = if precision < 0 { 6usize } else { precision as usize };
7366            exp = if v > 0.0 { compute_exp10(v) } else { 0 };
7367            use_f = false;
7368        }
7369        _ => {
7370            p = if precision < 0 { 6usize } else { precision as usize };
7371            exp = 0;
7372            use_f = true;
7373        }
7374    }
7375
7376    if v == 0.0 {
7377        *dst.add(pos) = b'0'; pos += 1;
7378        if !(fmt_type == FMT_G && flags & FLAG_HASH == 0) {
7379            if p > 0 || flags & FLAG_HASH != 0 {
7380                *dst.add(pos) = b'.'; pos += 1;
7381                for _ in 0..p { *dst.add(pos) = b'0'; pos += 1; }
7382            }
7383        }
7384        if !use_f {
7385            let ec = if uppercase { b'E' } else { b'e' };
7386            *dst.add(pos) = ec; pos += 1;
7387            *dst.add(pos) = b'+'; pos += 1;
7388            *dst.add(pos) = b'0'; pos += 1;
7389            *dst.add(pos) = b'0'; pos += 1;
7390        }
7391        return pos;
7392    }
7393
7394    // === %f format: exact bit-based arithmetic, returns early ===
7395    if use_f {
7396        let bits = v.to_bits();
7397        let raw_mant = bits & 0x000FFFFFFFFFFFFF;
7398        let raw_exp_bits = ((bits >> 52) & 0x7FF) as i32;
7399        let (mant_b, bin_exp) = if raw_exp_bits == 0 {
7400            (raw_mant, -1022i32)
7401        } else {
7402            (raw_mant | (1u64 << 52), raw_exp_bits - 1023)
7403        };
7404
7405        // Integer part as decimal string
7406        let mut ibuf = [0u8; 400];
7407        let mut ilen: usize;
7408        if bin_exp < 0 {
7409            ibuf[0] = b'0'; ilen = 1;
7410        } else if bin_exp <= 63 {
7411            let int_val = if bin_exp <= 52 { mant_b >> (52 - bin_exp) }
7412                          else { mant_b << (bin_exp - 52) };
7413            let (buf2, len2) = format_u64(int_val);
7414            ibuf[..len2].copy_from_slice(&buf2[..len2]);
7415            ilen = len2;
7416        } else {
7417            ilen = bigint_to_decimal(ibuf.as_mut_ptr(), mant_b, (bin_exp - 52) as u32);
7418        }
7419
7420        // Fractional digits
7421        let mut fbuf = [0u8; 1100];
7422        let mut has_rest = false;
7423        if p > 0 && bin_exp < 52 {
7424            let shift = (52 - bin_exp) as u32;
7425            let frac_bits = if bin_exp >= 0 { mant_b & ((1u64 << shift) - 1) } else { mant_b };
7426            if shift <= 124 {
7427                has_rest = frac_digits_u128(fbuf.as_mut_ptr(), frac_bits, shift, p + 1);
7428            } else {
7429                has_rest = frac_digits_bigint(fbuf.as_mut_ptr(), frac_bits, shift, p + 1);
7430            }
7431        }
7432
7433        // Rounding
7434        if p > 0 && bin_exp < 52 {
7435            let next_d = fbuf[p];
7436            let last_d = fbuf[p - 1];
7437            if next_d > 5 || (next_d == 5 && (has_rest || last_d & 1 != 0)) {
7438                let mut carry = true;
7439                for j in (0..p).rev() {
7440                    if !carry { break; }
7441                    fbuf[j] += 1;
7442                    if fbuf[j] < 10 { carry = false; break; }
7443                    fbuf[j] = 0;
7444                }
7445                if carry { increment_decimal(ibuf.as_mut_ptr(), &mut ilen); }
7446            }
7447        } else if p == 0 {
7448            // %.0f: round integer based on fractional part
7449            if bin_exp >= 0 && bin_exp < 52 {
7450                let shift = (52 - bin_exp) as u32;
7451                let frac_bits = mant_b & ((1u64 << shift) - 1);
7452                let half = 1u64 << (shift - 1);
7453                let last_d = ibuf[ilen - 1] - b'0';
7454                if frac_bits > half || (frac_bits == half && last_d & 1 != 0) {
7455                    increment_decimal(ibuf.as_mut_ptr(), &mut ilen);
7456                }
7457            }
7458        }
7459
7460        // Output
7461        core::ptr::copy_nonoverlapping(ibuf.as_ptr(), dst.add(pos), ilen);
7462        pos += ilen;
7463        if p > 0 || flags & FLAG_HASH != 0 {
7464            *dst.add(pos) = b'.'; pos += 1;
7465            for i in 0..p { *dst.add(pos) = b'0' + fbuf[i]; pos += 1; }
7466        }
7467        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7468            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7469            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7470        }
7471        return pos;
7472    }
7473
7474    // === %e/%g format: exact big-integer digit extraction ===
7475    // D = floor(v * 10^(p+1-exp)), using v = mant_b * 2^(bin_exp-52)
7476    let mut fbuf = [0u8; 20];
7477    let mut int_part: u64;
7478    {
7479        let bits_v = v.to_bits();
7480        let raw_mant_v = bits_v & 0x000FFFFFFFFFFFFF;
7481        let raw_exp_v = ((bits_v >> 52) & 0x7FF) as i32;
7482        let (mant_b_v, bin_exp_v) = if raw_exp_v == 0 {
7483            (raw_mant_v, -1022i32)
7484        } else {
7485            (raw_mant_v | (1u64 << 52), raw_exp_v - 1023)
7486        };
7487
7488        let s: i32 = (p as i32) + 1 - exp;
7489        let bs: i32 = bin_exp_v - 52 + s;
7490
7491        let mut limbs = [0u32; 40];
7492        limbs[0] = mant_b_v as u32;
7493        limbs[1] = (mant_b_v >> 32) as u32;
7494        let mut nlimbs: usize = if limbs[1] != 0 { 2 } else { 1 };
7495
7496        if s > 0 {
7497            for _ in 0..(s as usize) {
7498                let mut carry = 0u64;
7499                for j in 0..nlimbs {
7500                    let val = limbs[j] as u64 * 5 + carry;
7501                    limbs[j] = val as u32;
7502                    carry = val >> 32;
7503                }
7504                if carry > 0 { limbs[nlimbs] = carry as u32; nlimbs += 1; }
7505            }
7506        }
7507
7508        if bs > 0 {
7509            let ws = (bs as u32 / 32) as usize;
7510            let bit = bs as u32 % 32;
7511            if ws > 0 {
7512                let mut i = nlimbs;
7513                while i > 0 { i -= 1; if i + ws < 40 { limbs[i + ws] = limbs[i]; } limbs[i] = 0; }
7514                nlimbs += ws;
7515            }
7516            if bit > 0 {
7517                let mut carry = 0u32;
7518                for i in ws..nlimbs {
7519                    let new_val = (limbs[i] << bit) | carry;
7520                    carry = limbs[i] >> (32 - bit);
7521                    limbs[i] = new_val;
7522                }
7523                if carry > 0 && nlimbs < 40 { limbs[nlimbs] = carry; nlimbs += 1; }
7524            }
7525        }
7526
7527        let mut has_rest = false;
7528        if s < 0 {
7529            for _ in 0..(-s as usize) {
7530                let mut rem = 0u64;
7531                for i in (0..nlimbs).rev() {
7532                    let val = (rem << 32) | limbs[i] as u64;
7533                    limbs[i] = (val / 5) as u32;
7534                    rem = val % 5;
7535                }
7536                if rem != 0 { has_rest = true; }
7537            }
7538        }
7539
7540        if bs < 0 {
7541            let rshift = (-bs) as u32;
7542            let ws = (rshift / 32) as usize;
7543            let bit = rshift % 32;
7544            if ws > 0 {
7545                for j in 0..ws.min(nlimbs) { if limbs[j] != 0 { has_rest = true; } }
7546                for i in ws..nlimbs { limbs[i - ws] = limbs[i]; }
7547                nlimbs = nlimbs.saturating_sub(ws);
7548            }
7549            if bit > 0 && nlimbs > 0 {
7550                let mask = (1u32 << bit) - 1;
7551                if limbs[0] & mask != 0 { has_rest = true; }
7552                for i in 0..nlimbs - 1 {
7553                    limbs[i] = (limbs[i] >> bit) | (limbs[i + 1] << (32 - bit));
7554                }
7555                limbs[nlimbs - 1] >>= bit;
7556            }
7557        }
7558
7559        while nlimbs > 0 && limbs[nlimbs - 1] == 0 { nlimbs -= 1; }
7560
7561        let ndigits = p + 2;
7562        let mut all_digits = [0u8; 25];
7563        let mut nd = 0usize;
7564        if nlimbs > 0 {
7565            loop {
7566                let mut all_zero = true;
7567                for i in 0..nlimbs { if limbs[i] != 0 { all_zero = false; break; } }
7568                if all_zero { break; }
7569                let mut rem64 = 0u64;
7570                for i in (0..nlimbs).rev() {
7571                    let val = (rem64 << 32) | limbs[i] as u64;
7572                    limbs[i] = (val / 10) as u32;
7573                    rem64 = val % 10;
7574                }
7575                if nd < 25 { all_digits[nd] = rem64 as u8; }
7576                nd += 1;
7577            }
7578        }
7579
7580        if nd >= ndigits {
7581            for i in 0..ndigits { fbuf[ndigits - 1 - i] = all_digits[i]; }
7582        } else {
7583            for i in 0..nd { fbuf[ndigits - 1 - i] = all_digits[i]; }
7584            for i in nd..ndigits { fbuf[ndigits - 1 - i] = 0; }
7585        }
7586
7587        int_part = fbuf[0] as u64;
7588
7589        // Round half to even: next_d is the rounding digit beyond precision
7590        if p > 0 {
7591            let next_d = fbuf[p + 1];
7592            let last_d = fbuf[p];
7593            if next_d > 5 || (next_d == 5 && (has_rest || last_d & 1 != 0)) {
7594                let mut carry = true;
7595                for j in (1..=p).rev() {
7596                    if !carry { break; }
7597                    let d = fbuf[j] + 1;
7598                    if d < 10 { fbuf[j] = d; carry = false; break; }
7599                    fbuf[j] = 0;
7600                }
7601                if carry { int_part += 1; }
7602            }
7603        } else {
7604            let next_d = fbuf[1];
7605            if next_d > 5 || (next_d == 5 && (has_rest || int_part & 1 != 0)) {
7606                int_part += 1;
7607            }
7608        }
7609
7610        // fbuf[1..=p] are now the fractional digits for output
7611        // Shift them to fbuf[0..p] so output code can index fbuf[0..p]
7612        for i in 0..p { fbuf[i] = fbuf[i + 1]; }
7613    }
7614
7615    if !use_f && int_part >= 10 {
7616        exp += 1;
7617        int_part = 1;
7618    }
7619
7620    // Format output
7621    if use_f {
7622        // %f style
7623        let (ibuf, ilen) = format_u64(int_part);
7624        core::ptr::copy_nonoverlapping(ibuf.as_ptr(), dst.add(pos), ilen);
7625        pos += ilen;
7626        if p > 0 || flags & FLAG_HASH != 0 {
7627            *dst.add(pos) = b'.'; pos += 1;
7628            for idx in 0..p { *dst.add(pos) = b'0' + fbuf[idx]; pos += 1; }
7629        }
7630        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7631            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7632            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7633        }
7634    } else {
7635        // %e style
7636        *dst.add(pos) = b'0' + int_part as u8; pos += 1;
7637        if p > 0 || flags & FLAG_HASH != 0 {
7638            *dst.add(pos) = b'.'; pos += 1;
7639            for idx in 0..p { *dst.add(pos) = b'0' + fbuf[idx]; pos += 1; }
7640        }
7641        if fmt_type == FMT_G && flags & FLAG_HASH == 0 {
7642            while pos > 0 && *dst.add(pos - 1) == b'0' { pos -= 1; }
7643            if pos > 0 && *dst.add(pos - 1) == b'.' { pos -= 1; }
7644        }
7645        let ec = if uppercase { b'E' } else { b'e' };
7646        *dst.add(pos) = ec; pos += 1;
7647        *dst.add(pos) = if exp < 0 { b'-' } else { b'+' }; pos += 1;
7648        let eabs = if exp < 0 { (-exp) as u32 } else { exp as u32 };
7649        if eabs < 10 { *dst.add(pos) = b'0'; pos += 1; }
7650        let (ebuf, elen) = format_u64(eabs as u64);
7651        core::ptr::copy_nonoverlapping(ebuf.as_ptr(), dst.add(pos), elen);
7652        pos += elen;
7653    }
7654
7655    pos
7656}
7657
7658// Compute decimal exponent: floor(log10(v)) with correction
7659unsafe fn compute_exp10(v: f64) -> i32 {
7660    let e = libm::floor(libm::log10(v)) as i32;
7661    let probe = v / libm::pow(10.0, e as f64);
7662    if probe >= 10.0 { e + 1 }
7663    else if probe < 1.0 { e - 1 }
7664    else { e }
7665}
7666
7667// Write hex float to dst. Returns bytes written.
7668unsafe fn fmt_hex_float(dst: *mut u8, val: f64, precision: i32, _flags: u8, uppercase: bool) -> usize {
7669    // Handle zero (and negative zero) specially
7670    if val.to_bits() & 0x7FFFFFFFFFFFFFFF == 0 {
7671        let lc = !uppercase;
7672        let pfx: &[u8] = if lc { b"0x" } else { b"0X" };
7673        let p = if precision < 0 { 0usize } else { precision as usize };
7674        let mut pos = 0usize;
7675        core::ptr::copy_nonoverlapping(pfx.as_ptr(), dst.add(pos), 2); pos += 2;
7676        *dst.add(pos) = b'0'; pos += 1;
7677        if p > 0 {
7678            *dst.add(pos) = b'.'; pos += 1;
7679            for _ in 0..p { *dst.add(pos) = b'0'; pos += 1; }
7680        }
7681        let pc = if lc { b'p' } else { b'P' };
7682        *dst.add(pos) = pc; pos += 1;
7683        *dst.add(pos) = b'+'; pos += 1;
7684        *dst.add(pos) = b'0'; pos += 1;
7685        return pos;
7686    }
7687    let bits = val.to_bits();
7688    let exp_bits = ((bits >> 52) & 0x7FF) as i32;
7689    let mant_bits = bits & 0x000FFFFFFFFFFFFF;
7690    let (mut e, mut m) = if exp_bits == 0 { (1 - 1023, mant_bits) } else { (exp_bits - 1023, mant_bits | (1u64 << 52)) };
7691    // musl normalizes subnormals so the leading digit is always 1, which
7692    // lets the exponent go below -1022 (e.g. 0x1p-1074 for the smallest).
7693    if exp_bits == 0 && m != 0 {
7694        let shift = m.leading_zeros() as i32 - 11;
7695        m <<= shift;
7696        e -= shift;
7697    }
7698    let explicit = precision >= 0;
7699    let p = if explicit { precision as usize } else { 13usize };
7700    let mut pos = 0usize;
7701    let lc = !uppercase;
7702    let pfx: &[u8] = if lc { b"0x" } else { b"0X" };
7703    core::ptr::copy_nonoverlapping(pfx.as_ptr(), dst.add(pos), 2); pos += 2;
7704
7705    // Leading digit from bit 52 (1 for every normalized value).
7706    let lead_pos = pos;
7707    let mut lead = ((m >> 52) & 0xF) as u8;
7708    *dst.add(pos) = hex_digit_char(lead, lc); pos += 1;
7709    let mut frac_start = pos;
7710    if p > 0 {
7711        *dst.add(pos) = b'.'; pos += 1;
7712        frac_start = pos;
7713    }
7714
7715    // Extract p hex digits from the fraction, most significant nibble first.
7716    let mut rm = m;
7717    for _ in 0..p {
7718        let nib = ((rm >> 48) & 0xF) as u8;
7719        *dst.add(pos) = hex_digit_char(nib, lc); pos += 1;
7720        rm <<= 4;
7721    }
7722
7723    // Round to nearest, ties to even, based on the next nibble.
7724    let round_nib = ((rm >> 48) & 0xF) as u8;
7725    let rest = rm & 0x0000FFFFFFFFFFFF;
7726    let last_nib = if p > 0 {
7727        hex_val(*dst.add(pos - 1)).unwrap_or(0)
7728    } else {
7729        lead
7730    };
7731    let should_round = round_nib > 8 || (round_nib == 8 && (rest != 0 || (last_nib & 1) != 0));
7732    if should_round {
7733        let mut j = pos;
7734        loop {
7735            if j == frac_start {
7736                // Carry out of the fraction into the leading digit.
7737                lead += 1;
7738                *dst.add(lead_pos) = hex_digit_char(lead, lc);
7739                break;
7740            }
7741            j -= 1;
7742            let v = hex_val(*dst.add(j)).unwrap_or(0);
7743            if v < 15 {
7744                *dst.add(j) = hex_digit_char(v + 1, lc);
7745                break;
7746            }
7747            *dst.add(j) = b'0';
7748        }
7749    }
7750
7751    // With no explicit precision, print the shortest exact representation:
7752    // trim trailing fractional zeros and drop the radix point if empty.
7753    if !explicit {
7754        while pos > frac_start && *dst.add(pos - 1) == b'0' {
7755            pos -= 1;
7756        }
7757        if pos == frac_start {
7758            pos = frac_start - 1;
7759        }
7760    }
7761
7762    // Exponent
7763    let pc = if lc { b'p' } else { b'P' };
7764    *dst.add(pos) = pc; pos += 1;
7765    *dst.add(pos) = if e < 0 { b'-' } else { b'+' }; pos += 1;
7766    let eabs = if e < 0 { (-e) as u32 } else { e as u32 };
7767    let (ebuf, elen) = format_u64(eabs as u64);
7768    core::ptr::copy_nonoverlapping(ebuf.as_ptr(), dst.add(pos), elen);
7769    pos += elen;
7770    pos
7771}
7772
7773#[inline]
7774fn hex_digit_char(v: u8, lowercase: bool) -> u8 {
7775    if v < 10 { b'0' + v }
7776    else if lowercase { b'a' + v - 10 }
7777    else { b'A' + v - 10 }
7778}
7779
7780#[inline]
7781
7782// Apply width and flags padding to a formatted string in buf[0..len].
7783// Writes the final result to dst. Returns total bytes written.
7784unsafe fn apply_width_flags(
7785    dst: *mut u8, buf: *const u8, len: usize, width: usize, flags: u8,
7786) -> usize {
7787    if len >= width {
7788        core::ptr::copy_nonoverlapping(buf, dst, len);
7789        return len;
7790    }
7791    let pad = width - len;
7792    let pad_char = if flags & FLAG_ZERO != 0 && flags & FLAG_MINUS == 0 { b'0' } else { b' ' };
7793    if flags & FLAG_MINUS != 0 {
7794        // Left align
7795        core::ptr::copy_nonoverlapping(buf, dst, len);
7796        for i in 0..pad { *dst.add(len + i) = pad_char; }
7797    } else {
7798        // Right align
7799        // For zero-padded numbers, sign goes before zeros
7800        if flags & FLAG_ZERO != 0 && len > 0 {
7801            let first = *buf;
7802            if first == b'-' || first == b'+' || first == b' ' {
7803                *dst = first;
7804                for i in 0..pad { *dst.add(1 + i) = pad_char; }
7805                core::ptr::copy_nonoverlapping(buf.add(1), dst.add(1 + pad), len - 1);
7806                return width;
7807            }
7808        }
7809        for i in 0..pad { *dst.add(i) = pad_char; }
7810        core::ptr::copy_nonoverlapping(buf, dst.add(pad), len);
7811    }
7812    width
7813}
7814
7815#[no_mangle]
7816pub unsafe extern "C" fn vprintf(fmt: *const c_char, mut args: VaList) -> c_int {
7817    impl_format!(fmt, args,
7818        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stdout); },
7819        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stdout); }
7820    )
7821}
7822
7823#[no_mangle]
7824pub unsafe extern "C" fn vfprintf(stream: *mut FILE, fmt: *const c_char, mut args: VaList) -> c_int {
7825    impl_format!(fmt, args,
7826        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stream); },
7827        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stream); }
7828    )
7829}
7830
7831#[no_mangle]
7832pub unsafe extern "C" fn printf(fmt: *const c_char, mut args: ...) -> c_int {
7833    impl_format!(fmt, args,
7834        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stdout); },
7835        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stdout); }
7836    )
7837}
7838
7839#[no_mangle]
7840pub unsafe extern "C" fn fprintf(stream: *mut FILE, fmt: *const c_char, mut args: ...) -> c_int {
7841    impl_format!(fmt, args,
7842        |c: u8| { let _ = fwrite(&c as *const u8 as *const c_void, 1, 1, stream); },
7843        |s: *const u8, len: usize| { let _ = fwrite(s as *const c_void, 1, len, stream); }
7844    )
7845}
7846
7847unsafe fn format_write_fd(fd: c_int, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
7848    // cgroupfs (and some other pseudo-filesystems) parse one command per
7849    // write() call, so the whole formatted string must go out at once.
7850    let mut stack = [0u8; FMT_WRITE_BUF];
7851    let mut a1 = args.clone();
7852    let n = format_to_buf(stack.as_mut_ptr(), stack.len(), fmt, &mut a1);
7853    if n < 0 { return -1; }
7854    if (n as usize) < stack.len() {
7855        let w = crate::write(fd, stack.as_ptr() as *const c_void, n as usize);
7856        if w < 0 { return -1; }
7857        return n;
7858    }
7859    let heap = crate::malloc(n as usize + 1) as *mut u8;
7860    if heap.is_null() { return -1; }
7861    let mut a2 = args.clone();
7862    let n2 = format_to_buf(heap, n as usize + 1, fmt, &mut a2);
7863    if n2 < 0 { crate::free(heap as *mut c_void); return -1; }
7864    let w = crate::write(fd, heap as *const c_void, n2 as usize);
7865    crate::free(heap as *mut c_void);
7866    if w < 0 { return -1; }
7867    n2
7868}
7869
7870#[no_mangle]
7871pub unsafe extern "C" fn dprintf(fd: c_int, fmt: *const c_char, mut args: ...) -> c_int {
7872    format_write_fd(fd, fmt, &mut args)
7873}
7874
7875#[no_mangle]
7876pub unsafe extern "C" fn vdprintf(fd: c_int, fmt: *const c_char, mut args: VaList) -> c_int {
7877    format_write_fd(fd, fmt, &mut args)
7878}
7879
7880// ============================================================
7881// sprintf / snprintf / vsprintf / vsnprintf
7882// ============================================================
7883
7884unsafe fn format_to_buf(buf: *mut u8, cap: usize, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
7885    // Reuse the shared format engine with buffer writer closures instead of
7886    // maintaining a second copy of the conversion table.
7887    let pos = core::cell::Cell::new(0usize);
7888    let write_char = |c: u8| {
7889        let p = pos.get();
7890        if p < cap { *buf.add(p) = c; }
7891        pos.set(p + 1);
7892    };
7893    let write_str = |s: *const u8, len: usize| {
7894        let p = pos.get();
7895        for k in 0..len {
7896            if p + k < cap { *buf.add(p + k) = *s.add(k); }
7897        }
7898        pos.set(p + len);
7899    };
7900    let count = impl_format!(fmt, *args, write_char, write_str);
7901    if cap > 0 {
7902        let end = core::cmp::min(count as usize, cap - 1);
7903        *buf.add(end) = 0;
7904    }
7905    count
7906}
7907
7908#[no_mangle]
7909pub unsafe extern "C" fn vsprintf(buf: *mut c_char, fmt: *const c_char, mut args: VaList) -> c_int {
7910    format_to_buf(buf as *mut u8, usize::MAX, fmt, &mut args)
7911}
7912
7913#[no_mangle]
7914pub unsafe extern "C" fn vsnprintf(buf: *mut c_char, size: usize, fmt: *const c_char, mut args: VaList) -> c_int {
7915    format_to_buf(buf as *mut u8, size, fmt, &mut args)
7916}
7917
7918#[no_mangle]
7919pub unsafe extern "C" fn sprintf(buf: *mut c_char, fmt: *const c_char, mut args: ...) -> c_int {
7920    format_to_buf(buf as *mut u8, usize::MAX, fmt, &mut args)
7921}
7922
7923#[no_mangle]
7924pub unsafe extern "C" fn snprintf(buf: *mut c_char, size: usize, fmt: *const c_char, mut args: ...) -> c_int {
7925    format_to_buf(buf as *mut u8, size, fmt, &mut args)
7926}
7927
7928#[no_mangle]
7929pub unsafe extern "C" fn vasprintf(strp: *mut *mut c_char, fmt: *const c_char, ap: VaList) -> c_int {
7930    if strp.is_null() {
7931        ERRNO!() = EINVAL;
7932        return -1;
7933    }
7934    let len = vsnprintf(core::ptr::null_mut(), 0, fmt, ap.clone());
7935    if len < 0 {
7936        *strp = core::ptr::null_mut();
7937        return -1;
7938    }
7939    let p = malloc((len as usize) + 1) as *mut c_char;
7940    if p.is_null() {
7941        *strp = core::ptr::null_mut();
7942        return -1;
7943    }
7944    let ret = vsnprintf(p, (len as usize) + 1, fmt, ap.clone());
7945    if ret < 0 {
7946        free(p as *mut c_void);
7947        *strp = core::ptr::null_mut();
7948        return -1;
7949    }
7950    *strp = p;
7951    ret
7952}
7953
7954#[no_mangle]
7955pub unsafe extern "C" fn asprintf(strp: *mut *mut c_char, fmt: *const c_char, args: ...) -> c_int {
7956    vasprintf(strp, fmt, args)
7957}
7958
7959// ============================================================
7960// scanf / vscanf / fscanf / vfscanf / sscanf / vsscanf
7961// ============================================================
7962
7963
7964#[inline]
7965fn is_ws_byte(c: u8) -> bool {
7966    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == 0x0b || c == 0x0c
7967}
7968
7969// Scan integer with position tracking. Returns (value, is_negative, success).
7970// base: 0=auto, 8=octal, 10=decimal, 16=hex
7971unsafe fn scan_int_val(
7972    buf: *const u8, pos: &mut usize, buf_len: usize, base: u32, width: usize,
7973) -> (u64, bool, bool) {
7974    let start = *pos;
7975    let max = if width > 0 { (start + width).min(buf_len) } else { buf_len };
7976    let neg = if *pos < max && *buf.add(*pos) == b'-' { *pos += 1; true }
7977    else if *pos < max && *buf.add(*pos) == b'+' { *pos += 1; false }
7978    else { false };
7979    if *pos >= max { *pos = start; return (0, false, false); }
7980
7981    let mut base = base;
7982    if base == 0 || base == 16 {
7983        if *buf.add(*pos) == b'0' && *pos + 1 < max
7984            && (*buf.add(*pos + 1) == b'x' || *buf.add(*pos + 1) == b'X')
7985        {
7986            // musl treats "0x" without a following hex digit as a failed
7987            // conversion, not as the number zero.
7988            let has_digit = *pos + 2 < max && hex_val(*buf.add(*pos + 2)).is_some();
7989            *pos += 2;
7990            if !has_digit {
7991                return (0, neg, false);
7992            }
7993            base = 16;
7994        } else if base == 0 {
7995            base = 8;
7996        }
7997    }
7998    if base == 0 { base = 10; }
7999
8000    let mut val: u64 = 0;
8001    let mut found = false;
8002    while *pos < max {
8003        let c = *buf.add(*pos);
8004        let d: Option<u64> = match base {
8005            8 => if c >= b'0' && c <= b'7' { Some((c - b'0') as u64) } else { None },
8006            10 => if c >= b'0' && c <= b'9' { Some((c - b'0') as u64) } else { None },
8007            16 => hex_val(c).map(|v| v as u64),
8008            _ => None,
8009        };
8010        match d {
8011            Some(digit) => {
8012                val = val.wrapping_mul(base as u64).wrapping_add(digit);
8013                *pos += 1;
8014                found = true;
8015            }
8016            None => break,
8017        }
8018    }
8019    if !found { *pos = start; return (0, false, false); }
8020    (val, neg, true)
8021}
8022
8023// Scan float with position tracking. Returns (value, success).
8024unsafe fn scan_float_val(
8025    buf: *const u8, pos: &mut usize, buf_len: usize, width: usize,
8026) -> (f64, bool) {
8027    let start = *pos;
8028    let max = if width > 0 { (start + width).min(buf_len) } else { buf_len };
8029    let neg = if *pos < max && *buf.add(*pos) == b'-' { *pos += 1; true }
8030    else if *pos < max && *buf.add(*pos) == b'+' { *pos += 1; false }
8031    else { false };
8032    // inf/nan
8033    if *pos + 2 < max {
8034        let (c0,c1,c2) = (*buf.add(*pos), *buf.add(*pos+1), *buf.add(*pos+2));
8035        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); }
8036        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); }
8037    }
8038    // hex float
8039    if *pos+1 < max && *buf.add(*pos)==b'0' && (*buf.add(*pos+1)==b'x'||*buf.add(*pos+1)==b'X') {
8040        *pos += 2;
8041        let mut val: f64 = 0.0; let mut found = false; let mut frac_scale = 1.0f64; let mut in_frac = false;
8042        while *pos < max {
8043            if let Some(d) = hex_val(*buf.add(*pos)) {
8044                if in_frac { frac_scale /= 16.0; val += d as f64 * frac_scale; } else { val = val * 16.0 + d as f64; }
8045                *pos += 1; found = true;
8046            } else if *buf.add(*pos)==b'.' && !in_frac { in_frac = true; *pos += 1; } else { break; }
8047        }
8048        if !found { *pos = start; return (0.0, false); }
8049        // p exponent
8050        if *pos < max && (*buf.add(*pos)==b'p'||*buf.add(*pos)==b'P') {
8051            *pos += 1;
8052            let mut eneg = false;
8053            if *pos<max && *buf.add(*pos)==b'-' { eneg=true; *pos+=1; }
8054            else if *pos<max && *buf.add(*pos)==b'+' { *pos+=1; }
8055            let mut ev: i32 = 0; let mut ef = false;
8056            while *pos<max && *buf.add(*pos)>=b'0' && *buf.add(*pos)<=b'9' {
8057                ev = ev.saturating_mul(10).saturating_add((*buf.add(*pos)-b'0') as i32).min(1_000_000);
8058                *pos+=1; ef=true;
8059            }
8060            if !ef { return (0.0, false); }
8061            if eneg { ev = -ev; }
8062            val *= libm::pow(2.0, ev as f64);
8063        }
8064        return (if neg{-val}else{val}, true);
8065    }
8066    let token_start = start;
8067    let mut i = start;
8068    let mut saw_digit = false;
8069    let mut saw_dot = false;
8070    let mut saw_exp = false;
8071    let mut first = true;
8072    while i < max {
8073        let c = *buf.add(i);
8074        if (c == b'+' || c == b'-') && first {
8075            i += 1; first = false; continue;
8076        }
8077        if c >= b'0' && c <= b'9' {
8078            saw_digit = true; i += 1; first = false; continue;
8079        }
8080        if c == b'.' && !saw_dot && !saw_exp {
8081            saw_dot = true; i += 1; first = false; continue;
8082        }
8083        if (c == b'e' || c == b'E') && !saw_exp && saw_digit {
8084            saw_exp = true; i += 1; first = true; continue;
8085        }
8086        break;
8087    }
8088    if !saw_digit { return (0.0, false); }
8089    let s = core::str::from_utf8_unchecked(core::slice::from_raw_parts(buf.add(token_start), i - token_start));
8090    match <f64 as core::str::FromStr>::from_str(s) {
8091        Ok(v) => { *pos = i; return (v, true); }
8092        Err(_) => { return (0.0, false); }
8093    }
8094}
8095
8096/// Store a scanned integer with the width selected by the length modifier.
8097/// Without this, `%ld`/`%lu` silently truncate to 32 bits.
8098// Length-modifier encoding shared by the scanf parser and integer store.
8099const LEN_NONE: u8 = 0;
8100const LEN_SHORT: u8 = 1;
8101const LEN_CHAR: u8 = 2;
8102const LEN_LONG: u8 = 3;
8103const LEN_LONG_LONG: u8 = 4;
8104const LEN_LONG_DOUBLE: u8 = 5;
8105
8106unsafe fn store_scan_int(dest: *mut c_void, len_mod: u8, val: u64, neg: bool) {
8107    let sv: i64 = if neg { (val as i64).wrapping_neg() } else { val as i64 };
8108    match len_mod {
8109        LEN_CHAR => *(dest as *mut i8) = sv as i8,
8110        LEN_SHORT => *(dest as *mut i16) = sv as i16,
8111        LEN_LONG | LEN_LONG_LONG => *(dest as *mut i64) = sv,
8112        _ => *(dest as *mut i32) = sv as i32,
8113    }
8114}
8115
8116/// Advance over up to `max` input bytes accepted by `accept` and return how
8117/// many were consumed.  The scanf text conversions differ only in this
8118/// predicate; the caller copies the resulting span into its destination.
8119#[inline]
8120unsafe fn scan_span<F: Fn(u8) -> bool>(
8121    buf: *const u8,
8122    buf_len: usize,
8123    p: &mut usize,
8124    max: usize,
8125    accept: F,
8126) -> usize {
8127    let start = *p;
8128    let mut n = 0usize;
8129    while n < max && *p < buf_len {
8130        let c = *buf.add(*p);
8131        if !accept(c) { break; }
8132        *p += 1;
8133        n += 1;
8134    }
8135    *p - start
8136}
8137
8138const SCAN_BUF_INIT: usize = 4096;
8139
8140// Comprehensive scanf parser with position tracking.
8141// consumed: if non-null, stores number of bytes consumed from buf.
8142unsafe fn do_vsscanf(
8143    buf: *const u8, buf_len: usize, fmt: *const c_char, args: &mut VaList<'_>, consumed: *mut usize,
8144) -> c_int {
8145    let mut p = 0usize;
8146    let mut fi = 0usize;
8147    let mut assigned = 0i32;
8148    let mut input_eof = false;
8149    loop {
8150        let fc = *fmt.add(fi) as u8;
8151        if fc == 0 { break; }
8152        if is_ws_byte(fc) {
8153            while is_ws_byte(*fmt.add(fi) as u8) { fi += 1; }
8154            while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8155            continue;
8156        }
8157        if fc != b'%' {
8158            if p >= buf_len { input_eof = true; break; }
8159            if *buf.add(p) != fc { break; }
8160            p += 1; fi += 1; continue;
8161        }
8162        fi += 1;
8163        // %%
8164        if *fmt.add(fi) as u8 == b'%' {
8165            if p >= buf_len { input_eof = true; break; }
8166            if *buf.add(p) != b'%' { break; }
8167            p += 1; fi += 1; continue;
8168        }
8169        let suppress = if *fmt.add(fi) as u8 == b'*' { fi += 1; true } else { false };
8170        let mut width: usize = 0;
8171        let mut width_overflow = false;
8172        while (*fmt.add(fi) as u8) >= b'0' && (*fmt.add(fi) as u8) <= b'9' {
8173            let digit = ((*fmt.add(fi) as u8) - b'0') as usize;
8174            if width > (c_int::MAX as usize - digit) / 10 {
8175                width_overflow = true;
8176                break;
8177            }
8178            width = width * 10 + digit;
8179            fi += 1;
8180        }
8181        if width_overflow { input_eof = true; break; }
8182        let mut alloc = false;
8183        if *fmt.add(fi) as u8 == b'm' {
8184            alloc = !suppress;
8185            fi += 1;
8186        }
8187        let mut len_mod = LEN_NONE;
8188        match *fmt.add(fi) as u8 {
8189            b'h' => { fi += 1; if *fmt.add(fi) as u8 == b'h' { fi += 1; len_mod = LEN_CHAR; } else { len_mod = LEN_SHORT; } }
8190            b'l' => { fi += 1; if *fmt.add(fi) as u8 == b'l' { fi += 1; len_mod = LEN_LONG_LONG; } else { len_mod = LEN_LONG; } }
8191            b'j' => { fi += 1; len_mod = LEN_LONG_LONG; }
8192            b'z' | b't' => { fi += 1; len_mod = LEN_LONG; }
8193            b'L' => { fi += 1; len_mod = LEN_LONG_DOUBLE; }
8194            _ => {}
8195        }
8196        let spec = *fmt.add(fi) as u8;
8197        let (real_spec, _real_len) = if spec==b'C' {(b'c',3u8)} else if spec==b'S' {(b's',3u8)} else {(spec,len_mod)};
8198        match real_spec {
8199            b'n' => {
8200                if !suppress {
8201                    let out = args.next_arg::<*mut c_void>();
8202                    if !out.is_null() {
8203                        match len_mod {
8204                            LEN_SHORT => *(out as *mut i16) = p as i16,
8205                            LEN_CHAR => *(out as *mut i8) = p as i8,
8206                            LEN_LONG | LEN_LONG_LONG => *(out as *mut i64) = p as i64,
8207                            _ => *(out as *mut c_int) = p as c_int,
8208                        }
8209                    }
8210                }
8211            }
8212            b'd' | b'u' => {
8213                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8214                if p >= buf_len { input_eof = true; break; }
8215                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8216                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 10, width);
8217                if !ok { break; }
8218                if let Some(out) = dest { if !out.is_null() {
8219                    store_scan_int(out, len_mod, val, neg);
8220                }}
8221                if !suppress { assigned += 1; }
8222            }
8223            b'i' => {
8224                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8225                if p >= buf_len { input_eof = true; break; }
8226                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8227                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 0, width);
8228                if !ok { break; }
8229                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8230                if !suppress { assigned += 1; }
8231            }
8232            b'o' => {
8233                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8234                if p >= buf_len { input_eof = true; break; }
8235                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8236                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 8, width);
8237                if !ok { break; }
8238                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8239                if !suppress { assigned += 1; }
8240            }
8241            b'x' | b'X' => {
8242                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8243                if p >= buf_len { input_eof = true; break; }
8244                let dest = if !suppress { Some(args.next_arg::<*mut c_void>()) } else { None };
8245                let (val, neg, ok) = scan_int_val(buf, &mut p, buf_len, 16, width);
8246                if !ok { break; }
8247                if let Some(out) = dest { if !out.is_null() { store_scan_int(out, len_mod, val, neg); } }
8248                if !suppress { assigned += 1; }
8249            }
8250            b'p' => {
8251                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8252                if p >= buf_len { input_eof = true; break; }
8253                let dest = if !suppress { Some(args.next_arg::<*mut *mut c_void>()) } else { None };
8254                let (val, _, ok) = scan_int_val(buf, &mut p, buf_len, 16, width);
8255                if !ok { break; }
8256                if let Some(out) = dest { if !out.is_null() { *out = val as usize as *mut c_void; } }
8257                if !suppress { assigned += 1; }
8258            }
8259            b'a' | b'e' | b'f' | b'g' | b'A' | b'E' | b'F' | b'G' => {
8260                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8261                if p >= buf_len { input_eof = true; break; }
8262                let (val, ok) = scan_float_val(buf, &mut p, buf_len, width);
8263                if !ok { break; }
8264                if !suppress {
8265                    if _real_len == LEN_LONG {
8266                        let out = args.next_arg::<*mut f64>(); if !out.is_null() { *out = val; }
8267                    } else if _real_len == LEN_LONG_DOUBLE {
8268                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
8269                        { let out = args.next_arg::<*mut f128>(); if !out.is_null() { *out = f64_to_f128(val); } }
8270                        #[cfg(target_arch = "x86_64")]
8271                        { let out = args.next_arg::<*mut f64>(); if !out.is_null() { *out = val; } }
8272                    } else {
8273                        let out = args.next_arg::<*mut f32>(); if !out.is_null() { *out = val as f32; }
8274                    }
8275                }
8276                if !suppress { assigned += 1; }
8277            }
8278            b'c' => {
8279                let w = if width > 0 { width } else { 1 };
8280                if p >= buf_len { input_eof = true; break; }
8281                let start_p = p;
8282                let n = scan_span(buf, buf_len, &mut p, w, |_| true);
8283                if n != w { p = start_p; input_eof = true; break; }
8284                if alloc {
8285                    let out = args.next_arg::<*mut *mut c_char>();
8286                    let s = crate::malloc(w + 1) as *mut c_char;
8287                    if s.is_null() {
8288                        if !consumed.is_null() { *consumed = p; }
8289                        return if assigned == 0 { -1 } else { assigned };
8290                    }
8291                    core::ptr::copy_nonoverlapping(buf.add(start_p), s as *mut u8, w);
8292                    *s.add(w) = 0;
8293                    if !out.is_null() { *out = s; } else { crate::free(s as *mut c_void); }
8294                } else {
8295                    let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8296                    if !dest_ptr.is_null() {
8297                        core::ptr::copy_nonoverlapping(buf.add(start_p), dest_ptr as *mut u8, w);
8298                    }
8299                }
8300                if !suppress { assigned += 1; }
8301            }
8302            b's' => {
8303                while p < buf_len && is_ws_byte(*buf.add(p)) { p += 1; }
8304                if p >= buf_len { input_eof = true; break; }
8305                let w = if width > 0 { width } else { usize::MAX };
8306                let start_p = p;
8307                let n = scan_span(buf, buf_len, &mut p, w, |c| c != 0 && !is_ws_byte(c));
8308                if n == 0 { break; }
8309                if alloc {
8310                    let out = args.next_arg::<*mut *mut c_char>();
8311                    let s = crate::malloc(n + 1) as *mut c_char;
8312                    if s.is_null() {
8313                        if !consumed.is_null() { *consumed = p; }
8314                        return if assigned == 0 { -1 } else { assigned };
8315                    }
8316                    core::ptr::copy_nonoverlapping(buf.add(start_p), s as *mut u8, n);
8317                    *s.add(n) = 0;
8318                    if !out.is_null() { *out = s; } else { crate::free(s as *mut c_void); }
8319                } else {
8320                    let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8321                    if !dest_ptr.is_null() {
8322                        core::ptr::copy_nonoverlapping(buf.add(start_p), dest_ptr as *mut u8, n);
8323                        *dest_ptr.add(n) = 0;
8324                    }
8325                }
8326                if !suppress { assigned += 1; }
8327            }
8328            b'[' => {
8329                fi += 1;
8330                let negate = if *fmt.add(fi) as u8 == b'^' { fi += 1; true } else { false };
8331                let mut charset = [0u8; 256];
8332                let mut prev: Option<u8> = None;
8333                if *fmt.add(fi) as u8 == b']' {
8334                    charset[b']' as usize] = 1;
8335                    prev = Some(b']');
8336                    fi += 1;
8337                }
8338                loop {
8339                    let c = *fmt.add(fi) as u8;
8340                    if c == b']' || c == 0 { break; }
8341                    // "a-z" is a range; a '-' next to ']' or at the start/end
8342                    // of the set is a literal.
8343                    if c == b'-' && prev.is_some() {
8344                        let hi = *fmt.add(fi + 1) as u8;
8345                        if hi != b']' && hi != 0 {
8346                            let lo = prev.unwrap();
8347                            let mut k = lo;
8348                            while k <= hi {
8349                                charset[k as usize] = 1;
8350                                if k == 255 { break; }
8351                                k += 1;
8352                            }
8353                            prev = None;
8354                            fi += 2;
8355                            continue;
8356                        }
8357                    }
8358                    charset[c as usize] = 1;
8359                    prev = Some(c);
8360                    fi += 1;
8361                }
8362                if *fmt.add(fi) as u8 == b']' { fi += 1; }
8363                fi -= 1; // common fi += 1 will advance past the closing ]
8364                if p >= buf_len { input_eof = true; break; }
8365                let w = if width > 0 { width } else { usize::MAX };
8366                let start_p = p;
8367                let n = scan_span(buf, buf_len, &mut p, w, |c| {
8368                    if c == 0 { return false; }
8369                    let in_set = charset[c as usize] != 0;
8370                    if negate { !in_set } else { in_set }
8371                });
8372                if n == 0 { break; }
8373                if alloc {
8374                    let out = args.next_arg::<*mut *mut c_char>();
8375                    let s = crate::malloc(n + 1) as *mut c_char;
8376                    if s.is_null() {
8377                        if !consumed.is_null() { *consumed = p; }
8378                        return if assigned == 0 { -1 } else { assigned };
8379                    }
8380                    core::ptr::copy_nonoverlapping(buf.add(start_p), s as *mut u8, n);
8381                    *s.add(n) = 0;
8382                    if !out.is_null() { *out = s; } else { crate::free(s as *mut c_void); }
8383                } else {
8384                    let dest_ptr: *mut c_char = if !suppress { args.next_arg::<*mut c_char>() } else { core::ptr::null_mut() };
8385                    if !dest_ptr.is_null() {
8386                        core::ptr::copy_nonoverlapping(buf.add(start_p), dest_ptr as *mut u8, n);
8387                        *dest_ptr.add(n) = 0;
8388                    }
8389                }
8390                if !suppress { assigned += 1; }
8391            }
8392            _ => break,
8393        }
8394        fi += 1;
8395    }
8396    if !consumed.is_null() { *consumed = p; }
8397    if assigned == 0 && input_eof { -1 } else { assigned }
8398}
8399
8400unsafe fn vsscanf_inner(buf: *const u8, fmt: *const c_char, args: &mut VaList<'_>) -> c_int {
8401    let len = strlen(buf as *const c_char);
8402    do_vsscanf(buf, len, fmt, args, core::ptr::null_mut())
8403}
8404
8405#[no_mangle]
8406pub unsafe extern "C" fn vsscanf(buf: *const c_char, fmt: *const c_char, mut args: VaList) -> c_int {
8407    vsscanf_inner(buf as *const u8, fmt, &mut args)
8408}
8409
8410unsafe fn scan_buf_grow(buf: &mut *mut u8, cap: &mut usize, need: usize) -> bool {
8411    if need <= *cap {
8412        return true;
8413    }
8414    let mut next = core::cmp::max(*cap, 256);
8415    while next < need {
8416        next = match next.checked_mul(2) {
8417            Some(v) => v,
8418            None => return false,
8419        };
8420    }
8421    let grown = crate::realloc(*buf as *mut c_void, next) as *mut u8;
8422    if grown.is_null() {
8423        return false;
8424    }
8425    *buf = grown;
8426    *cap = next;
8427    true
8428}
8429
8430#[no_mangle]
8431pub unsafe extern "C" fn vfscanf(stream: *mut FILE, fmt: *const c_char, mut args: VaList) -> c_int {
8432    let f = &mut *stream;
8433    let start_ungotten_count = f.ungotten_count as usize;
8434    let ungotten_saved = f.ungotten;
8435    let sfunc = f.seek_fn;
8436    // Logical position, not the raw fd offset: fgetc may have read ahead.
8437    let start_pos = if sfunc.is_some() { ftello(stream) } else { -1 };
8438
8439    let mut cap = SCAN_BUF_INIT;
8440    let mut line = crate::malloc(cap) as *mut u8;
8441    if line.is_null() {
8442        ERRNO!() = ENOMEM;
8443        return -1;
8444    }
8445    let mut pos = 0usize;
8446
8447    if start_pos >= 0 {
8448        // Seekable: read via fgetc until newline or EOF.
8449        loop {
8450            if !scan_buf_grow(&mut line, &mut cap, pos + 1) {
8451                crate::free(line as *mut c_void);
8452                ERRNO!() = ENOMEM;
8453                return -1;
8454            }
8455            let c = fgetc(stream);
8456            if c == -1 { break; }
8457            *line.add(pos) = c as u8;
8458            pos += 1;
8459            if c == b'\n' as c_int { break; }
8460        }
8461    } else {
8462        // Non-seekable (pipe/socket): drain pushback, then read all available
8463        // data non-blocking so we don't stop at newline boundaries.
8464
8465        // 1. Drain ungotten bytes (LIFO order)
8466        while f.ungotten_count > 0 {
8467            if !scan_buf_grow(&mut line, &mut cap, pos + 1) {
8468                crate::free(line as *mut c_void);
8469                ERRNO!() = ENOMEM;
8470                return -1;
8471            }
8472            f.ungotten_count -= 1;
8473            *line.add(pos) = f.ungotten[f.ungotten_count as usize] as u8;
8474            pos += 1;
8475        }
8476        // 2. Drain rpos/rend pushback buffer
8477        while !f.rpos.is_null() && f.rpos < f.rend {
8478            if !scan_buf_grow(&mut line, &mut cap, pos + 1) {
8479                crate::free(line as *mut c_void);
8480                ERRNO!() = ENOMEM;
8481                return -1;
8482            }
8483            *line.add(pos) = *f.rpos;
8484            f.rpos = f.rpos.add(1);
8485            pos += 1;
8486        }
8487        // 3. Wait for the first byte (blocking), then drain whatever else is
8488        // available without waiting. A pure non-blocking read would race with
8489        // a producer such as popen() that has not written yet.
8490        let fd = f.fd;
8491        if pos == 0 {
8492            let n = sys_read(fd as i64, line, 1);
8493            if n == 1 { pos = 1; }
8494        }
8495        let old_flags = sys_fcntl(fd, F_GETFL, 0);
8496        if old_flags >= 0 {
8497            let _ = sys_fcntl(fd, F_SETFL, old_flags | O_NONBLOCK as i64);
8498        }
8499        loop {
8500            if pos + 1 >= cap && !scan_buf_grow(&mut line, &mut cap, pos + 2) {
8501                if old_flags >= 0 { let _ = sys_fcntl(fd, F_SETFL, old_flags); }
8502                crate::free(line as *mut c_void);
8503                ERRNO!() = ENOMEM;
8504                return -1;
8505            }
8506            let n = sys_read(fd as i64, line.add(pos), cap - 1 - pos);
8507            if n <= 0 { break; }
8508            pos += n as usize;
8509        }
8510        if old_flags >= 0 {
8511            let _ = sys_fcntl(fd, F_SETFL, old_flags);
8512        }
8513        // Clear flags that the failed non-blocking read may have set
8514        f._eof = 0;
8515        f._err = 0;
8516        f.flags &= !(F_EOF | F_ERR);
8517    }
8518
8519    *line.add(pos) = 0;
8520    if pos == 0 {
8521        crate::free(line as *mut c_void);
8522        return 0;
8523    }
8524
8525    let mut consumed = 0usize;
8526    let assigned = do_vsscanf(line, pos, fmt, &mut args, &mut consumed);
8527
8528    if start_pos >= 0 {
8529        // Seek back to the logical position just past the consumed bytes and
8530        // restore any ungetc pushback the scan did not consume.
8531        let remaining = start_ungotten_count.saturating_sub(consumed);
8532        // The restored ungetc bytes will be subtracted by ftello(), so the
8533        // raw fd offset must include them.
8534        let target = start_pos + consumed as i64 + remaining as i64;
8535        if let Some(sfunc) = sfunc {
8536            sfunc(stream, target, SEEK_SET);
8537        }
8538        f.rpos = core::ptr::null_mut();
8539        f.rend = core::ptr::null_mut();
8540        if consumed < pos { f._eof = 0; }
8541        f.ungotten_count = 0;
8542        for i in 0..remaining {
8543            f.ungotten[f.ungotten_count as usize] = ungotten_saved[i];
8544            f.ungotten_count += 1;
8545        }
8546    } else {
8547        // Non-seekable: push back unconsumed bytes into FILE read buffer
8548        let unconsumed = pos.saturating_sub(consumed);
8549        if unconsumed > 0 && !f.buf.is_null() {
8550            let copy_count = core::cmp::min(unconsumed, f.buf_size);
8551            core::ptr::copy(
8552                line.add(consumed),
8553                f.buf,
8554                copy_count,
8555            );
8556            f.rpos = f.buf;
8557            f.rend = f.buf.add(copy_count);
8558        }
8559        f.ungotten_count = 0;
8560        f._eof = 0;
8561        f.flags &= !F_EOF;
8562    }
8563    crate::free(line as *mut c_void);
8564    assigned
8565}
8566
8567#[no_mangle]
8568pub unsafe extern "C" fn vscanf(fmt: *const c_char, args: VaList) -> c_int {
8569    vfscanf(stdin, fmt, args)
8570}
8571
8572#[no_mangle]
8573pub unsafe extern "C" fn sscanf(buf: *const c_char, fmt: *const c_char, mut args: ...) -> c_int {
8574    vsscanf_inner(buf as *const u8, fmt, &mut args)
8575}
8576
8577#[no_mangle]
8578pub unsafe extern "C" fn fscanf(stream: *mut FILE, fmt: *const c_char, args: ...) -> c_int {
8579    vfscanf(stream, fmt, args)
8580}
8581
8582#[no_mangle]
8583pub unsafe extern "C" fn scanf(fmt: *const c_char, args: ...) -> c_int {
8584    vfscanf(stdin, fmt, args)
8585}
8586
8587// ============================================================
8588// getdelim / getline
8589// ============================================================
8590
8591#[no_mangle]
8592pub unsafe extern "C" fn getdelim(
8593    lineptr: *mut *mut c_char, n: *mut usize, delim: c_int, stream: *mut FILE,
8594) -> isize {
8595    if lineptr.is_null() || n.is_null() {
8596        ERRNO!() = EINVAL;
8597        return -1;
8598    }
8599    let mut cap = *n;
8600    let mut buf = *lineptr;
8601    if buf.is_null() || cap == 0 {
8602        cap = 128;
8603        buf = realloc(buf as *mut c_void, cap) as *mut c_char;
8604        if buf.is_null() { return -1; }
8605        *lineptr = buf;
8606        *n = cap;
8607    }
8608    let mut len = 0usize;
8609    loop {
8610        let c = fgetc(stream);
8611        if c == -1 { if len == 0 { return -1; } break; }
8612        if len >= cap - 1 {
8613            let new_cap = match cap.checked_mul(2) {
8614                Some(v) => v,
8615                None => {
8616                    ERRNO!() = ENOMEM;
8617                    return -1;
8618                }
8619            };
8620            let new_buf = realloc(buf as *mut c_void, new_cap) as *mut c_char;
8621            if new_buf.is_null() {
8622                ERRNO!() = ENOMEM;
8623                return -1;
8624            }
8625            buf = new_buf; cap = new_cap;
8626            *lineptr = buf; *n = cap;
8627        }
8628        *buf.add(len) = c as c_char;
8629        len += 1;
8630        if c == delim { break; }
8631    }
8632    *buf.add(len) = 0;
8633    len as isize
8634}
8635
8636#[no_mangle]
8637pub unsafe extern "C" fn getline(lineptr: *mut *mut c_char, n: *mut usize, stream: *mut FILE) -> isize {
8638    getdelim(lineptr, n, b'\n' as c_int, stream)
8639}
8640
8641// ============================================================
8642// popen / pclose
8643// ============================================================
8644
8645#[no_mangle]
8646pub unsafe extern "C" fn popen(cmd: *const c_char, mode: *const c_char) -> *mut FILE {
8647    if cmd.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
8648    let m = *mode;
8649    if (m != b'r' as c_char && m != b'w' as c_char) || *mode.add(1) != 0 {
8650        ERRNO!() = EINVAL;
8651        return core::ptr::null_mut();
8652    }
8653    let mut p: [c_int; 2] = [0; 2];
8654    let pipe_ret = sys_pipe2(p.as_mut_ptr(), O_CLOEXEC);
8655    if pipe_ret < 0 {
8656        ERRNO!() = (-pipe_ret) as c_int;
8657        return core::ptr::null_mut();
8658    }
8659    let op = if m == b'r' as c_char { 0 } else { 1 };
8660    let child_fd = p[1 - op];
8661    let f = fdopen(p[op], mode);
8662    if f.is_null() { sys_close(p[0] as i64); sys_close(p[1] as i64); return core::ptr::null_mut(); }
8663    let pid = sys_fork();
8664    if pid < 0 {
8665        let e = (-pid) as c_int;
8666        fclose(f); sys_close(child_fd as i64);
8667        ERRNO!() = e;
8668        return core::ptr::null_mut();
8669    }
8670    if pid == 0 {
8671        sys_close(p[op] as i64);
8672        if child_fd != (1 - op) as c_int { sys_dup3(child_fd, (1 - op) as c_int, 0); sys_close(child_fd as i64); }
8673        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
8674        let argv = [b"sh\0".as_ptr() as *const c_char, b"-c\0".as_ptr() as *const c_char, cmd, core::ptr::null()];
8675        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
8676        _exit(127);
8677    }
8678    sys_close(child_fd as i64);
8679    (*f).pipe_pid = pid as c_int;
8680    f
8681}
8682
8683#[no_mangle]
8684pub unsafe extern "C" fn pclose(f: *mut FILE) -> c_int {
8685    if f.is_null() { ERRNO!() = EINVAL; return -1; }
8686    let pid = (*f).pipe_pid;
8687    if pid <= 0 { ERRNO!() = EINVAL; return -1; }
8688    let r = fclose(f);
8689    let mut status: c_int = 0;
8690    let w = loop {
8691        let w = waitpid(pid, &mut status, 0);
8692        if w >= 0 || ERRNO!() != EINTR { break w; }
8693    };
8694    if w < 0 || r != 0 { return -1; }
8695    status
8696}
8697
8698// ============================================================
8699// tmpfile / tmpnam / remove / rename
8700// ============================================================
8701
8702const L_TMPNAM: usize = 20;
8703static TMPNAM_COUNTER: AtomicU32 = AtomicU32::new(0);
8704
8705unsafe fn tmp_seed() -> c_uint {
8706    let mut ts: timespec = core::mem::zeroed();
8707    if sys_clock_gettime(CLOCK_REALTIME, &mut ts) < 0 {
8708        let mut v: u32 = 0;
8709        crate::getrandom(&mut v as *mut u32 as *mut u8, core::mem::size_of::<u32>(), 0);
8710        return v;
8711    }
8712    ts.tv_nsec as u32
8713}
8714
8715unsafe fn fill_tmpname(out: *mut c_char, seed: c_uint) {
8716    let prefix = b"/tmp/tmp\0";
8717    let mut k = 0;
8718    while k < prefix.len() - 1 { *out.add(k) = prefix[k] as c_char; k += 1; }
8719    let (buf, len) = format_hex(seed as u64, false);
8720    for j in 0..len.min(L_TMPNAM - k - 1) { *out.add(k + j) = buf[j] as c_char; k += 1; }
8721    *out.add(k) = 0;
8722}
8723
8724#[no_mangle]
8725pub unsafe extern "C" fn tmpfile() -> *mut FILE {
8726    let mut name = [0u8; L_TMPNAM];
8727    let mut ctr: c_uint = 0;
8728    loop {
8729        ctr = ctr.wrapping_add(1);
8730        let seed = tmp_seed().wrapping_add(ctr);
8731        fill_tmpname(name.as_mut_ptr() as *mut c_char, seed);
8732        let fd = sys_open(name.as_ptr(), (O_RDWR | O_CREAT | O_EXCL) as i64, 0o600);
8733        if fd >= 0 {
8734            sys_unlinkat(AT_FDCWD, name.as_ptr(), 0);
8735            let f = fdopen(fd as c_int, b"w+\0".as_ptr() as *const c_char);
8736            if f.is_null() { sys_close(fd); }
8737            return f;
8738        }
8739        if ctr > 100 { return core::ptr::null_mut(); }
8740    }
8741}
8742
8743#[no_mangle]
8744pub unsafe extern "C" fn tmpnam(s: *mut c_char) -> *mut c_char {
8745    static mut BUF: [c_char; L_TMPNAM] = [0; L_TMPNAM];
8746    let out = if s.is_null() { core::ptr::addr_of_mut!(BUF) as *mut c_char } else { s };
8747    let counter = TMPNAM_COUNTER.fetch_add(1, Ordering::Relaxed);
8748    let seed = tmp_seed().wrapping_add(counter);
8749    fill_tmpname(out, seed);
8750    out
8751}
8752
8753#[no_mangle]
8754pub unsafe extern "C" fn remove(path: *const c_char) -> c_int {
8755    if path.is_null() { ERRNO!() = EINVAL; return -1; }
8756    let r = sys_unlinkat(AT_FDCWD, path as *const u8, 0);
8757    if r == 0 {
8758        return 0;
8759    }
8760    // POSIX remove() also removes directories; musl falls back to rmdir only
8761    // when unlink reports EISDIR.
8762    if (-r) as c_int == 21 {
8763        return rmdir(path);
8764    }
8765    ERRNO!() = (-r) as c_int;
8766    -1
8767}
8768
8769#[no_mangle]
8770pub unsafe extern "C" fn rename(old: *const c_char, new_: *const c_char) -> c_int {
8771    if old.is_null() || new_.is_null() { ERRNO!() = EINVAL; return -1; }
8772    let r = sys_renameat2(AT_FDCWD, old as *const u8, AT_FDCWD, new_ as *const u8, 0);
8773    if r == 0 { 0 } else { ERRNO!() = (-r) as c_int; -1 }
8774}
8775
8776// ============================================================
8777// Allocator basics
8778// ============================================================
8779
8780const MMAP_FAILED: *mut u8 = !0usize as *mut u8;
8781const PAGE: usize = 4096;
8782
8783// ============================================================
8784// Process: exit / _exit / _Exit
8785// ============================================================
8786
8787#[no_mangle]
8788pub unsafe extern "C" fn _exit(code: c_int) -> ! {
8789    sys_exit_group(code)
8790}
8791
8792#[inline]
8793unsafe fn sys_exit_group(code: c_int) -> ! {
8794    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT_GROUP, code as i64)
8795}
8796
8797#[inline]
8798unsafe fn sys_exit_thread(code: c_int) -> ! {
8799    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT, code as i64)
8800}
8801
8802#[no_mangle]
8803pub unsafe extern "C" fn _Exit(code: c_int) -> ! {
8804    _exit(code);
8805}
8806
8807#[no_mangle]
8808pub unsafe extern "C" fn exit(code: c_int) -> ! {
8809    fflush(core::ptr::null_mut());
8810    __funcs_on_exit();
8811    _exit(code);
8812}
8813
8814#[no_mangle]
8815pub unsafe extern "C" fn abort() -> ! {
8816    raise(6); // SIGABRT
8817    _exit(128 + 6);
8818}
8819
8820// aarch64 GCC accesses the stack canary via the global __stack_chk_guard
8821// symbol (GOT-based for PIE). Export it so the dynamic linker can resolve it.
8822#[no_mangle]
8823pub static mut __stack_chk_guard: usize = 0;
8824
8825#[no_mangle]
8826pub unsafe extern "C" fn __stack_chk_fail() -> ! {
8827    const MSG: &[u8] = b"*** stack smashing detected ***: terminated\n";
8828    let _ = sys_write(2, MSG.as_ptr(), MSG.len());
8829    abort();
8830}
8831
8832#[no_mangle]
8833pub unsafe extern "C" fn __stack_chk_fail_local() -> ! {
8834    __stack_chk_fail()
8835}
8836
8837// ============================================================
8838// qsort / qsort_r (smoothsort, O(1) aux, adaptive)
8839// ============================================================
8840
8841type CmpRfn = unsafe extern "C" fn(*const c_void, *const c_void, *mut c_void) -> c_int;
8842
8843const AR_LEN: usize = 16 * core::mem::size_of::<usize>();
8844const AR_MASK: usize = AR_LEN - 1;
8845
8846unsafe fn qsort_pntz(p: &[usize; 2]) -> i32 {
8847    if p[0] != 1 {
8848        p[0].wrapping_sub(1).trailing_zeros() as i32
8849    } else if p[1] != 0 {
8850        (8 * core::mem::size_of::<usize>()) as i32 + p[1].trailing_zeros() as i32
8851    } else {
8852        0
8853    }
8854}
8855
8856unsafe fn qsort_cycle(width: usize, ar: &mut [*mut u8; AR_LEN], n: usize) {
8857    if n < 2 { return; }
8858    let mut tmp = [0u8; 256];
8859    ar[n] = tmp.as_mut_ptr();
8860    let mut w = width;
8861    while w > 0 {
8862        let l = if 256 < w { 256 } else { w };
8863        core::ptr::copy_nonoverlapping(ar[0], ar[n], l);
8864        for i in 0..n {
8865            core::ptr::copy_nonoverlapping(ar[i + 1], ar[i], l);
8866            ar[i] = ar[i].add(l);
8867        }
8868        w -= l;
8869    }
8870}
8871
8872unsafe fn qsort_shl(p: &mut [usize; 2], n: i32) {
8873    let bits = (8 * core::mem::size_of::<usize>()) as i32;
8874    if n >= bits {
8875        p[1] = p[0];
8876        p[0] = 0;
8877        let n = n - bits;
8878        if n == 0 { return; }
8879    }
8880    p[1] = (p[1] << n) | (p[0] >> (bits - n));
8881    p[0] <<= n;
8882}
8883
8884unsafe fn qsort_shr(p: &mut [usize; 2], n: i32) {
8885    let bits = (8 * core::mem::size_of::<usize>()) as i32;
8886    if n >= bits {
8887        p[0] = p[1];
8888        p[1] = 0;
8889        let n = n - bits;
8890        if n == 0 { return; }
8891    }
8892    p[0] = (p[0] >> n) | (p[1] << (bits - n));
8893    p[1] >>= n;
8894}
8895
8896unsafe fn qsort_sift(
8897    head: *mut u8, width: usize,
8898    cmp: CmpRfn, arg: *mut c_void,
8899    pshift: i32, lp: &[usize],
8900) {
8901    let mut ar: [*mut u8; AR_LEN] = [core::ptr::null_mut(); AR_LEN];
8902    ar[0] = head;
8903    let mut i = 1usize;
8904    let mut h = head;
8905    let mut ps = pshift;
8906
8907    while ps > 1 {
8908        let rt = h.sub(width);
8909        let lf = h.sub(width + lp[(ps - 2) as usize]);
8910
8911        if cmp(ar[0] as *const c_void, lf as *const c_void, arg) >= 0
8912            && cmp(ar[0] as *const c_void, rt as *const c_void, arg) >= 0
8913        {
8914            break;
8915        }
8916        if cmp(lf as *const c_void, rt as *const c_void, arg) >= 0 {
8917            ar[i & AR_MASK] = lf;
8918            i += 1;
8919            h = lf;
8920            ps -= 1;
8921        } else {
8922            ar[i & AR_MASK] = rt;
8923            i += 1;
8924            h = rt;
8925            ps -= 2;
8926        }
8927    }
8928    qsort_cycle(width, &mut ar, i & AR_MASK);
8929}
8930
8931unsafe fn qsort_trinkle(
8932    head: *mut u8, width: usize,
8933    cmp: CmpRfn, arg: *mut c_void,
8934    pp: &[usize; 2], pshift: i32, trusty: i32,
8935    lp: &[usize],
8936) {
8937    let mut ar: [*mut u8; AR_LEN] = [core::ptr::null_mut(); AR_LEN];
8938    let mut p = *pp;
8939    ar[0] = head;
8940    let mut i = 1usize;
8941    let mut h = head;
8942    let mut ps = pshift;
8943    let mut t = trusty;
8944
8945    while p[0] != 1 || p[1] != 0 {
8946        let stepson = h.sub(lp[ps as usize]);
8947        if cmp(stepson as *const c_void, ar[0] as *const c_void, arg) <= 0 {
8948            break;
8949        }
8950        if t == 0 && ps > 1 {
8951            let rt = h.sub(width);
8952            let lf = h.sub(width + lp[(ps - 2) as usize]);
8953            if cmp(rt as *const c_void, stepson as *const c_void, arg) >= 0
8954                || cmp(lf as *const c_void, stepson as *const c_void, arg) >= 0
8955            {
8956                break;
8957            }
8958        }
8959
8960        ar[i & AR_MASK] = stepson;
8961        i += 1;
8962        h = stepson;
8963        let trail = qsort_pntz(&p);
8964        qsort_shr(&mut p, trail);
8965        ps += trail;
8966        t = 0;
8967    }
8968    if t == 0 {
8969        qsort_cycle(width, &mut ar, i & AR_MASK);
8970        qsort_sift(h, width, cmp, arg, ps, lp);
8971    }
8972}
8973
8974#[no_mangle]
8975pub unsafe extern "C" fn __qsort_r(
8976    base: *mut c_void,
8977    nel: usize,
8978    width: usize,
8979    cmp: CmpRfn,
8980    arg: *mut c_void,
8981) {
8982    let size = match width.checked_mul(nel) {
8983        Some(v) => v,
8984        None => return,
8985    };
8986    if size == 0 { return; }
8987
8988    let mut lp = [0usize; 96];
8989    lp[0] = width;
8990    lp[1] = width;
8991    let mut li = 2;
8992    while li + 1 < lp.len() {
8993        lp[li] = match lp[li - 2]
8994            .checked_add(lp[li - 1])
8995            .and_then(|v| v.checked_add(width))
8996        {
8997            Some(v) => v,
8998            None => break,
8999        };
9000        if lp[li] >= size { break; }
9001        li += 1;
9002    }
9003
9004    let mut head = base as *mut u8;
9005    let high = head.add(size - width);
9006    let mut p: [usize; 2] = [1, 0];
9007    let mut pshift: i32 = 1;
9008
9009    while head < high {
9010        if (p[0] & 3) == 3 {
9011            qsort_sift(head, width, cmp, arg, pshift, &lp);
9012            qsort_shr(&mut p, 2);
9013            pshift += 2;
9014        } else {
9015            if lp[(pshift - 1) as usize] >= (high as usize) - (head as usize) {
9016                qsort_trinkle(head, width, cmp, arg, &p, pshift, 0, &lp);
9017            } else {
9018                qsort_sift(head, width, cmp, arg, pshift, &lp);
9019            }
9020
9021            if pshift == 1 {
9022                qsort_shl(&mut p, 1);
9023                pshift = 0;
9024            } else {
9025                qsort_shl(&mut p, pshift - 1);
9026                pshift = 1;
9027            }
9028        }
9029
9030        p[0] |= 1;
9031        head = head.add(width);
9032    }
9033
9034    qsort_trinkle(head, width, cmp, arg, &p, pshift, 0, &lp);
9035
9036    while pshift != 1 || p[0] != 1 || p[1] != 0 {
9037        if pshift <= 1 {
9038            let trail = qsort_pntz(&p);
9039            qsort_shr(&mut p, trail);
9040            pshift += trail;
9041        } else {
9042            qsort_shl(&mut p, 2);
9043            pshift -= 2;
9044            p[0] ^= 7;
9045            qsort_shr(&mut p, 1);
9046            qsort_trinkle(
9047                head.sub(lp[pshift as usize] + width),
9048                width, cmp, arg, &p, pshift + 1, 1, &lp,
9049            );
9050            qsort_shl(&mut p, 1);
9051            p[0] |= 1;
9052            qsort_trinkle(head.sub(width), width, cmp, arg, &p, pshift, 1, &lp);
9053        }
9054        head = head.sub(width);
9055    }
9056}
9057
9058#[no_mangle]
9059pub unsafe extern "C" fn qsort_r(
9060    base: *mut c_void,
9061    nel: usize,
9062    width: usize,
9063    cmp: CmpRfn,
9064    arg: *mut c_void,
9065) {
9066    __qsort_r(base, nel, width, cmp, arg);
9067}
9068
9069unsafe extern "C" fn qsort_wrap_cmp(
9070    a: *const c_void,
9071    b: *const c_void,
9072    cmp_ctx: *mut c_void,
9073) -> c_int {
9074    let cmp: CmpFn = core::mem::transmute(cmp_ctx);
9075    cmp(a, b)
9076}
9077
9078#[no_mangle]
9079pub unsafe extern "C" fn qsort(
9080    base: *mut c_void,
9081    nel: usize,
9082    width: usize,
9083    cmp: CmpFn,
9084) {
9085    __qsort_r(base, nel, width, qsort_wrap_cmp, cmp as *mut c_void);
9086}
9087
9088// ============================================================
9089// atexit / __cxa_atexit / __funcs_on_exit
9090// ============================================================
9091
9092const ATEXIT_COUNT: usize = 32;
9093
9094#[repr(C)]
9095struct AtExitBlock {
9096    next: *mut AtExitBlock,
9097    f: [Option<unsafe extern "C" fn(*mut c_void)>; ATEXIT_COUNT],
9098    a: [*mut c_void; ATEXIT_COUNT],
9099}
9100
9101static mut ATEXIT_BUILTIN: AtExitBlock = AtExitBlock {
9102    next: core::ptr::null_mut(),
9103    f: [None; ATEXIT_COUNT],
9104    a: [core::ptr::null_mut(); ATEXIT_COUNT],
9105};
9106static mut ATEXIT_HEAD: *mut AtExitBlock = core::ptr::null_mut();
9107static mut ATEXIT_SLOT: usize = 0;
9108static mut ATEXIT_FINISHED: bool = false;
9109
9110#[no_mangle]
9111pub unsafe extern "C" fn __funcs_on_exit() {
9112    while !ATEXIT_HEAD.is_null() {
9113        let head = ATEXIT_HEAD;
9114        while ATEXIT_SLOT > 0 {
9115            ATEXIT_SLOT -= 1;
9116            if let Some(f) = (*head).f[ATEXIT_SLOT] {
9117                let a = (*head).a[ATEXIT_SLOT];
9118                f(a);
9119            }
9120        }
9121        ATEXIT_HEAD = (*head).next;
9122        ATEXIT_SLOT = ATEXIT_COUNT;
9123    }
9124    ATEXIT_FINISHED = true;
9125}
9126
9127#[no_mangle]
9128pub unsafe extern "C" fn __cxa_atexit(
9129    func: unsafe extern "C" fn(*mut c_void),
9130    arg: *mut c_void,
9131    _dso: *mut c_void,
9132) -> c_int {
9133    if ATEXIT_FINISHED {
9134        return -1;
9135    }
9136    if ATEXIT_HEAD.is_null() {
9137        ATEXIT_HEAD = core::ptr::addr_of_mut!(ATEXIT_BUILTIN);
9138    }
9139    if ATEXIT_SLOT == ATEXIT_COUNT {
9140        let new = calloc(1, core::mem::size_of::<AtExitBlock>()) as *mut AtExitBlock;
9141        if new.is_null() {
9142            return -1;
9143        }
9144        (*new).next = ATEXIT_HEAD;
9145        ATEXIT_HEAD = new;
9146        ATEXIT_SLOT = 0;
9147    }
9148    (*ATEXIT_HEAD).f[ATEXIT_SLOT] = Some(func);
9149    (*ATEXIT_HEAD).a[ATEXIT_SLOT] = arg;
9150    ATEXIT_SLOT += 1;
9151    0
9152}
9153
9154unsafe extern "C" fn atexit_caller(arg: *mut c_void) {
9155    let func: unsafe extern "C" fn() = core::mem::transmute(arg);
9156    func();
9157}
9158
9159#[no_mangle]
9160pub unsafe extern "C" fn atexit(func: unsafe extern "C" fn()) -> c_int {
9161    __cxa_atexit(atexit_caller, func as *mut c_void, core::ptr::null_mut())
9162}
9163
9164#[no_mangle]
9165pub unsafe extern "C" fn __cxa_finalize(_dso: *mut c_void) {
9166    // Modules are never unloaded (dlclose is a no-op), so there is nothing
9167    // to finalize here.
9168}
9169
9170// ============================================================
9171// getenv / setenv / putenv / unsetenv / clearenv
9172// ============================================================
9173
9174#[no_mangle]
9175pub static mut __environ: *mut *mut c_char = core::ptr::null_mut();
9176
9177// Growable tracking of strings allocated by setenv/putenv.  Realloc keeps
9178// this unbounded; if it fails the new string is simply left untracked.
9179static mut ENV_ALLOCED: *mut *mut c_char = core::ptr::null_mut();
9180static mut ENV_ALLOCED_N: usize = 0;
9181static mut ENV_ALLOCED_CAP: usize = 0;
9182
9183unsafe fn env_rm_add(old: *mut c_char, mut new: *mut c_char) {
9184    for i in 0..ENV_ALLOCED_N {
9185        if (*ENV_ALLOCED.add(i)) == old {
9186            *ENV_ALLOCED.add(i) = new;
9187            if !old.is_null() {
9188                free(old as *mut c_void);
9189            }
9190            return;
9191        } else if (*ENV_ALLOCED.add(i)).is_null() && !new.is_null() {
9192            *ENV_ALLOCED.add(i) = new;
9193            new = core::ptr::null_mut();
9194        }
9195    }
9196    if !new.is_null() {
9197        if ENV_ALLOCED_N == ENV_ALLOCED_CAP {
9198            let new_cap = if ENV_ALLOCED_CAP == 0 { 16 } else { ENV_ALLOCED_CAP * 2 };
9199            let grown = realloc(
9200                ENV_ALLOCED as *mut c_void,
9201                new_cap * core::mem::size_of::<*mut c_char>(),
9202            ) as *mut *mut c_char;
9203            if grown.is_null() {
9204                return;
9205            }
9206            ENV_ALLOCED = grown;
9207            ENV_ALLOCED_CAP = new_cap;
9208        }
9209        *ENV_ALLOCED.add(ENV_ALLOCED_N) = new;
9210        ENV_ALLOCED_N += 1;
9211    }
9212}
9213
9214unsafe fn strchrnul_u8(s: *const u8, c: u8) -> *const u8 {
9215    let mut p = s;
9216    while *p != 0 && *p != c {
9217        p = p.add(1);
9218    }
9219    p
9220}
9221
9222#[no_mangle]
9223pub unsafe extern "C" fn getenv(name: *const c_char) -> *mut c_char {
9224    if __environ.is_null() || name.is_null() {
9225        return core::ptr::null_mut();
9226    }
9227    let name = name as *const u8;
9228    let l = strchrnul_u8(name, b'=') as usize - name as usize;
9229    if l == 0 || *name.add(l) != 0 {
9230        return core::ptr::null_mut();
9231    }
9232    let mut e = __environ;
9233    while !(*e).is_null() {
9234        let entry = *e as *const u8;
9235        if strncmp(entry, name, l) == 0 && *entry.add(l) == b'=' {
9236            return entry.add(l + 1) as *mut c_char;
9237        }
9238        e = e.add(1);
9239    }
9240    core::ptr::null_mut()
9241}
9242
9243#[no_mangle]
9244pub unsafe extern "C" fn setenv(
9245    var: *const c_char,
9246    value: *const c_char,
9247    overwrite: c_int,
9248) -> c_int {
9249    if var.is_null() || value.is_null() {
9250        ERRNO!() = EINVAL;
9251        return -1;
9252    }
9253    let var = var as *const u8;
9254    let l1 = strchrnul_u8(var, b'=') as usize - var as usize;
9255    if l1 == 0 || *var.add(l1) != 0 {
9256        ERRNO!() = EINVAL;
9257        return -1;
9258    }
9259    if overwrite == 0 && !getenv(var as *const c_char).is_null() {
9260        return 0;
9261    }
9262    let l2 = strlen(value as *const c_char);
9263    let s = malloc(l1 + l2 + 2) as *mut u8;
9264    if s.is_null() {
9265        return -1;
9266    }
9267    core::ptr::copy_nonoverlapping(var, s, l1);
9268    *s.add(l1) = b'=';
9269    core::ptr::copy_nonoverlapping(value as *const u8, s.add(l1 + 1), l2 + 1);
9270    putenv_internal(s as *mut c_char, l1, s as *mut c_char)
9271}
9272
9273unsafe fn putenv_internal(s: *mut c_char, l: usize, r: *mut c_char) -> c_int {
9274    let mut i = 0;
9275    if !__environ.is_null() {
9276        let mut e = __environ;
9277        while !(*e).is_null() {
9278            if strncmp(s as *const u8, *e as *const u8, l + 1) == 0 {
9279                let tmp = *e;
9280                *e = s;
9281                env_rm_add(tmp, r);
9282                return 0;
9283            }
9284            e = e.add(1);
9285            i += 1;
9286        }
9287    }
9288    let newenv = malloc(core::mem::size_of::<*mut c_char>() * (i + 2)) as *mut *mut c_char;
9289    if newenv.is_null() {
9290        if !r.is_null() { free(r as *mut c_void); }
9291        return -1;
9292    }
9293    if i > 0 && !__environ.is_null() {
9294        core::ptr::copy_nonoverlapping(__environ, newenv, i);
9295    }
9296    *newenv.add(i) = s;
9297    *newenv.add(i + 1) = core::ptr::null_mut();
9298    // don't free old __environ (may not be from our malloc)
9299    __environ = newenv;
9300    environ = __environ;
9301    if !r.is_null() {
9302        env_rm_add(core::ptr::null_mut(), r);
9303    }
9304    0
9305}
9306
9307#[no_mangle]
9308pub unsafe extern "C" fn putenv(s: *mut c_char) -> c_int {
9309    if s.is_null() { return -1; }
9310    let l = strchrnul_u8(s as *const u8, b'=') as usize - s as *const u8 as usize;
9311    if l == 0 || *s.add(l) as u8 == 0 {
9312        return unsetenv(s);
9313    }
9314    putenv_internal(s, l, core::ptr::null_mut())
9315}
9316
9317#[no_mangle]
9318pub unsafe extern "C" fn unsetenv(name: *const c_char) -> c_int {
9319    if name.is_null() {
9320        ERRNO!() = EINVAL;
9321        return -1;
9322    }
9323    let name = name as *const u8;
9324    let l = strchrnul_u8(name, b'=') as usize - name as usize;
9325    if l == 0 || *name.add(l) != 0 {
9326        ERRNO!() = EINVAL;
9327        return -1;
9328    }
9329    if __environ.is_null() {
9330        return 0;
9331    }
9332    let mut e = __environ;
9333    let mut eo = e;
9334    while !(*e).is_null() {
9335        if strncmp(name, *e as *const u8, l) == 0 && *(*e as *const u8).add(l) == b'=' {
9336            env_rm_add(*e, core::ptr::null_mut());
9337        } else {
9338            if eo != e {
9339                *eo = *e;
9340            }
9341            eo = eo.add(1);
9342        }
9343        e = e.add(1);
9344    }
9345    if eo != e {
9346        *eo = core::ptr::null_mut();
9347    }
9348    environ = __environ;
9349    0
9350}
9351
9352#[no_mangle]
9353pub unsafe extern "C" fn clearenv() -> c_int {
9354    let e = __environ;
9355    __environ = core::ptr::null_mut();
9356    environ = core::ptr::null_mut();
9357    if !e.is_null() {
9358        let mut p = e;
9359        while !(*p).is_null() {
9360            env_rm_add(*p, core::ptr::null_mut());
9361            p = p.add(1);
9362        }
9363    }
9364    0
9365}
9366
9367// ============================================================
9368// random / srandom / initstate / setstate (BSD lagged fibonacci)
9369// musl serializes the process-global state with a lock; keel currently
9370// does not, so concurrent callers must provide their own serialization.
9371// ============================================================
9372
9373static mut RANDOM_INIT: [u32; 32] = [
9374    0x00000000,0x5851f42d,0xc0b18ccf,0xcbb5f646,
9375    0xc7033129,0x30705b04,0x20fd5db4,0x9a8b7f78,
9376    0x502959d8,0xab894868,0x6c0356a7,0x88cdb7ff,
9377    0xb477d43f,0x70a3a52b,0xa8e4baf1,0xfd8341fc,
9378    0x8ae16fd9,0x742d2f7a,0x0d1f0796,0x76035e09,
9379    0x40f7702c,0x6fa72ca5,0xaaa84157,0x58a0df74,
9380    0xc74a0364,0xae533cc4,0x04185faf,0x6de3b115,
9381    0x0cab8628,0xf043bfa4,0x398150e9,0x37521657,
9382];
9383
9384static mut RANDOM_N: i32 = 31;
9385static mut RANDOM_I: i32 = 3;
9386static mut RANDOM_J: i32 = 0;
9387static mut RANDOM_X: *mut u32 = unsafe { core::ptr::addr_of_mut!(RANDOM_INIT).cast::<u32>().add(1) };
9388
9389unsafe fn random_lcg31(x: u32) -> u32 {
9390    (1103515245u32.wrapping_mul(x).wrapping_add(12345)) & 0x7fffffff
9391}
9392
9393unsafe fn random_lcg64(x: u64) -> u64 {
9394    6364136223846793005u64.wrapping_mul(x).wrapping_add(1)
9395}
9396
9397unsafe fn random_savestate() -> *mut u8 {
9398    (*RANDOM_X.offset(-1)) = ((RANDOM_N as u32) << 16) | ((RANDOM_I as u32) << 8) | (RANDOM_J as u32);
9399    RANDOM_X.offset(-1) as *mut u8
9400}
9401
9402unsafe fn random_loadstate(state: *mut u32) {
9403    RANDOM_X = state.add(1);
9404    RANDOM_N = ((*RANDOM_X.offset(-1)) >> 16) as i32;
9405    RANDOM_I = (((*RANDOM_X.offset(-1)) >> 8) & 0xff) as i32;
9406    RANDOM_J = ((*RANDOM_X.offset(-1)) & 0xff) as i32;
9407}
9408
9409unsafe fn random_srandom_inner(seed: u32) {
9410    let mut s = seed as u64;
9411    if RANDOM_N == 0 {
9412        *RANDOM_X = s as u32;
9413        return;
9414    }
9415    RANDOM_I = if RANDOM_N == 31 || RANDOM_N == 7 { 3 } else { 1 };
9416    RANDOM_J = 0;
9417    for k in 0..RANDOM_N as usize {
9418        s = random_lcg64(s);
9419        *RANDOM_X.add(k) = (s >> 32) as u32;
9420    }
9421    *RANDOM_X |= 1;
9422}
9423
9424#[no_mangle]
9425pub unsafe extern "C" fn srandom(seed: c_uint) {
9426    random_srandom_inner(seed);
9427}
9428
9429#[no_mangle]
9430pub unsafe extern "C" fn initstate(seed: c_uint, state: *mut c_char, size: usize) -> *mut c_char {
9431    if size < 8 { return core::ptr::null_mut(); }
9432    let old = random_savestate();
9433    RANDOM_N = if size < 32 { 0 }
9434        else if size < 64 { 7 }
9435        else if size < 128 { 15 }
9436        else if size < 256 { 31 }
9437        else { 63 };
9438    RANDOM_X = (state as *mut u32).add(1);
9439    random_srandom_inner(seed);
9440    random_savestate();
9441    old as *mut c_char
9442}
9443
9444#[no_mangle]
9445pub unsafe extern "C" fn setstate(state: *mut c_char) -> *mut c_char {
9446    let old = random_savestate();
9447    random_loadstate(state as *mut u32);
9448    old as *mut c_char
9449}
9450
9451#[no_mangle]
9452pub unsafe extern "C" fn random() -> c_long {
9453    let k: c_long;
9454    if RANDOM_N == 0 {
9455        *RANDOM_X = random_lcg31(*RANDOM_X);
9456        k = *RANDOM_X as c_long;
9457    } else {
9458        *RANDOM_X.add(RANDOM_I as usize) = (*RANDOM_X.add(RANDOM_I as usize)).wrapping_add(*RANDOM_X.add(RANDOM_J as usize));
9459        k = (*RANDOM_X.add(RANDOM_I as usize) >> 1) as c_long;
9460        RANDOM_I += 1;
9461        if RANDOM_I == RANDOM_N { RANDOM_I = 0; }
9462        RANDOM_J += 1;
9463        if RANDOM_J == RANDOM_N { RANDOM_J = 0; }
9464    }
9465    k
9466}
9467
9468// ============================================================
9469// multibyte (UTF-8, musl state machine)
9470// ============================================================
9471
9472const SA: u8 = 0xC2;
9473const SB: u8 = 0xF4;
9474
9475const BITTAB: [u32; 51] = [
9476    0xC000_0002, 0xC000_0003, 0xC000_0004, 0xC000_0005, 0xC000_0006, 0xC000_0007,
9477    0xC000_0008, 0xC000_0009, 0xC000_000A, 0xC000_000B, 0xC000_000C, 0xC000_000D,
9478    0xC000_000E, 0xC000_000F, 0xC000_0010, 0xC000_0011, 0xC000_0012, 0xC000_0013,
9479    0xC000_0014, 0xC000_0015, 0xC000_0016, 0xC000_0017, 0xC000_0018, 0xC000_0019,
9480    0xC000_001A, 0xC000_001B, 0xC000_001C, 0xC000_001D, 0xC000_001E, 0xC000_001F,
9481    0xB300_0000, 0xC300_0001, 0xC300_0002, 0xC300_0003, 0xC300_0004, 0xC300_0005,
9482    0xC300_0006, 0xC300_0007, 0xC300_0008, 0xC300_0009, 0xC300_000A, 0xC300_000B,
9483    0xC300_000C, 0xD300_000D, 0xC300_000E, 0xC300_000F, 0xBB0C_0000, 0xC30C_0001,
9484    0xC30C_0002, 0xC30C_0003, 0xDB0C_0004,
9485];
9486
9487#[inline]
9488fn mb_oob(c: u32, b: u8) -> u32 {
9489    let b3 = (b >> 3) as u32;
9490    ((b3.wrapping_sub(0x10)) | (b3.wrapping_add((c as i32 >> 26) as u32))) & !7
9491}
9492
9493static mut MB_STATE: c_uint = 0;
9494
9495/// Select the caller's multibyte state or the process-global fallback used
9496/// when `st` is null.
9497#[inline]
9498unsafe fn mb_state_or(st: *mut c_uint) -> &'static mut c_uint {
9499    if st.is_null() { &mut *(&raw mut MB_STATE) } else { &mut *st }
9500}
9501
9502const MB_CUR_MAX_VAL_UTF8: usize = 4;
9503const MB_CUR_MAX_VAL_C: usize = 1;
9504
9505#[no_mangle]
9506pub extern "C" fn __ctype_get_mb_cur_max() -> usize {
9507    unsafe { if LOCALE_CTYPE_UTF8 { MB_CUR_MAX_VAL_UTF8 } else { MB_CUR_MAX_VAL_C } }
9508}
9509
9510#[no_mangle]
9511pub unsafe extern "C" fn mbrtowc(
9512    wc: *mut c_int,
9513    src: *const c_char,
9514    n: usize,
9515    st: *mut c_uint,
9516) -> usize {
9517    let s = src as *const u8;
9518    let n0 = n;
9519    let mut dummy: c_int = 0;
9520    let wc = if wc.is_null() { &mut dummy } else { &mut *wc };
9521    let st = mb_state_or(st);
9522
9523    let mut c: u32 = *st;
9524    let mut s = s;
9525    let mut n = n;
9526
9527    if s.is_null() {
9528        if c != 0 { *st = 0; ERRNO!() = EILSEQ; return !0usize; }
9529        return 0;
9530    }
9531
9532    if n == 0 { return !1usize; }
9533
9534    if unsafe { !LOCALE_CTYPE_UTF8 } {
9535        let b = *s;
9536        *wc = c_locale_codeunit(b) as c_int;
9537        return if b == 0 { 0 } else { 1 };
9538    }
9539
9540    if c == 0 {
9541        if *s < 0x80 {
9542            let r = if *s == 0 { 0 } else { 1 };
9543            *wc = *s as c_int;
9544            return r;
9545        }
9546        if (*s).wrapping_sub(SA) as u32 > (SB - SA) as u32 {
9547            *st = 0; ERRNO!() = EILSEQ; return !0usize;
9548        }
9549        c = BITTAB[*s as usize - SA as usize];
9550        s = s.add(1);
9551        n -= 1;
9552    }
9553
9554    if n > 0 {
9555        if mb_oob(c, *s) != 0 {
9556            *st = 0; ERRNO!() = EILSEQ; return !0usize;
9557        }
9558        loop {
9559            c = (c << 6) | (*s as u32).wrapping_sub(0x80);
9560            s = s.add(1);
9561            n -= 1;
9562            if c & (1u32 << 31) == 0 {
9563                *st = 0;
9564                *wc = c as c_int;
9565                return n0 - n;
9566            }
9567            if n == 0 { break; }
9568            if (*s).wrapping_sub(0x80) >= 0x40 {
9569                *st = 0; ERRNO!() = EILSEQ; return !0usize;
9570            }
9571        }
9572    }
9573
9574    *st = c;
9575    !1usize
9576}
9577
9578#[no_mangle]
9579pub unsafe extern "C" fn wcrtomb(
9580    s: *mut c_char,
9581    wc: c_int,
9582    _st: *mut c_uint,
9583) -> usize {
9584    if s.is_null() { return 1; }
9585    let wc_u = wc as u32;
9586    if unsafe { !LOCALE_CTYPE_UTF8 } {
9587        if wc_u < 0x80 {
9588            *s = wc as c_char;
9589            return 1;
9590        }
9591        if c_locale_is_codeunit(wc_u) {
9592            *s = (wc_u & 0xFF) as c_char;
9593            return 1;
9594        }
9595        ERRNO!() = EILSEQ;
9596        return !0usize;
9597    }
9598    if wc_u < 0x80 {
9599        *s = wc as c_char;
9600        return 1;
9601    }
9602    if wc_u < 0x800 {
9603        *s = (0xC0 | (wc_u >> 6)) as c_char;
9604        *s.add(1) = (0x80 | (wc_u & 0x3F)) as c_char;
9605        return 2;
9606    }
9607    if wc_u < UNICODE_SURROGATE_START || wc_u.wrapping_sub(UNICODE_SURROGATE_END_EXCL) < 0x2000 {
9608        *s = (0xE0 | (wc_u >> 12)) as c_char;
9609        *s.add(1) = (0x80 | ((wc_u >> 6) & 0x3F)) as c_char;
9610        *s.add(2) = (0x80 | (wc_u & 0x3F)) as c_char;
9611        return 3;
9612    }
9613    if wc_u.wrapping_sub(UNICODE_SUPPLEMENTARY_BASE) < UNICODE_SUPPLEMENTARY_SIZE {
9614        *s = (0xF0 | (wc_u >> 18)) as c_char;
9615        *s.add(1) = (0x80 | ((wc_u >> 12) & 0x3F)) as c_char;
9616        *s.add(2) = (0x80 | ((wc_u >> 6) & 0x3F)) as c_char;
9617        *s.add(3) = (0x80 | (wc_u & 0x3F)) as c_char;
9618        return 4;
9619    }
9620    ERRNO!() = EILSEQ;
9621    !0usize
9622}
9623
9624#[no_mangle]
9625pub unsafe extern "C" fn mblen(s: *const c_char, n: usize) -> c_int {
9626    if s.is_null() { return 0; }
9627    mbtowc(core::ptr::null_mut(), s, n)
9628}
9629
9630#[no_mangle]
9631pub unsafe extern "C" fn mbtowc(
9632    wc: *mut c_int,
9633    src: *const c_char,
9634    n: usize,
9635) -> c_int {
9636    if src.is_null() { return 0; }
9637    if n == 0 { ERRNO!() = EILSEQ; return -1; }
9638    let mut state: c_uint = 0;
9639    let mut w: c_int = 0;
9640    let r = mbrtowc(&mut w, src, n, &mut state);
9641    if r == !0usize { return -1; }
9642    if !wc.is_null() { *wc = w; }
9643    r as c_int
9644}
9645
9646#[no_mangle]
9647pub unsafe extern "C" fn wctomb(s: *mut c_char, wc: c_int) -> c_int {
9648    if s.is_null() { return 0; }
9649    wcrtomb(s, wc, core::ptr::null_mut()) as c_int
9650}
9651
9652#[no_mangle]
9653pub unsafe extern "C" fn mbsrtowcs(
9654    ws: *mut c_int,
9655    src: *mut *const c_char,
9656    wn: usize,
9657    st: *mut c_uint,
9658) -> usize {
9659    let st = mb_state_or(st);
9660    let mut s = *src as *const u8;
9661    let wn0 = wn;
9662    let mut wn = wn;
9663
9664    if ws.is_null() {
9665        while *s != 0 {
9666            if *s < 0x80 {
9667                s = s.add(1);
9668                wn = wn.wrapping_sub(1);
9669                continue;
9670            }
9671            let mut wc: c_int = 0;
9672            let r = mbrtowc(&mut wc, s as *const c_char, 4, st);
9673            if r == !0usize { return !0usize; }
9674            if r == !1usize { return wn0 - wn; }
9675            s = s.add(r);
9676            wn = wn.wrapping_sub(1);
9677        }
9678        wn0 - wn
9679    } else {
9680        let mut w = ws;
9681        while wn > 0 {
9682            if *s < 0x80 {
9683                let c = *s as c_int;
9684                *w = c;
9685                if c == 0 {
9686                    *src = core::ptr::null();
9687                    return wn0 - wn;
9688                }
9689                w = w.add(1);
9690                s = s.add(1);
9691                wn -= 1;
9692                continue;
9693            }
9694            let mut wc: c_int = 0;
9695            let r = mbrtowc(&mut wc, s as *const c_char, 4, st);
9696            if r == !0usize {
9697                *src = s as *const c_char;
9698                return !0usize;
9699            }
9700            if r == !1usize {
9701                *src = s as *const c_char;
9702                return wn0 - wn;
9703            }
9704            *w = wc;
9705            w = w.add(1);
9706            s = s.add(r);
9707            wn -= 1;
9708        }
9709        *src = s as *const c_char;
9710        wn0 - wn
9711    }
9712}
9713
9714#[no_mangle]
9715pub unsafe extern "C" fn wcsrtombs(
9716    s: *mut c_char,
9717    ws: *mut *const c_int,
9718    n: usize,
9719    _st: *mut c_uint,
9720) -> usize {
9721    let mut w = *ws;
9722    let n0 = n;
9723    let mut n = n;
9724
9725    if s.is_null() {
9726        let mut count = 0usize;
9727        while *w != 0 {
9728            if (*w as u32) < 0x80 {
9729                count += 1;
9730            } else {
9731                let mut buf = [0u8; 4];
9732                let r = wcrtomb(buf.as_mut_ptr() as *mut c_char, *w, core::ptr::null_mut());
9733                if r == !0usize { return !0usize; }
9734                count += r;
9735            }
9736            w = w.add(1);
9737        }
9738        return count;
9739    }
9740
9741    let mut dst = s;
9742    while n > 0 {
9743        if (*w as u32) < 0x80 {
9744            *dst = *w as c_char;
9745            if *w == 0 {
9746                *ws = core::ptr::null();
9747                return n0 - n;
9748            }
9749            dst = dst.add(1);
9750            n -= 1;
9751        } else {
9752            let r = wcrtomb(dst, *w, core::ptr::null_mut());
9753            if r == !0usize {
9754                *ws = w;
9755                return !0usize;
9756            }
9757            if r > n {
9758                *ws = w;
9759                return n0 - n;
9760            }
9761            dst = dst.add(r);
9762            n -= r;
9763        }
9764        w = w.add(1);
9765    }
9766    *ws = w;
9767    n0
9768}
9769
9770#[no_mangle]
9771pub unsafe extern "C" fn mbstowcs(
9772    ws: *mut c_int,
9773    src: *const c_char,
9774    wn: usize,
9775) -> usize {
9776    let mut src_ptr = src;
9777    mbsrtowcs(ws, &mut src_ptr, wn, core::ptr::null_mut())
9778}
9779
9780#[no_mangle]
9781pub unsafe extern "C" fn wcstombs(
9782    s: *mut c_char,
9783    ws: *const c_int,
9784    n: usize,
9785) -> usize {
9786    let mut ws_ptr = ws;
9787    wcsrtombs(s, &mut ws_ptr, n, core::ptr::null_mut())
9788}
9789
9790// ============================================================
9791// wchar: btowc / wctob / mbsinit / mbrlen
9792// ============================================================
9793
9794// musl's C locale represents bytes >= 0x80 as the single-byte "code units"
9795// 0xDF80..0xDFFF so they are distinct from Unicode code points.
9796#[inline]
9797fn c_locale_codeunit(b: u8) -> u32 {
9798    0xdfff & (b as i8 as i32) as u32
9799}
9800
9801#[inline]
9802fn c_locale_is_codeunit(c: u32) -> bool {
9803    c.wrapping_sub(0xDF80) < 0x80
9804}
9805
9806#[no_mangle]
9807pub extern "C" fn btowc(c: c_int) -> wint_t {
9808    if c == -1 { return WEOF; }
9809    unsafe {
9810        if LOCALE_CTYPE_UTF8 {
9811            if (c as u32) < 128 { c as wint_t } else { WEOF }
9812        } else {
9813            c_locale_codeunit(c as u8) as wint_t
9814        }
9815    }
9816}
9817
9818#[no_mangle]
9819pub extern "C" fn wctob(c: wint_t) -> c_int {
9820    unsafe {
9821        if LOCALE_CTYPE_UTF8 {
9822            if c < 128 { c as c_int } else { -1 }
9823        } else if c < 128 {
9824            c as c_int
9825        } else if c_locale_is_codeunit(c) {
9826            (c & 0xFF) as c_int
9827        } else {
9828            -1
9829        }
9830    }
9831}
9832
9833#[no_mangle]
9834pub unsafe extern "C" fn mbsinit(s: *const c_uint) -> c_int {
9835    if s.is_null() || *s == 0 { 1 } else { 0 }
9836}
9837
9838#[no_mangle]
9839pub unsafe extern "C" fn mbrlen(s: *const c_char, n: usize, ps: *mut c_uint) -> usize {
9840    mbrtowc(core::ptr::null_mut(), s, n, ps)
9841}
9842
9843// ============================================================
9844// wchar: wide string functions
9845// ============================================================
9846
9847#[no_mangle]
9848pub unsafe extern "C" fn wcslen(s: *const wchar_t) -> usize {
9849    let mut len = 0;
9850    while *s.add(len) != 0 { len += 1; }
9851    len
9852}
9853
9854#[no_mangle]
9855pub unsafe extern "C" fn wcschr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
9856    let mut i = 0;
9857    loop {
9858        let ch = *s.add(i);
9859        if ch == c { return s.add(i) as *mut wchar_t; }
9860        if ch == 0 { return null_mut(); }
9861        i += 1;
9862    }
9863}
9864
9865#[no_mangle]
9866pub unsafe extern "C" fn wcsrchr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
9867    let mut i = 0;
9868    let mut last: *mut wchar_t = null_mut();
9869    loop {
9870        let ch = *s.add(i);
9871        if ch == c { last = s.add(i) as *mut wchar_t; }
9872        if ch == 0 { return last; }
9873        i += 1;
9874    }
9875}
9876
9877#[no_mangle]
9878pub unsafe extern "C" fn wcsstr(haystack: *const wchar_t, needle: *const wchar_t) -> *mut wchar_t {
9879    if *needle == 0 { return haystack as *mut wchar_t; }
9880    let mut i = 0;
9881    loop {
9882        let h = *haystack.add(i);
9883        if h == 0 { return null_mut(); }
9884        if h == *needle {
9885            let mut j = 0;
9886            loop {
9887                let n = *needle.add(j);
9888                if n == 0 { return haystack.add(i) as *mut wchar_t; }
9889                if *haystack.add(i + j) != n { break; }
9890                j += 1;
9891            }
9892        }
9893        i += 1;
9894    }
9895}
9896
9897#[no_mangle]
9898pub unsafe extern "C" fn wcscmp(s1: *const wchar_t, s2: *const wchar_t) -> c_int {
9899    let mut i = 0;
9900    loop {
9901        let a = *s1.add(i);
9902        let b = *s2.add(i);
9903        if a != b { return a - b; }
9904        if a == 0 { return 0; }
9905        i += 1;
9906    }
9907}
9908
9909#[no_mangle]
9910pub unsafe extern "C" fn wcsncmp(s1: *const wchar_t, s2: *const wchar_t, n: usize) -> c_int {
9911    let mut i = 0;
9912    while i < n {
9913        let a = *s1.add(i);
9914        let b = *s2.add(i);
9915        if a != b { return a - b; }
9916        if a == 0 { return 0; }
9917        i += 1;
9918    }
9919    0
9920}
9921
9922#[no_mangle]
9923pub unsafe extern "C" fn wcscpy(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
9924    let mut i = 0;
9925    loop {
9926        let c = *src.add(i);
9927        *dst.add(i) = c;
9928        if c == 0 { break; }
9929        i += 1;
9930    }
9931    dst
9932}
9933
9934#[no_mangle]
9935pub unsafe extern "C" fn wcsncpy(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
9936    let mut i = 0;
9937    while i < n && *src.add(i) != 0 { *dst.add(i) = *src.add(i); i += 1; }
9938    while i < n { *dst.add(i) = 0; i += 1; }
9939    dst
9940}
9941
9942#[no_mangle]
9943pub unsafe extern "C" fn wcscat(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
9944    let mut i = 0;
9945    while *dst.add(i) != 0 { i += 1; }
9946    let mut j = 0;
9947    loop {
9948        let c = *src.add(j);
9949        *dst.add(i + j) = c;
9950        if c == 0 { break; }
9951        j += 1;
9952    }
9953    dst
9954}
9955
9956#[no_mangle]
9957pub unsafe extern "C" fn wcsncat(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
9958    let mut i = 0;
9959    while *dst.add(i) != 0 { i += 1; }
9960    let mut j = 0;
9961    while j < n && *src.add(j) != 0 { *dst.add(i + j) = *src.add(j); j += 1; }
9962    *dst.add(i + j) = 0;
9963    dst
9964}
9965
9966#[no_mangle]
9967pub unsafe extern "C" fn wcsdup(s: *const wchar_t) -> *mut wchar_t {
9968    let len = wcslen(s);
9969    let p = malloc((len + 1) * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
9970    if p.is_null() { return null_mut(); }
9971    core::ptr::copy_nonoverlapping(s, p, len + 1);
9972    p
9973}
9974
9975#[no_mangle]
9976pub unsafe extern "C" fn wcsnlen(s: *const wchar_t, maxlen: usize) -> usize {
9977    let mut i = 0;
9978    while i < maxlen && *s.add(i) != 0 { i += 1; }
9979    i
9980}
9981
9982#[no_mangle]
9983pub unsafe extern "C" fn wcsspn(s: *const wchar_t, accept: *const wchar_t) -> usize {
9984    let mut i = 0;
9985    loop {
9986        let c = *s.add(i);
9987        if c == 0 { return i; }
9988        let mut found = false;
9989        let mut j = 0;
9990        loop {
9991            let a = *accept.add(j);
9992            if a == 0 { break; }
9993            if c == a { found = true; break; }
9994            j += 1;
9995        }
9996        if !found { return i; }
9997        i += 1;
9998    }
9999}
10000
10001#[no_mangle]
10002pub unsafe extern "C" fn wcscspn(s: *const wchar_t, reject: *const wchar_t) -> usize {
10003    let mut i = 0;
10004    loop {
10005        let c = *s.add(i);
10006        if c == 0 { return i; }
10007        let mut j = 0;
10008        loop {
10009            let r = *reject.add(j);
10010            if r == 0 { break; }
10011            if c == r { return i; }
10012            j += 1;
10013        }
10014        i += 1;
10015    }
10016}
10017
10018#[no_mangle]
10019pub unsafe extern "C" fn wcspbrk(s: *const wchar_t, accept: *const wchar_t) -> *mut wchar_t {
10020    let mut i = 0;
10021    loop {
10022        let c = *s.add(i);
10023        if c == 0 { return null_mut(); }
10024        let mut j = 0;
10025        loop {
10026            let a = *accept.add(j);
10027            if a == 0 { break; }
10028            if c == a { return s.add(i) as *mut wchar_t; }
10029            j += 1;
10030        }
10031        i += 1;
10032    }
10033}
10034
10035#[no_mangle]
10036pub unsafe extern "C" fn wcsxfrm(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> usize {
10037    let len = wcslen(src);
10038    if !dst.is_null() {
10039        let copy = if len < n { len } else { if n > 0 { n - 1 } else { 0 } };
10040        for i in 0..copy { *dst.add(i) = *src.add(i); }
10041        if n > 0 { *dst.add(copy) = 0; }
10042    }
10043    len
10044}
10045
10046// ============================================================
10047// wchar: wcsto* number conversions
10048// ============================================================
10049
10050unsafe fn wcs_to_bytes(ws: *const wchar_t, buf: *mut u8, bufsz: usize) -> usize {
10051    let mut i = 0;
10052    while i < bufsz - 1 {
10053        let c = *ws.add(i);
10054        if c == 0 { break; }
10055        if (c as u32) > 127 { break; }
10056        *buf.add(i) = c as u8;
10057        i += 1;
10058    }
10059    *buf.add(i) = 0;
10060    i
10061}
10062
10063macro_rules! wcsto_int {
10064    ($name:ident, $ret:ty, $conv:ident) => {
10065        #[no_mangle]
10066        pub unsafe extern "C" fn $name(
10067            s: *const wchar_t,
10068            endptr: *mut *mut wchar_t,
10069            base: c_int,
10070        ) -> $ret {
10071            let cap = wcslen(s).saturating_add(1);
10072            let heap = cap > 256;
10073            let mut stack = [0u8; 256];
10074            let buf = if heap {
10075                crate::malloc(cap) as *mut u8
10076            } else {
10077                stack.as_mut_ptr()
10078            };
10079            if buf.is_null() {
10080                ERRNO!() = ENOMEM;
10081                return 0;
10082            }
10083            wcs_to_bytes(s, buf, cap);
10084            let mut end: *mut c_char = core::ptr::null_mut();
10085            let r = $conv(buf as *const c_char, &mut end, base);
10086            if !endptr.is_null() {
10087                let offset = end as usize - buf as usize;
10088                *endptr = s.add(offset) as *mut wchar_t;
10089            }
10090            if heap {
10091                crate::free(buf as *mut c_void);
10092            }
10093            r
10094        }
10095    };
10096}
10097
10098wcsto_int!(wcstol, c_long, strtol);
10099wcsto_int!(wcstoul, c_ulong, strtoul);
10100wcsto_int!(wcstoll, c_longlong, strtoll);
10101wcsto_int!(wcstoull, c_ulonglong, strtoull);
10102
10103#[no_mangle]
10104pub unsafe extern "C" fn wcstod(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 {
10105    let cap = wcslen(s).saturating_add(1);
10106    let heap = cap > 256;
10107    let mut stack = [0u8; 256];
10108    let buf = if heap {
10109        crate::malloc(cap) as *mut u8
10110    } else {
10111        stack.as_mut_ptr()
10112    };
10113    if buf.is_null() {
10114        ERRNO!() = ENOMEM;
10115        return 0.0;
10116    }
10117    wcs_to_bytes(s, buf, cap);
10118    let mut end: *mut c_char = core::ptr::null_mut();
10119    let r = strtod(buf as *const c_char, &mut end);
10120    if !endptr.is_null() {
10121        let offset = end as usize - buf as usize;
10122        *endptr = s.add(offset) as *mut wchar_t;
10123    }
10124    if heap {
10125        crate::free(buf as *mut c_void);
10126    }
10127    r
10128}
10129
10130#[no_mangle]
10131pub unsafe extern "C" fn wcstof(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f32 { wcstod(s, endptr) as f32 }
10132
10133#[no_mangle]
10134#[cfg(target_arch = "x86_64")]
10135pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 { wcstod(s, endptr) }
10136
10137#[no_mangle]
10138#[cfg(target_arch = "aarch64")]
10139pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { f64_to_f128(wcstod(s, endptr)) }
10140
10141#[no_mangle]
10142#[cfg(target_arch = "riscv64")]
10143pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { f64_to_f128(wcstod(s, endptr)) }
10144
10145#[no_mangle]
10146pub unsafe extern "C" fn wcstoimax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_longlong { wcstoll(s, endptr, base) }
10147
10148#[no_mangle]
10149pub unsafe extern "C" fn wcstoumax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulonglong { wcstoull(s, endptr, base) }
10150
10151// ============================================================
10152// wctype: classification functions
10153// ============================================================
10154
10155const WC_ALPHA: c_int = 1;
10156const WC_DIGIT: c_int = 2;
10157const WC_SPACE: c_int = 4;
10158const WC_UPPER: c_int = 8;
10159const WC_LOWER: c_int = 16;
10160const WC_ALNUM: c_int = WC_ALPHA | WC_DIGIT;
10161const WC_BLANK: c_int = 32;
10162const WC_CNTRL: c_int = 64;
10163const WC_PUNCT: c_int = 128;
10164const WC_GRAPH: c_int = WC_ALNUM | WC_PUNCT;
10165const WC_PRINT: c_int = WC_GRAPH | WC_BLANK;
10166const WC_XDIGIT: c_int = 256;
10167
10168#[inline]
10169fn wctable_bit(table: &[u8], wc: wint_t) -> bool {
10170    let wc = wc as u32;
10171    let page = table[(wc >> 8) as usize] as usize;
10172    (table[page * 32 + ((wc & 255) >> 3) as usize] >> (wc & 7)) & 1 != 0
10173}
10174
10175/// Port of musl's iswalpha: table lookup below U+20000, then a broad
10176/// alphabetic range up to U+2FFFD.
10177#[no_mangle]
10178pub extern "C" fn iswalpha(c: wint_t) -> c_int {
10179    let wc = c as u32;
10180    if wc < 0x20000 {
10181        return wctable_bit(&WCTYPE_ALPHA_TABLE, c) as c_int;
10182    }
10183    if wc < 0x2fffe { 1 } else { 0 }
10184}
10185
10186/// Port of musl's iswpunct.
10187#[no_mangle]
10188pub extern "C" fn iswpunct(c: wint_t) -> c_int {
10189    let wc = c as u32;
10190    if wc < 0x20000 {
10191        wctable_bit(&WCTYPE_PUNCT_TABLE, c) as c_int
10192    } else {
10193        0
10194    }
10195}
10196
10197/// Port of musl's iswprint.
10198#[no_mangle]
10199pub extern "C" fn iswprint(c: wint_t) -> c_int {
10200    let wc = c as u32;
10201    if wc < 0xff {
10202        return (((wc + 1) & 0x7f) >= 0x21) as c_int;
10203    }
10204    if wc < 0x2028
10205        || wc.wrapping_sub(0x202a) < 0xd800 - 0x202a
10206        || wc.wrapping_sub(0xe000) < 0xfff9 - 0xe000
10207    {
10208        return 1;
10209    }
10210    if wc.wrapping_sub(0xfffc) > 0x10ffff - 0xfffc || (wc & 0xfffe) == 0xfffe {
10211        return 0;
10212    }
10213    1
10214}
10215
10216/// Port of musl's iswspace: Unicode White_Space minus U+00A0/U+2007/U+202F,
10217/// plus U+1680 and U+180E are excluded (they have non-blank glyphs).
10218#[no_mangle]
10219pub extern "C" fn iswspace(c: wint_t) -> c_int {
10220    matches!(
10221        c as u32,
10222        0x20 | 0x09 | 0x0a | 0x0d | 0x0b | 0x0c | 0x85
10223            | 0x2000..=0x2006 | 0x2008..=0x200a
10224            | 0x2028 | 0x2029 | 0x205f | 0x3000
10225    ) as c_int
10226}
10227
10228/// Port of musl's iswcntrl.
10229#[no_mangle]
10230pub extern "C" fn iswcntrl(c: wint_t) -> c_int {
10231    let wc = c as u32;
10232    ((wc < 32)
10233        || wc.wrapping_sub(0x7f) < 33
10234        || wc.wrapping_sub(0x2028) < 2
10235        || wc.wrapping_sub(0xfff9) < 3) as c_int
10236}
10237
10238#[no_mangle]
10239pub extern "C" fn iswdigit(c: wint_t) -> c_int {
10240    ((c as u32).wrapping_sub(b'0' as u32) < 10) as c_int
10241}
10242
10243#[no_mangle]
10244pub extern "C" fn iswxdigit(c: wint_t) -> c_int {
10245    let wc = c as u32;
10246    ((wc.wrapping_sub(b'0' as u32) < 10) || ((wc | 32).wrapping_sub(b'a' as u32) < 6)) as c_int
10247}
10248
10249#[no_mangle]
10250pub extern "C" fn iswalnum(c: wint_t) -> c_int {
10251    (iswdigit(c) != 0 || iswalpha(c) != 0) as c_int
10252}
10253
10254#[no_mangle]
10255pub extern "C" fn iswblank(c: wint_t) -> c_int {
10256    (c == b' ' as wint_t || c == b'\t' as wint_t) as c_int
10257}
10258
10259#[no_mangle]
10260pub extern "C" fn iswgraph(c: wint_t) -> c_int {
10261    (iswspace(c) == 0 && iswprint(c) != 0) as c_int
10262}
10263
10264#[no_mangle]
10265pub extern "C" fn iswlower(c: wint_t) -> c_int {
10266    (unsafe { towupper(c) } != c) as c_int
10267}
10268
10269#[no_mangle]
10270pub extern "C" fn iswupper(c: wint_t) -> c_int {
10271    (unsafe { towlower(c) } != c) as c_int
10272}
10273
10274static WCTYPE_ALNUM: c_int = WC_ALNUM;
10275static WCTYPE_ALPHA: c_int = WC_ALPHA;
10276static WCTYPE_BLANK: c_int = WC_BLANK;
10277static WCTYPE_CNTRL: c_int = WC_CNTRL;
10278static WCTYPE_DIGIT: c_int = WC_DIGIT;
10279static WCTYPE_GRAPH: c_int = WC_GRAPH;
10280static WCTYPE_LOWER: c_int = WC_LOWER;
10281static WCTYPE_PRINT: c_int = WC_PRINT;
10282static WCTYPE_PUNCT: c_int = WC_PUNCT;
10283static WCTYPE_SPACE: c_int = WC_SPACE;
10284static WCTYPE_UPPER: c_int = WC_UPPER;
10285static WCTYPE_XDIGIT: c_int = WC_XDIGIT;
10286
10287#[no_mangle]
10288pub unsafe extern "C" fn wctype(name: *const c_char) -> wctype_t {
10289    if name.is_null() { return core::ptr::null(); }
10290    let n = name as *const u8;
10291    if strcmp(n, b"alnum\0".as_ptr()) == 0 { return &WCTYPE_ALNUM; }
10292    if strcmp(n, b"alpha\0".as_ptr()) == 0 { return &WCTYPE_ALPHA; }
10293    if strcmp(n, b"blank\0".as_ptr()) == 0 { return &WCTYPE_BLANK; }
10294    if strcmp(n, b"cntrl\0".as_ptr()) == 0 { return &WCTYPE_CNTRL; }
10295    if strcmp(n, b"digit\0".as_ptr()) == 0 { return &WCTYPE_DIGIT; }
10296    if strcmp(n, b"graph\0".as_ptr()) == 0 { return &WCTYPE_GRAPH; }
10297    if strcmp(n, b"lower\0".as_ptr()) == 0 { return &WCTYPE_LOWER; }
10298    if strcmp(n, b"print\0".as_ptr()) == 0 { return &WCTYPE_PRINT; }
10299    if strcmp(n, b"punct\0".as_ptr()) == 0 { return &WCTYPE_PUNCT; }
10300    if strcmp(n, b"space\0".as_ptr()) == 0 { return &WCTYPE_SPACE; }
10301    if strcmp(n, b"upper\0".as_ptr()) == 0 { return &WCTYPE_UPPER; }
10302    if strcmp(n, b"xdigit\0".as_ptr()) == 0 { return &WCTYPE_XDIGIT; }
10303    core::ptr::null()
10304}
10305
10306#[no_mangle]
10307pub unsafe extern "C" fn iswctype(c: wint_t, desc: wctype_t) -> c_int {
10308    if desc.is_null() { return 0; }
10309    if desc == core::ptr::addr_of!(WCTYPE_ALNUM) { return iswalnum(c); }
10310    if desc == core::ptr::addr_of!(WCTYPE_ALPHA) { return iswalpha(c); }
10311    if desc == core::ptr::addr_of!(WCTYPE_BLANK) { return iswblank(c); }
10312    if desc == core::ptr::addr_of!(WCTYPE_CNTRL) { return iswcntrl(c); }
10313    if desc == core::ptr::addr_of!(WCTYPE_DIGIT) { return iswdigit(c); }
10314    if desc == core::ptr::addr_of!(WCTYPE_GRAPH) { return iswgraph(c); }
10315    if desc == core::ptr::addr_of!(WCTYPE_LOWER) { return iswlower(c); }
10316    if desc == core::ptr::addr_of!(WCTYPE_PRINT) { return iswprint(c); }
10317    if desc == core::ptr::addr_of!(WCTYPE_PUNCT) { return iswpunct(c); }
10318    if desc == core::ptr::addr_of!(WCTYPE_SPACE) { return iswspace(c); }
10319    if desc == core::ptr::addr_of!(WCTYPE_UPPER) { return iswupper(c); }
10320    if desc == core::ptr::addr_of!(WCTYPE_XDIGIT) { return iswxdigit(c); }
10321    0
10322}
10323
10324static WCTRANS_LOWER: c_int = 1;
10325static WCTRANS_UPPER: c_int = 2;
10326
10327/// Port of musl's casemap() from ctype/towctrans.c.
10328fn casemap(c: wint_t, dir: i32) -> wint_t {
10329    let c0 = c;
10330    if c0 >= 0x20000 {
10331        return c0;
10332    }
10333    let b = (c0 >> 8) as usize;
10334    let cc = c0 & 255;
10335    let x = (cc / 3) as usize;
10336    let y = (cc % 3) as usize;
10337    const MT: [u32; 3] = [2048, 342, 57];
10338    let v = WCTYPE_CASEMAP_TAB[WCTYPE_CASEMAP_TAB[b] as usize * 86 + x] as u32;
10339    let v = (v * MT[y] >> 11) % 6;
10340    let r = WCTYPE_CASEMAP_RULES[(WCTYPE_CASEMAP_RULEBASES[b] + v as u8) as usize];
10341    let rt = (r & 255) as i32;
10342    let rd = r >> 8;
10343    if rt < 2 {
10344        return (c0 as i32 + (rd & -((rt) ^ dir))) as wint_t;
10345    }
10346    let mut xn = (rd & 0xff) as u32;
10347    let mut xb = (rd as u32) >> 8;
10348    while xn != 0 {
10349        let idx = (xb + xn / 2) as usize;
10350        let try_ = WCTYPE_CASEMAP_EXCEPTIONS[idx][0] as u32;
10351        if try_ == cc {
10352            let r2 = WCTYPE_CASEMAP_RULES[WCTYPE_CASEMAP_EXCEPTIONS[idx][1] as usize];
10353            let rt2 = (r2 & 255) as i32;
10354            let rd2 = r2 >> 8;
10355            if rt2 < 2 {
10356                return (c0 as i32 + (rd2 & -((rt2) ^ dir))) as wint_t;
10357            }
10358            return (c0 as i32 + if dir != 0 { -1 } else { 1 }) as wint_t;
10359        } else if try_ > cc {
10360            xn /= 2;
10361        } else {
10362            xb += xn / 2;
10363            xn -= xn / 2;
10364        }
10365    }
10366    c0
10367}
10368
10369#[no_mangle]
10370pub unsafe extern "C" fn towlower(c: wint_t) -> wint_t {
10371    casemap(c, 0)
10372}
10373
10374#[no_mangle]
10375pub unsafe extern "C" fn towupper(c: wint_t) -> wint_t {
10376    casemap(c, 1)
10377}
10378
10379#[no_mangle]
10380pub unsafe extern "C" fn wctrans(name: *const c_char) -> wctrans_t {
10381    if name.is_null() { return core::ptr::null(); }
10382    let n = name as *const u8;
10383    if strcmp(n, b"tolower\0".as_ptr()) == 0 { return &WCTRANS_LOWER; }
10384    if strcmp(n, b"toupper\0".as_ptr()) == 0 { return &WCTRANS_UPPER; }
10385    core::ptr::null()
10386}
10387
10388#[no_mangle]
10389pub unsafe extern "C" fn towctrans(c: wint_t, desc: wctrans_t) -> wint_t {
10390    if desc.is_null() { return c; }
10391    match *desc {
10392        1 => towlower(c),
10393        2 => towupper(c),
10394        _ => c,
10395    }
10396}
10397
10398// ============================================================
10399// wchar: wide stdio
10400// ============================================================
10401
10402#[no_mangle]
10403pub unsafe extern "C" fn fgetwc(f: *mut FILE) -> wint_t {
10404    let mut state: c_uint = 0;
10405    let mut wc: wchar_t = 0;
10406    let mut buf = [0u8; 4];
10407    let c = fgetc(f);
10408    if c == -1 { return WEOF; }
10409    buf[0] = c as u8;
10410    if buf[0] < 0x80 { return buf[0] as wint_t; }
10411    let len = if buf[0] < 0xE0 { 2 } else if buf[0] < 0xF0 { 3 } else { 4 };
10412    let mut n = 1usize;
10413    while n < len {
10414        let c2 = fgetc(f);
10415        if c2 == -1 {
10416            // Put the partial sequence back so a later read sees it.
10417            while n > 1 {
10418                n -= 1;
10419                ungetc(buf[n] as c_int, f);
10420            }
10421            return WEOF;
10422        }
10423        buf[n] = c2 as u8;
10424        n += 1;
10425    }
10426    let r = mbrtowc(&mut wc, buf.as_ptr() as *const c_char, n, &mut state);
10427    if r == !0usize {
10428        ERRNO!() = EILSEQ;
10429        WEOF
10430    } else if r == !1usize {
10431        while n > 0 {
10432            n -= 1;
10433            ungetc(buf[n] as c_int, f);
10434        }
10435        WEOF
10436    } else {
10437        wc as wint_t
10438    }
10439}
10440
10441#[no_mangle]
10442pub unsafe extern "C" fn fputwc(c: wchar_t, f: *mut FILE) -> wint_t {
10443    let mut buf = [0u8; 4];
10444    let n = wcrtomb(buf.as_mut_ptr() as *mut c_char, c, core::ptr::null_mut());
10445    if n == !0usize || n == 0 { return WEOF; }
10446    if fwrite(buf.as_ptr() as *const c_void, 1, n, f) != n { return WEOF; }
10447    c as wint_t
10448}
10449
10450#[no_mangle]
10451pub unsafe extern "C" fn fputws(s: *const wchar_t, f: *mut FILE) -> c_int {
10452    let mut i = 0;
10453    while *s.add(i) != 0 {
10454        if fputwc(*s.add(i), f) == WEOF { return -1; }
10455        i += 1;
10456    }
10457    0
10458}
10459
10460#[no_mangle]
10461pub unsafe extern "C" fn ungetwc(c: wint_t, f: *mut FILE) -> wint_t {
10462    if c == WEOF { return WEOF; }
10463    let mut buf = [0u8; 4];
10464    let n = wcrtomb(buf.as_mut_ptr() as *mut c_char, c as wchar_t, core::ptr::null_mut());
10465    if n == !0usize || n == 0 { return WEOF; }
10466    let mut i = n;
10467    while i > 0 {
10468        i -= 1;
10469        if ungetc(buf[i] as c_int, f) == -1 { return WEOF; }
10470    }
10471    c
10472}
10473
10474#[no_mangle]
10475pub unsafe extern "C" fn getwchar() -> wint_t { fgetwc(stdin) }
10476
10477#[no_mangle]
10478pub unsafe extern "C" fn putwchar(c: wchar_t) -> wint_t { fputwc(c, stdout) }
10479
10480// ============================================================
10481// wchar: swprintf / vswprintf / fwprintf / vfwprintf
10482// ============================================================
10483
10484unsafe fn wfmt_write_str(dst: *mut wchar_t, pos: usize, cap: usize, s: *const u8, len: usize) -> usize {
10485    let mut i = 0;
10486    while i < len {
10487        if pos + i < cap { *dst.add(pos + i) = *s.add(i) as wchar_t; }
10488        i += 1;
10489    }
10490    pos + len
10491}
10492
10493struct HeapGuard(*mut u8);
10494
10495impl Drop for HeapGuard {
10496    fn drop(&mut self) {
10497        if !self.0.is_null() {
10498            unsafe { crate::free(self.0 as *mut c_void); }
10499        }
10500    }
10501}
10502
10503#[no_mangle]
10504unsafe fn vswprintf_impl(
10505    s: *mut *mut wchar_t,
10506    n: usize,
10507    fmt: *const wchar_t,
10508    mut args: VaList,
10509    grow: bool,
10510) -> c_int {
10511    if !grow && n == 0 { return -1; }
10512    let mut buf = *s;
10513    let mut cap = if grow { n } else { n - 1 };
10514    let mut pos = 0usize;
10515    // Format specifiers are ASCII. Keep one byte per wide character so a
10516    // non-ASCII literal can still be emitted from the original string.
10517    let fmt_len = wcslen(fmt);
10518    let fmt_cap = fmt_len.saturating_add(1);
10519    let fmt_guard = HeapGuard(crate::malloc(fmt_cap) as *mut u8);
10520    let fmt_narrow = fmt_guard.0;
10521    if fmt_narrow.is_null() {
10522        ERRNO!() = ENOMEM;
10523        return -1;
10524    }
10525    wcsfmt_to_mbs(fmt_narrow, fmt_cap, fmt);
10526    let mut fi = 0usize;
10527    macro_rules! wc {
10528        ($c:expr) => {
10529            if grow && pos + 1 >= cap {
10530                let newcap = cap.saturating_mul(2).max(pos + 2);
10531                let grown = crate::realloc(buf as *mut c_void, newcap * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
10532                if grown.is_null() { return -1; }
10533                buf = grown;
10534                cap = newcap;
10535            }
10536            if pos < cap { *buf.add(pos) = $c as wchar_t; }
10537            pos += 1;
10538        }
10539    }
10540    macro_rules! wemit {
10541        ($buf:expr, $len:expr) => {
10542            for k in 0..$len { wc!($buf[k]); }
10543        };
10544    }
10545    loop {
10546        let c = *fmt_narrow.add(fi);
10547        if c == 0 { break; }
10548        if c != b'%' {
10549            wc!(*fmt.add(fi) as u32);
10550            fi += 1;
10551            continue;
10552        }
10553        fi += 1;
10554        let fs = parse_format_spec(fmt_narrow, fi, &mut args);
10555        let flags = fs.flags;
10556        let width = fs.width;
10557        let precision = fs.precision;
10558        let len_mod = fs.len1;
10559        fi = fs.next;
10560        if fs.len2 != 0 {
10561            let spec = fs.len2;
10562            let spec2 = fs.spec;
10563            match (len_mod, spec, spec2) {
10564                    (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; } }
10565                    (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; } }
10566                    (b'h', b'h', b'd') | (b'h', b'h', b'i') => {
10567                        let mut fbuf = [0u8; FMT_INT_BUF];
10568                        let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_int>() as i8 as i64, precision, width, flags);
10569                        wemit!(fbuf, len);
10570                    },
10571                    (b'h', b'h', b'u') => {
10572                        let mut fbuf = [0u8; FMT_INT_BUF];
10573                        let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u8 as u64, precision, width, flags);
10574                        wemit!(fbuf, len);
10575                    },
10576                    (b'h', b'h', b'x') => {
10577                        let mut fbuf = [0u8; FMT_INT_BUF];
10578                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u8 as u64, false, precision, width, flags);
10579                        wemit!(fbuf, len);
10580                    },
10581                    (b'h', b'h', b'X') => {
10582                        let mut fbuf = [0u8; FMT_INT_BUF];
10583                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u8 as u64, true, precision, width, flags);
10584                        wemit!(fbuf, len);
10585                    },
10586                    (b'h', b'h', b'o') => {
10587                        let mut fbuf = [0u8; FMT_INT_BUF];
10588                        let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u8 as u64, precision, width, flags);
10589                        wemit!(fbuf, len);
10590                    },
10591                    (b'l', b'l', b'd') | (b'l', b'l', b'i') => {
10592                        let mut fbuf = [0u8; FMT_INT_BUF];
10593                        let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_longlong>() as i64, precision, width, flags);
10594                        wemit!(fbuf, len);
10595                    },
10596                    (b'l', b'l', b'u') => {
10597                        let mut fbuf = [0u8; FMT_INT_BUF];
10598                        let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulonglong>() as u64, precision, width, flags);
10599                        wemit!(fbuf, len);
10600                    },
10601                    (b'l', b'l', b'x') => {
10602                        let mut fbuf = [0u8; FMT_INT_BUF];
10603                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulonglong>() as u64, false, precision, width, flags);
10604                        wemit!(fbuf, len);
10605                    },
10606                    (b'l', b'l', b'X') => {
10607                        let mut fbuf = [0u8; FMT_INT_BUF];
10608                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulonglong>() as u64, true, precision, width, flags);
10609                        wemit!(fbuf, len);
10610                    },
10611                    (b'l', b'l', b'o') => {
10612                        let mut fbuf = [0u8; FMT_INT_BUF];
10613                        let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulonglong>() as u64, precision, width, flags);
10614                        wemit!(fbuf, len);
10615                    },
10616                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); wc!(spec2); }
10617                }
10618            } else if len_mod != 0 {
10619                let spec = fs.spec;
10620                let lm = match len_mod {
10621                        b'z' | b't' if spec != b'n' => b'l',
10622                        // intmax_t is long on every target keel supports.
10623                        b'j' if spec != b'n' => b'l',
10624                        _ => len_mod,
10625                    };
10626                match (lm, spec) {
10627                    (b'h', b'n') => { let p = args.next_arg::<*mut c_void>(); if !p.is_null() { *(p as *mut u16) = pos as u16; } }
10628                    (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; } }
10629                    (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; } }
10630                    (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; } }
10631                    (b'h', b'd') | (b'h', b'i') => {
10632                        let mut fbuf = [0u8; FMT_INT_BUF];
10633                        let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_int>() as i16 as i64, precision, width, flags);
10634                        wemit!(fbuf, len);
10635                    },
10636                    (b'h', b'u') => {
10637                        let mut fbuf = [0u8; FMT_INT_BUF];
10638                        let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u16 as u64, precision, width, flags);
10639                        wemit!(fbuf, len);
10640                    },
10641                    (b'h', b'x') => {
10642                        let mut fbuf = [0u8; FMT_INT_BUF];
10643                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u16 as u64, false, precision, width, flags);
10644                        wemit!(fbuf, len);
10645                    },
10646                    (b'h', b'X') => {
10647                        let mut fbuf = [0u8; FMT_INT_BUF];
10648                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u16 as u64, true, precision, width, flags);
10649                        wemit!(fbuf, len);
10650                    },
10651                    (b'h', b'o') => {
10652                        let mut fbuf = [0u8; FMT_INT_BUF];
10653                        let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u16 as u64, precision, width, flags);
10654                        wemit!(fbuf, len);
10655                    },
10656                    (b'l', b'd') | (b'l', b'i') => {
10657                        let mut fbuf = [0u8; FMT_INT_BUF];
10658                        let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_long>() as i64, precision, width, flags);
10659                        wemit!(fbuf, len);
10660                    },
10661                    (b'l', b'u') => {
10662                        let mut fbuf = [0u8; FMT_INT_BUF];
10663                        let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulong>() as u64, precision, width, flags);
10664                        wemit!(fbuf, len);
10665                    },
10666                    (b'l', b'x') => {
10667                        let mut fbuf = [0u8; FMT_INT_BUF];
10668                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulong>() as u64, false, precision, width, flags);
10669                        wemit!(fbuf, len);
10670                    },
10671                    (b'l', b'X') => {
10672                        let mut fbuf = [0u8; FMT_INT_BUF];
10673                        let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulong>() as u64, true, precision, width, flags);
10674                        wemit!(fbuf, len);
10675                    },
10676                    (b'l', b'o') => {
10677                        let mut fbuf = [0u8; FMT_INT_BUF];
10678                        let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_ulong>() as u64, precision, width, flags);
10679                        wemit!(fbuf, len);
10680                    },
10681                    (b'l', b'c') => {
10682                        let ch = args.next_arg::<wint_t>();
10683                        let pad = width.saturating_sub(1);
10684                        if flags & FLAG_MINUS != 0 {
10685                            wc!(ch);
10686                            for _ in 0..pad { wc!(b' '); }
10687                        } else {
10688                            for _ in 0..pad { wc!(b' '); }
10689                            wc!(ch);
10690                        }
10691                    }
10692                    (b'l', b's') => {
10693                        let ws_arg = args.next_arg::<*const wchar_t>();
10694                        if ws_arg.is_null() {
10695                            let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
10696                            if flags & FLAG_MINUS != 0 {
10697                                for k in 0..slen { wc!(b"(null)"[k]); }
10698                                for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10699                            } else {
10700                                for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10701                                for k in 0..slen { wc!(b"(null)"[k]); }
10702                            }
10703                        } else {
10704                            let mut wlen = 0usize;
10705                            loop {
10706                                let ch = *ws_arg.add(wlen);
10707                                if ch == 0 { break; }
10708                                if precision >= 0 && wlen >= precision as usize { break; }
10709                                wlen += 1;
10710                            }
10711                            if flags & FLAG_MINUS != 0 {
10712                                for k in 0..wlen { wc!(*ws_arg.add(k)); }
10713                                for _ in 0..width.saturating_sub(wlen) { wc!(b' '); }
10714                            } else {
10715                                for _ in 0..width.saturating_sub(wlen) { wc!(b' '); }
10716                                for k in 0..wlen { wc!(*ws_arg.add(k)); }
10717                            }
10718                        }
10719                    }
10720                    (b'l', b'f') | (b'l', b'F') | (b'l', b'e') | (b'l', b'E')
10721                    | (b'l', b'g') | (b'l', b'G') | (b'l', b'a') | (b'l', b'A') => {
10722                        let mut wbuf = [0u8; FMT_FLOAT_BUF];
10723                        let wlen = format_float_into(wbuf.as_mut_ptr(), args.next_arg::<f64>(), spec, precision, width, flags);
10724                        wemit!(wbuf, wlen);
10725                    },
10726                    (b'L', b'f') | (b'L', b'F') | (b'L', b'e') | (b'L', b'E')
10727                    | (b'L', b'g') | (b'L', b'G') | (b'L', b'a') | (b'L', b'A') => {
10728                        #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
10729                        let val = f128_to_f64(valist_read_f128(&mut args));
10730                        #[cfg(target_arch = "x86_64")]
10731                        let val = args.next_arg::<f64>();
10732                        let mut wbuf = [0u8; FMT_FLOAT_BUF];
10733                        let wlen = format_float_into(wbuf.as_mut_ptr(), val, spec, precision, width, flags);
10734                        wemit!(wbuf, wlen);
10735                    },
10736                    _ => { wc!(b'%'); wc!(len_mod); wc!(spec); }
10737                }
10738            } else {
10739            let spec = fs.spec;
10740            match spec {
10741                b'd' | b'i' => {
10742                    let mut fbuf = [0u8; FMT_INT_BUF];
10743                    let len = format_signed_into(fbuf.as_mut_ptr(), args.next_arg::<c_int>() as i64, precision, width, flags);
10744                    wemit!(fbuf, len);
10745                },
10746                b'u' => {
10747                    let mut fbuf = [0u8; FMT_INT_BUF];
10748                    let len = format_unsigned_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u64, precision, width, flags);
10749                    wemit!(fbuf, len);
10750                },
10751                b'x' => {
10752                    let mut fbuf = [0u8; FMT_INT_BUF];
10753                    let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u64, false, precision, width, flags);
10754                    wemit!(fbuf, len);
10755                },
10756                b'X' => {
10757                    let mut fbuf = [0u8; FMT_INT_BUF];
10758                    let len = format_hex_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u64, true, precision, width, flags);
10759                    wemit!(fbuf, len);
10760                },
10761                b'o' => {
10762                    let mut fbuf = [0u8; FMT_INT_BUF];
10763                    let len = format_octal_into(fbuf.as_mut_ptr(), args.next_arg::<c_uint>() as u64, precision, width, flags);
10764                    wemit!(fbuf, len);
10765                },
10766                b'f' | b'F' | b'e' | b'E' | b'g' | b'G' | b'a' | b'A' => {
10767                    let val = args.next_arg::<f64>();
10768                    let ucase = spec == b'F' || spec == b'E' || spec == b'G' || spec == b'A';
10769                    let ftype = match spec | 0x20 { b'f' => FMT_F, b'e' => FMT_E, b'g' => FMT_G, b'a' => FMT_A, _ => FMT_F };
10770                    let mut fbuf = [0u8; FMT_FLOAT_BUF];
10771                    let flen = format_f64_full(fbuf.as_mut_ptr(), val, ftype, precision, flags, ucase);
10772                    let mut wbuf = [0u8; FMT_FLOAT_BUF];
10773                    let wlen = apply_width_flags(wbuf.as_mut_ptr(), fbuf.as_ptr(), flen, width, flags);
10774                    for k in 0..wlen { wc!(wbuf[k]); }
10775                }
10776                b'c' => {
10777                    let ch = args.next_arg::<c_int>();
10778                    wc!(ch as u8);
10779                }
10780                b's' => {
10781                    let p = args.next_arg::<*const c_char>();
10782                    if p.is_null() {
10783                        let slen = if precision >= 0 { (precision as usize).min(6) } else { 6 };
10784                        if flags & FLAG_MINUS != 0 {
10785                            for k in 0..slen { wc!(b"(null)"[k]); }
10786                            for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10787                        } else {
10788                            for _ in 0..width.saturating_sub(slen) { wc!(b' '); }
10789                            for k in 0..slen { wc!(b"(null)"[k]); }
10790                        }
10791                    } else {
10792                        let mut wbuf_local = [0i32; 256];
10793                        let mut wcount = 0usize;
10794                        let mut byte_pos = 0usize;
10795                        let pbytes = p as *const u8;
10796                        loop {
10797                            if precision >= 0 && wcount >= precision as usize { break; }
10798                            if wcount >= 256 { break; }
10799                            let mut wc_val: c_int = 0;
10800                            let consumed = mbrtowc(&mut wc_val as *mut c_int, p.add(byte_pos) as *const c_char, 256, core::ptr::null_mut());
10801                            if consumed == !0usize || consumed == !1usize {
10802                                wbuf_local[wcount] = *pbytes.add(byte_pos) as c_int;
10803                                byte_pos += 1;
10804                                wcount += 1;
10805                            } else if consumed == 0 {
10806                                break;
10807                            } else {
10808                                wbuf_local[wcount] = wc_val;
10809                                byte_pos += consumed;
10810                                wcount += 1;
10811                            }
10812                        }
10813                        if flags & FLAG_MINUS != 0 {
10814                            for k in 0..wcount { wc!(wbuf_local[k]); }
10815                            for _ in 0..width.saturating_sub(wcount) { wc!(b' '); }
10816                        } else {
10817                            for _ in 0..width.saturating_sub(wcount) { wc!(b' '); }
10818                            for k in 0..wcount { wc!(wbuf_local[k]); }
10819                        }
10820                    }
10821                }
10822                b'p' => {
10823                    wc!(b'0'); wc!(b'x');
10824                    let p = args.next_arg::<*const c_void>();
10825                    let b = format_hex(p as u64, false);
10826                    for k in 0..b.1 { wc!(b.0[k]); }
10827                }
10828                b'n' => {
10829                    let p = args.next_arg::<*mut c_void>();
10830                    if !p.is_null() { *(p as *mut c_int) = pos as c_int; }
10831                }
10832                b'%' => { wc!(b'%'); }
10833                _ => { wc!(b'%'); wc!(spec); }
10834            }
10835        }
10836        fi += 1;
10837    }
10838    let null_pos = if pos < cap { pos } else { cap };
10839    *buf.add(null_pos) = 0;
10840    if grow { *s = buf; }
10841    if pos > cap { -1 } else { pos as c_int }
10842}
10843
10844#[no_mangle]
10845pub unsafe extern "C" fn vswprintf(s: *mut wchar_t, n: usize, fmt: *const wchar_t, args: VaList) -> c_int {
10846    let mut buf = s;
10847    vswprintf_impl(&mut buf, n, fmt, args, false)
10848}
10849
10850#[no_mangle]
10851pub unsafe extern "C" fn swprintf(s: *mut wchar_t, n: usize, fmt: *const wchar_t, args: ...) -> c_int {
10852    vswprintf(s, n, fmt, args)
10853}
10854
10855#[no_mangle]
10856pub unsafe extern "C" fn vfwprintf(f: *mut FILE, fmt: *const wchar_t, args: VaList) -> c_int {
10857    // Grow the wide staging buffer instead of failing when the formatted
10858    // output exceeds a fixed size.
10859    let cap = 512usize;
10860    let mut buf = crate::malloc(cap * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
10861    if buf.is_null() {
10862        ERRNO!() = ENOMEM;
10863        return -1;
10864    }
10865    let r = vswprintf_impl(&mut buf, cap, fmt, args, true);
10866    if r < 0 {
10867        crate::free(buf as *mut c_void);
10868        return r;
10869    }
10870    let mut i = 0;
10871    while i < r as usize {
10872        let mut mb = [0u8; 4];
10873        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, *buf.add(i), core::ptr::null_mut());
10874        if n == !0usize {
10875            crate::free(buf as *mut c_void);
10876            return -1;
10877        }
10878        if fwrite(mb.as_ptr() as *const c_void, 1, n, f) != n {
10879            crate::free(buf as *mut c_void);
10880            return -1;
10881        }
10882        i += 1;
10883    }
10884    crate::free(buf as *mut c_void);
10885    r
10886}
10887
10888#[no_mangle]
10889pub unsafe extern "C" fn fwprintf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int {
10890    vfwprintf(f, fmt, args)
10891}
10892
10893// ============================================================
10894// wchar: vswscanf / swscanf / vfwscanf / fwscanf / vwscanf / wscanf
10895// ============================================================
10896
10897// Convert wchar_t format to byte format (ASCII cast, format specifiers are ASCII)
10898unsafe fn wcsfmt_to_mbs(dst: *mut u8, dst_len: usize, src: *const wchar_t) {
10899    let mut i = 0usize;
10900    loop {
10901        let ch = *src.add(i) as u32;
10902        if ch == 0 || i >= dst_len - 1 { break; }
10903        *dst.add(i) = if ch < 128 { ch as u8 } else { b'?' };
10904        i += 1;
10905    }
10906    *dst.add(i) = 0;
10907}
10908
10909#[no_mangle]
10910pub unsafe extern "C" fn vswscanf(s: *const wchar_t, fmt: *const wchar_t, mut args: VaList) -> c_int {
10911    if s.is_null() || fmt.is_null() {
10912        ERRNO!() = EINVAL;
10913        return -1;
10914    }
10915    let wlen = wcslen(s);
10916    let mut cap = wlen.saturating_mul(4).saturating_add(1);
10917    let mut mbs_buf = crate::malloc(cap) as *mut u8;
10918    if mbs_buf.is_null() {
10919        ERRNO!() = ENOMEM;
10920        return -1;
10921    }
10922    let mut i = 0usize;
10923    let mut mb_pos = 0usize;
10924    loop {
10925        let wc = *s.add(i) as c_int;
10926        if wc == 0 { break; }
10927        let mut mb = [0u8; 4];
10928        let n = wcrtomb(mb.as_mut_ptr() as *mut c_char, wc, core::ptr::null_mut());
10929        if n == !0usize || n == 0 { break; }
10930        if mb_pos + n >= cap {
10931            let next = match cap.checked_mul(2) {
10932                Some(v) => v,
10933                None => { crate::free(mbs_buf as *mut c_void); ERRNO!() = ENOMEM; return -1; }
10934            };
10935            let grown = crate::realloc(mbs_buf as *mut c_void, next) as *mut u8;
10936            if grown.is_null() { crate::free(mbs_buf as *mut c_void); ERRNO!() = ENOMEM; return -1; }
10937            mbs_buf = grown;
10938            cap = next;
10939        }
10940        core::ptr::copy_nonoverlapping(mb.as_ptr(), mbs_buf.add(mb_pos), n);
10941        mb_pos += n;
10942        i += 1;
10943    }
10944    *mbs_buf.add(mb_pos) = 0;
10945    let flen = wcslen(fmt);
10946    let fcap = flen.saturating_add(1);
10947    let mbs_fmt = crate::malloc(fcap) as *mut u8;
10948    if mbs_fmt.is_null() {
10949        crate::free(mbs_buf as *mut c_void);
10950        ERRNO!() = ENOMEM;
10951        return -1;
10952    }
10953    wcsfmt_to_mbs(mbs_fmt, fcap, fmt);
10954    let r = do_vsscanf(mbs_buf, mb_pos, mbs_fmt as *const c_char, &mut args, core::ptr::null_mut());
10955    crate::free(mbs_fmt as *mut c_void);
10956    crate::free(mbs_buf as *mut c_void);
10957    r
10958}
10959
10960#[no_mangle]
10961pub unsafe extern "C" fn swscanf(s: *const wchar_t, fmt: *const wchar_t, args: ...) -> c_int {
10962    vswscanf(s, fmt, args)
10963}
10964
10965#[no_mangle]
10966pub unsafe extern "C" fn vfwscanf(f: *mut FILE, fmt: *const wchar_t, mut args: VaList) -> c_int {
10967    if f.is_null() || fmt.is_null() {
10968        ERRNO!() = EINVAL;
10969        return -1;
10970    }
10971    let start_pos = ftello(f);
10972    if start_pos < 0 { return -1; }
10973    let mut cap = SCAN_BUF_INIT;
10974    let mut buf = crate::malloc(cap) as *mut u8;
10975    if buf.is_null() { ERRNO!() = ENOMEM; return -1; }
10976    let mut n = 0usize;
10977    loop {
10978        if n + 1 >= cap {
10979            let next = match cap.checked_mul(2) {
10980                Some(v) => v,
10981                None => { crate::free(buf as *mut c_void); ERRNO!() = ENOMEM; return -1; }
10982            };
10983            let grown = crate::realloc(buf as *mut c_void, next) as *mut u8;
10984            if grown.is_null() { crate::free(buf as *mut c_void); ERRNO!() = ENOMEM; return -1; }
10985            buf = grown;
10986            cap = next;
10987        }
10988        let c = fgetc(f);
10989        if c == -1 { break; }
10990        *buf.add(n) = c as u8;
10991        n += 1;
10992    }
10993    *buf.add(n) = 0;
10994    let flen = wcslen(fmt);
10995    let fcap = flen.saturating_add(1);
10996    let mbs_fmt = crate::malloc(fcap) as *mut u8;
10997    if mbs_fmt.is_null() {
10998        crate::free(buf as *mut c_void);
10999        ERRNO!() = ENOMEM;
11000        return -1;
11001    }
11002    wcsfmt_to_mbs(mbs_fmt, fcap, fmt);
11003    let mut consumed = 0usize;
11004    let hit_eof = (*f)._eof != 0;
11005    let result = do_vsscanf(buf, n, mbs_fmt as *const c_char, &mut args, &mut consumed);
11006    crate::free(mbs_fmt as *mut c_void);
11007    crate::free(buf as *mut c_void);
11008    let _ = fseeko(f, start_pos + consumed as i64, SEEK_SET);
11009    if hit_eof && consumed == n {
11010        (*f)._eof = 1;
11011    }
11012    result
11013}
11014
11015#[no_mangle]
11016pub unsafe extern "C" fn fwscanf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int {
11017    vfwscanf(f, fmt, args)
11018}
11019
11020#[no_mangle]
11021pub unsafe extern "C" fn vwscanf(fmt: *const wchar_t, args: VaList) -> c_int {
11022    vfwscanf(stdin, fmt, args)
11023}
11024
11025#[no_mangle]
11026pub unsafe extern "C" fn wscanf(fmt: *const wchar_t, args: ...) -> c_int {
11027    vfwscanf(stdin, fmt, args)
11028}
11029
11030// ============================================================
11031// Time: internal helpers
11032// ============================================================
11033
11034const LEAPOCH: i64 = 946684800 + 86400 * (31 + 29);
11035const DAYS_PER_400Y: i64 = 365 * 400 + 97;
11036const DAYS_PER_100Y: i64 = 365 * 100 + 24;
11037const DAYS_PER_4Y: i64 = 365 * 4 + 1;
11038
11039const SECS_THROUGH_MONTH: [i32; 12] = [
11040    0, 31*86400, 59*86400, 90*86400, 120*86400, 151*86400,
11041    181*86400, 212*86400, 243*86400, 273*86400, 304*86400, 334*86400,
11042];
11043
11044const DAYS_IN_MONTH: [i32; 12] = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29];
11045
11046unsafe fn year_to_secs(year: i64, is_leap: &mut bool) -> i64 {
11047    // musl compares (year-2) as unsigned: the small-year fast path is only
11048    // valid for 1902..2038.  A signed comparison miscomputes negative years.
11049    if (year.wrapping_sub(2) as u64) <= 136 {
11050        let y = year as i32;
11051        let mut leaps = (y - 68) >> 2;
11052        if (y - 68) & 3 == 0 { leaps -= 1; *is_leap = true; } else { *is_leap = false; }
11053        return 31536000 * (y as i64 - 70) + 86400 * leaps as i64;
11054    }
11055    let mut cycles = ((year - 100) / 400) as i32;
11056    let mut rem = ((year - 100) % 400) as i32;
11057    if rem < 0 { cycles -= 1; rem += 400; }
11058    let (centuries, leaps);
11059    if rem == 0 { *is_leap = true; centuries = 0; leaps = 0; }
11060    else {
11061        let c;
11062        if rem >= 200 { if rem >= 300 { c = 3; rem -= 300; } else { c = 2; rem -= 200; } }
11063        else { if rem >= 100 { c = 1; rem -= 100; } else { c = 0; } }
11064        centuries = c;
11065        if rem == 0 { *is_leap = false; leaps = 0; }
11066        else { leaps = rem / 4; rem %= 4; *is_leap = rem == 0; }
11067    }
11068    let total_leaps = leaps + 97 * cycles + 24 * centuries - (*is_leap as i32);
11069    (year - 100) * 31536000 + total_leaps as i64 * 86400 + 946684800 + 86400
11070}
11071
11072fn month_to_secs(month: i32, is_leap: bool) -> i32 {
11073    let mut t = SECS_THROUGH_MONTH[month as usize];
11074    if is_leap && month >= 2 { t += 86400; }
11075    t
11076}
11077
11078unsafe fn secs_to_tm(t: i64, tm: &mut tm) -> bool {
11079    if t < (i32::MIN as i64) * 31622400 || t > (i32::MAX as i64) * 31622400 { return false; }
11080    let secs = t - LEAPOCH;
11081    let mut days = secs / 86400;
11082    let mut remsecs = (secs % 86400) as i32;
11083    if remsecs < 0 { remsecs += 86400; days -= 1; }
11084    let mut wday = ((3 + days) % 7) as i32;
11085    if wday < 0 { wday += 7; }
11086    let mut qc_cycles = (days / DAYS_PER_400Y) as i32;
11087    let mut remdays = (days % DAYS_PER_400Y) as i32;
11088    if remdays < 0 { remdays += DAYS_PER_400Y as i32; qc_cycles -= 1; }
11089    let mut c_cycles = remdays / DAYS_PER_100Y as i32;
11090    if c_cycles == 4 { c_cycles -= 1; }
11091    remdays -= c_cycles * DAYS_PER_100Y as i32;
11092    let mut q_cycles = remdays / DAYS_PER_4Y as i32;
11093    if q_cycles == 25 { q_cycles -= 1; }
11094    remdays -= q_cycles * DAYS_PER_4Y as i32;
11095    let mut remyears = remdays / 365;
11096    if remyears == 4 { remyears -= 1; }
11097    remdays -= remyears * 365;
11098    let leap = remyears == 0 && (q_cycles != 0 || c_cycles == 0);
11099    let mut yday = remdays + 31 + 28 + leap as i32;
11100    if yday >= 365 + leap as i32 { yday -= 365 + leap as i32; }
11101    let years = remyears as i64 + 4 * q_cycles as i64 + 100 * c_cycles as i64 + 400 * qc_cycles as i64;
11102    let mut months = 0i32;
11103    let mut rd = remdays;
11104    for m in 0..12 {
11105        if DAYS_IN_MONTH[m] <= rd { rd -= DAYS_IN_MONTH[m]; } else { months = m as i32; break; }
11106    }
11107    let mut adj_years = years;
11108    if months >= 10 { months -= 12; adj_years += 1; }
11109    if adj_years + 100 > i32::MAX as i64 || adj_years + 100 < i32::MIN as i64 { return false; }
11110    tm.tm_year = (adj_years + 100) as c_int;
11111    tm.tm_mon = months + 2;
11112    tm.tm_mday = rd + 1;
11113    tm.tm_wday = wday;
11114    tm.tm_yday = yday;
11115    tm.tm_hour = remsecs / 3600;
11116    tm.tm_min = remsecs / 60 % 60;
11117    tm.tm_sec = remsecs % 60;
11118    true
11119}
11120
11121unsafe fn tm_to_secs(tm: *const tm) -> i64 {
11122    let mut year = (*tm).tm_year as i64;
11123    let mut month = (*tm).tm_mon;
11124    if month >= 12 || month < 0 {
11125        let adj = month / 12;
11126        month %= 12;
11127        if month < 0 { month += 12; }
11128        year += adj as i64;
11129    }
11130    let mut is_leap = false;
11131    let mut t = year_to_secs(year, &mut is_leap);
11132    t += month_to_secs(month, is_leap) as i64;
11133    t += 86400 * ((*tm).tm_mday as i64 - 1);
11134    t += 3600 * (*tm).tm_hour as i64;
11135    t += 60 * (*tm).tm_min as i64;
11136    t += (*tm).tm_sec as i64;
11137    t
11138}
11139
11140static mut TM_BUF: tm = tm {
11141    tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0,
11142    tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0,
11143    tm_gmtoff: 0, tm_zone: core::ptr::null(),
11144};
11145
11146static mut UTC_STR: [c_char; 4] = [b'U' as c_char, b'T' as c_char, b'C' as c_char, 0];
11147
11148const CLOCK_PROCESS_CPUTIME_ID: c_int = 2;
11149
11150// ============================================================
11151// Time: core functions
11152// ============================================================
11153
11154#[no_mangle]
11155pub unsafe extern "C" fn time(t: *mut TimeT) -> TimeT {
11156    let mut ts: timespec = core::mem::zeroed();
11157    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
11158    if !t.is_null() { *t = ts.tv_sec; }
11159    ts.tv_sec
11160}
11161
11162#[no_mangle]
11163pub unsafe extern "C" fn difftime(t1: TimeT, t0: TimeT) -> f64 {
11164    (t1 as i64 - t0 as i64) as f64
11165}
11166
11167#[no_mangle]
11168pub unsafe extern "C" fn clock() -> ClockT {
11169    let mut ts: timespec = core::mem::zeroed();
11170    let _ = sys_clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut ts);
11171    ts.tv_sec * 1000000 + ts.tv_nsec / 1000
11172}
11173
11174#[no_mangle]
11175pub unsafe extern "C" fn gmtime(t: *const TimeT) -> *mut tm {
11176    gmtime_r(t, &raw mut TM_BUF)
11177}
11178
11179unsafe fn tm_set_utc(tm: *mut tm) {
11180    (*tm).tm_isdst = 0;
11181    (*tm).tm_gmtoff = 0;
11182    (*tm).tm_zone = core::ptr::addr_of!(UTC_STR).cast::<c_char>();
11183}
11184
11185#[no_mangle]
11186pub unsafe extern "C" fn gmtime_r(t: *const TimeT, tm: *mut tm) -> *mut tm {
11187    if !secs_to_tm(*t as i64, &mut *tm) { ERRNO!() = EOVERFLOW; return core::ptr::null_mut(); }
11188    tm_set_utc(tm);
11189    tm
11190}
11191
11192#[no_mangle]
11193pub unsafe extern "C" fn localtime(t: *const TimeT) -> *mut tm {
11194    tz_localtime_r(t, &raw mut TM_BUF)
11195}
11196
11197#[no_mangle]
11198pub unsafe extern "C" fn localtime_r(t: *const TimeT, tm: *mut tm) -> *mut tm {
11199    tz_localtime_r(t, tm)
11200}
11201
11202#[no_mangle]
11203pub unsafe extern "C" fn mktime(tm: *mut tm) -> TimeT {
11204    tz_mktime(tm)
11205}
11206
11207#[no_mangle]
11208pub unsafe extern "C" fn timegm(tm: *mut tm) -> TimeT {
11209    let t = tm_to_secs(tm as *const tm);
11210    if !secs_to_tm(t, &mut *tm) { ERRNO!() = EOVERFLOW; return -1; }
11211    tm_set_utc(tm);
11212    t as TimeT
11213}
11214
11215static mut ASCTIME_BUF: [c_char; 26] = [0; 26];
11216
11217const 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"];
11218const 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"];
11219
11220#[no_mangle]
11221pub unsafe extern "C" fn asctime(tm: *const tm) -> *mut c_char {
11222    asctime_r(tm, core::ptr::addr_of_mut!(ASCTIME_BUF).cast::<c_char>())
11223}
11224
11225#[no_mangle]
11226pub unsafe extern "C" fn asctime_r(tm: *const tm, buf: *mut c_char) -> *mut c_char {
11227    let wday = if (*tm).tm_wday >= 0 && (*tm).tm_wday < 7 { (*tm).tm_wday as usize } else { 0 };
11228    let mon = if (*tm).tm_mon >= 0 && (*tm).tm_mon < 12 { (*tm).tm_mon as usize } else { 0 };
11229    let dn = DAY_NAMES[wday];
11230    let mn = MON_NAMES[mon];
11231    let mut p = 0;
11232    for k in 0..3 { *buf.add(p) = *dn.as_ptr().add(k) as c_char; p += 1; }
11233    *buf.add(p) = b' ' as c_char; p += 1;
11234    for k in 0..3 { *buf.add(p) = *mn.as_ptr().add(k) as c_char; p += 1; }
11235    *buf.add(p) = b' ' as c_char; p += 1;
11236    // %.3s %.3s%3d: the day is right-aligned in a three-column field.
11237    let v = (*tm).tm_mday;
11238    if v < 10 {
11239        *buf.add(p) = b' ' as c_char; p += 1;
11240        *buf.add(p) = b' ' as c_char; p += 1;
11241        *buf.add(p) = (b'0' + v as u8) as c_char; p += 1;
11242    } else if v < 100 {
11243        *buf.add(p) = b' ' as c_char; p += 1;
11244        *buf.add(p) = (b'0' + (v / 10) as u8) as c_char; p += 1;
11245        *buf.add(p) = (b'0' + (v % 10) as u8) as c_char; p += 1;
11246    } else {
11247        *buf.add(p) = (b'0' + (v / 100) as u8) as c_char; p += 1;
11248        *buf.add(p) = (b'0' + ((v / 10) % 10) as u8) as c_char; p += 1;
11249        *buf.add(p) = (b'0' + (v % 10) as u8) as c_char; p += 1;
11250    }
11251    *buf.add(p) = b' ' as c_char; p += 1;
11252    let hh = (*tm).tm_hour;
11253    *buf.add(p) = (b'0' + (hh / 10) as u8) as c_char; p += 1;
11254    *buf.add(p) = (b'0' + (hh % 10) as u8) as c_char; p += 1;
11255    *buf.add(p) = b':' as c_char; p += 1;
11256    let mm = (*tm).tm_min;
11257    *buf.add(p) = (b'0' + (mm / 10) as u8) as c_char; p += 1;
11258    *buf.add(p) = (b'0' + (mm % 10) as u8) as c_char; p += 1;
11259    *buf.add(p) = b':' as c_char; p += 1;
11260    let ss = (*tm).tm_sec;
11261    *buf.add(p) = (b'0' + (ss / 10) as u8) as c_char; p += 1;
11262    *buf.add(p) = (b'0' + (ss % 10) as u8) as c_char; p += 1;
11263    *buf.add(p) = b' ' as c_char; p += 1;
11264    // %d: negative and >4-digit years are valid in musl asctime.
11265    let yr = (*tm).tm_year as i64 + 1900;
11266    let mut tmp = [0u8; 16];
11267    let mut n = 0usize;
11268    let mut v2 = if yr < 0 { -yr } else { yr };
11269    if v2 == 0 {
11270        tmp[n] = b'0';
11271        n += 1;
11272    } else {
11273        while v2 > 0 && n < tmp.len() {
11274            tmp[n] = b'0' + (v2 % 10) as u8;
11275            v2 /= 10;
11276            n += 1;
11277        }
11278    }
11279    if yr < 0 {
11280        *buf.add(p) = b'-' as c_char;
11281        p += 1;
11282    }
11283    for k in (0..n).rev() {
11284        *buf.add(p) = tmp[k] as c_char;
11285        p += 1;
11286    }
11287    *buf.add(p) = b'\n' as c_char; p += 1;
11288    *buf.add(p) = 0;
11289    buf
11290}
11291
11292#[no_mangle]
11293pub unsafe extern "C" fn ctime(t: *const TimeT) -> *mut c_char {
11294    let tm = localtime(t);
11295    if tm.is_null() { core::ptr::null_mut() } else { asctime(tm) }
11296}
11297
11298#[no_mangle]
11299pub unsafe extern "C" fn ctime_r(t: *const TimeT, buf: *mut c_char) -> *mut c_char {
11300    let mut tmp: tm = core::mem::zeroed();
11301    if localtime_r(t, &mut tmp).is_null() { core::ptr::null_mut() } else { asctime_r(&tmp, buf) }
11302}
11303
11304// ============================================================
11305// Time: clock_getres / clock_settime / clock_nanosleep / gettimeofday
11306// ============================================================
11307
11308unsafe fn sys_clock_getres(clockid: c_int, ts: *mut timespec) -> i64 {
11309    <Arch as Syscalls>::syscall2(SYS_CLOCK_GETRES, clockid as i64, ts as i64)
11310}
11311
11312unsafe fn sys_clock_settime(clockid: c_int, ts: *const timespec) -> i64 {
11313    <Arch as Syscalls>::syscall2(SYS_CLOCK_SETTIME, clockid as i64, ts as i64)
11314}
11315
11316unsafe fn sys_clock_nanosleep(clockid: c_int, flags: c_int, req: *const timespec, rem: *mut timespec) -> i64 {
11317    <Arch as Syscalls>::syscall4(SYS_CLOCK_NANOSLEEP, clockid as i64, flags as i64, req as i64, rem as i64)
11318}
11319
11320#[no_mangle]
11321pub unsafe extern "C" fn clock_getres(clockid: c_int, ts: *mut timespec) -> c_int {
11322    let r = sys_clock_getres(clockid, ts);
11323    syscall_ret(r) as c_int
11324}
11325
11326#[no_mangle]
11327pub unsafe extern "C" fn clock_settime(clockid: c_int, ts: *const timespec) -> c_int {
11328    let r = sys_clock_settime(clockid, ts);
11329    syscall_ret(r) as c_int
11330}
11331
11332#[no_mangle]
11333pub unsafe extern "C" fn clock_nanosleep(clockid: c_int, flags: c_int, req: *const timespec, rem: *mut timespec) -> c_int {
11334    let r = sys_clock_nanosleep(clockid, flags, req, rem);
11335    if r < 0 {
11336        let e = (-r) as c_int;
11337        // The kernel returns EOPNOTSUPP for CLOCK_THREAD_CPUTIME_ID;
11338        // POSIX/musl report EINVAL instead.
11339        if clockid == 3 && e == 95 { return 22; }
11340        e
11341    } else {
11342        0
11343    }
11344}
11345
11346#[no_mangle]
11347pub unsafe extern "C" fn gettimeofday(tv: *mut timeval, _tz: *mut c_void) -> c_int {
11348    if tv.is_null() { return 0; }
11349    let mut ts: timespec = core::mem::zeroed();
11350    let _ = clock_gettime(CLOCK_REALTIME, &mut ts);
11351    (*tv).tv_sec = ts.tv_sec;
11352    (*tv).tv_usec = ts.tv_nsec / 1000;
11353    0
11354}
11355
11356// ============================================================
11357// Time: strftime
11358// ============================================================
11359
11360fn is_leap_year(y: i32) -> bool {
11361    // Widen before adding 1900 so years near i32::MAX cannot wrap; 2000 is
11362    // not congruent to 1900 modulo 400, so the old shortcut was wrong.
11363    let yr = (y as i64) + 1900;
11364    yr % 4 == 0 && (yr % 100 != 0 || yr % 400 == 0)
11365}
11366
11367fn week_num(tm: &tm) -> i32 {
11368    let mut val = (tm.tm_yday + 7 - ((tm.tm_wday + 6) % 7)) / 7;
11369    if (tm.tm_wday + 371 - tm.tm_yday - 2).rem_euclid(7) <= 2 { val += 1; }
11370    if val == 0 {
11371        val = 52;
11372        let dec31 = (tm.tm_wday + 7 - tm.tm_yday - 1).rem_euclid(7);
11373        if dec31 == 4 || (dec31 == 5 && is_leap_year(tm.tm_year % 400 - 1)) { val += 1; }
11374    } else if val == 53 {
11375        let jan1 = (tm.tm_wday + 371 - tm.tm_yday).rem_euclid(7);
11376        if jan1 != 4 && (jan1 != 3 || !is_leap_year(tm.tm_year)) { val = 1; }
11377    }
11378    val
11379}
11380
11381// Langinfo constants for strftime
11382const ABDAY_1: c_int = 0x20000;
11383const DAY_1: c_int = 0x20007;
11384const ABMON_1: c_int = 0x2000E;
11385const MON_1: c_int = 0x2001A;
11386const AM_STR_LI: c_int = 0x20026;
11387const PM_STR_LI: c_int = 0x20027;
11388const D_T_FMT: c_int = 0x20028;
11389const D_FMT: c_int = 0x20029;
11390const T_FMT: c_int = 0x2002A;
11391const T_FMT_AMPM: c_int = 0x2002B;
11392
11393// Format an i64 into buf as decimal with zero/sign padding. Returns (ptr_to_start, length).
11394// pad: '-' = no pad, '_' = space pad, '0' or 0 = zero pad. width: minimum digits (excluding sign).
11395unsafe fn num_fmt(buf: &mut [u8; 100], val: i64, pad: u8, width: usize) -> (*const u8, usize) {
11396    let negative = val < 0;
11397    let mut v = if negative { -val as u64 } else { val as u64 };
11398    let mut tmp = [0u8; 24];
11399    let mut pos = 24usize;
11400    if v == 0 { pos -= 1; tmp[pos] = b'0'; }
11401    while v > 0 { pos -= 1; tmp[pos] = b'0' + (v % 10) as u8; v /= 10; }
11402    let digits = 24 - pos;
11403    let sign_chars = if negative { 1 } else { 0 };
11404    let needed = sign_chars + digits;
11405    let fill = if width > needed { width - needed } else { 0 };
11406    let total = fill + needed;
11407    let mut p = 0usize;
11408    match pad {
11409        b'-' => { /* no fill */ }
11410        b'_' => {
11411            for _ in 0..fill { buf[p] = b' '; p += 1; }
11412            if negative { buf[p] = b'-'; p += 1; }
11413        }
11414        _ => {
11415            if negative { buf[p] = b'-'; p += 1; }
11416            for _ in 0..fill { buf[p] = b'0'; p += 1; }
11417        }
11418    }
11419    for i in 0..digits { buf[p] = tmp[pos + i]; p += 1; }
11420    (buf.as_ptr(), total)
11421}
11422
11423// Copy a null-terminated C string into buf. Returns (ptr, len).
11424unsafe fn str_to_buf(buf: &mut [u8; 100], s: *const c_char) -> (*const u8, usize) {
11425    let mut k = 0usize;
11426    // tm_zone and nl_langinfo strings are caller/file controlled; never walk
11427    // past the fixed buffer (the format result is truncated instead).
11428    while k + 1 < buf.len() && *s.add(k) != 0 {
11429        buf[k] = *s.add(k) as u8;
11430        k += 1;
11431    }
11432    (buf.as_ptr(), k)
11433}
11434
11435// Core format dispatcher. Returns (ptr, len) where ptr points into buf or a static string.
11436// pad=0 means use default; returns (null, 0) for unknown specifiers.
11437unsafe fn __strftime_fmt_1(buf: &mut [u8; 100], f: u8, tm: *const tm, pad: u8) -> (*const u8, usize) {
11438    let mut val: i64;
11439    let mut width: usize = 2;
11440    let mut def_pad: u8 = b'0';
11441    let fmt: *const c_char;
11442
11443    match f {
11444        b'a' => {
11445            if (*tm).tm_wday as u32 > 6 { return (b"\0".as_ptr(), 0); }
11446            let p = nl_langinfo(ABDAY_1 + (*tm).tm_wday);
11447            return str_to_buf(buf, p);
11448        }
11449        b'A' => {
11450            if (*tm).tm_wday as u32 > 6 { return (b"\0".as_ptr(), 0); }
11451            let p = nl_langinfo(DAY_1 + (*tm).tm_wday);
11452            return str_to_buf(buf, p);
11453        }
11454        b'h' | b'b' => {
11455            if (*tm).tm_mon as u32 > 11 { return (b"\0".as_ptr(), 0); }
11456            let p = nl_langinfo(ABMON_1 + (*tm).tm_mon);
11457            return str_to_buf(buf, p);
11458        }
11459        b'B' => {
11460            if (*tm).tm_mon as u32 > 11 { return (b"\0".as_ptr(), 0); }
11461            let p = nl_langinfo(MON_1 + (*tm).tm_mon);
11462            return str_to_buf(buf, p);
11463        }
11464        b'c' => {
11465            let p = nl_langinfo(D_T_FMT);
11466            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11467            return (buf.as_ptr(), l);
11468        }
11469        b'C' => {
11470            val = (1900i64 + (*tm).tm_year as i64) / 100;
11471            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11472        }
11473        b'e' => { def_pad = b'_'; }
11474        b'd' => {
11475            val = (*tm).tm_mday as i64;
11476            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11477        }
11478        b'D' => {
11479            fmt = b"%m/%d/%y\0".as_ptr() as *const c_char;
11480            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11481            return (buf.as_ptr(), l);
11482        }
11483        b'F' => {
11484            fmt = b"%Y-%m-%d\0".as_ptr() as *const c_char;
11485            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11486            return (buf.as_ptr(), l);
11487        }
11488        b'g' | b'G' => {
11489            val = (*tm).tm_year as i64 + 1900;
11490            if (*tm).tm_yday < 3 && week_num(&*tm) != 1 { val -= 1; }
11491            else if (*tm).tm_yday > 360 && week_num(&*tm) == 1 { val += 1; }
11492            if f == b'g' { val %= 100; }
11493            else { width = 4; }
11494            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11495        }
11496        b'H' => {
11497            val = (*tm).tm_hour as i64;
11498            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11499        }
11500        b'I' => {
11501            val = (*tm).tm_hour as i64;
11502            if val == 0 { val = 12; }
11503            else if val > 12 { val -= 12; }
11504            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11505        }
11506        b'j' => {
11507            val = (*tm).tm_yday as i64 + 1;
11508            width = 3;
11509            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11510        }
11511        b'm' => {
11512            val = (*tm).tm_mon as i64 + 1;
11513            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11514        }
11515        b'M' => {
11516            val = (*tm).tm_min as i64;
11517            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11518        }
11519        b'n' => { buf[0] = b'\n'; return (buf.as_ptr(), 1); }
11520        b'p' => {
11521            let p = if (*tm).tm_hour >= 12 { nl_langinfo(PM_STR_LI) } else { nl_langinfo(AM_STR_LI) };
11522            return str_to_buf(buf, p);
11523        }
11524        b'r' => {
11525            let p = nl_langinfo(T_FMT_AMPM);
11526            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11527            return (buf.as_ptr(), l);
11528        }
11529        b'R' => {
11530            fmt = b"%H:%M\0".as_ptr() as *const c_char;
11531            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11532            return (buf.as_ptr(), l);
11533        }
11534        b's' => {
11535            val = tm_to_secs(tm) - (*tm).tm_gmtoff as i64;
11536            width = 1;
11537            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11538        }
11539        b'S' => {
11540            val = (*tm).tm_sec as i64;
11541            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11542        }
11543        b't' => { buf[0] = b'\t'; return (buf.as_ptr(), 1); }
11544        b'T' => {
11545            fmt = b"%H:%M:%S\0".as_ptr() as *const c_char;
11546            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, fmt, tm);
11547            return (buf.as_ptr(), l);
11548        }
11549        b'u' => {
11550            val = if (*tm).tm_wday != 0 { (*tm).tm_wday as i64 } else { 7 };
11551            width = 1;
11552            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11553        }
11554        b'U' => {
11555            val = ((*tm).tm_yday as u64 + 7 - (*tm).tm_wday as u64) as i64 / 7;
11556            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11557        }
11558        b'W' => {
11559            val = ((*tm).tm_yday as u64 + 7 - ((*tm).tm_wday as u64 + 6) % 7) as i64 / 7;
11560            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11561        }
11562        b'V' => {
11563            val = week_num(&*tm) as i64;
11564            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11565        }
11566        b'w' => {
11567            val = (*tm).tm_wday as i64;
11568            width = 1;
11569            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11570        }
11571        b'x' => {
11572            let p = nl_langinfo(D_FMT);
11573            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11574            return (buf.as_ptr(), l);
11575        }
11576        b'X' => {
11577            let p = nl_langinfo(T_FMT);
11578            let l = __strftime_l(buf.as_mut_ptr() as *mut c_char, 100, p, tm);
11579            return (buf.as_ptr(), l);
11580        }
11581        b'y' => {
11582            val = (1900i64 + (*tm).tm_year as i64) % 100;
11583            if val < 0 { val = -val; }
11584            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11585        }
11586        b'Y' => {
11587            val = (*tm).tm_year as i64 + 1900;
11588            if val >= 10000 {
11589                let mut tmp = [0u8; 100];
11590                let (_, k) = num_fmt(&mut tmp, val, b'-', 1);
11591                buf[0] = b'+';
11592                for i in 0..k { buf[1 + i] = tmp[i]; }
11593                return (buf.as_ptr(), 1 + k);
11594            }
11595            width = 4;
11596            return num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width);
11597        }
11598        b'z' => {
11599            if (*tm).tm_isdst < 0 { return (b"\0".as_ptr(), 0); }
11600            let gmtoff = (*tm).tm_gmtoff as i64;
11601            let sign = if gmtoff >= 0 { b'+' } else { b'-' };
11602            let off = if gmtoff < 0 { -gmtoff } else { gmtoff };
11603            let hh = (off / 3600) as i32;
11604            let mm = ((off % 3600) / 60) as i32;
11605            buf[0] = sign;
11606            buf[1] = b'0' + (hh / 10) as u8;
11607            buf[2] = b'0' + (hh % 10) as u8;
11608            buf[3] = b'0' + (mm / 10) as u8;
11609            buf[4] = b'0' + (mm % 10) as u8;
11610            return (buf.as_ptr(), 5);
11611        }
11612        b'Z' => {
11613            if (*tm).tm_isdst < 0 || (*tm).tm_zone.is_null() { return (b"\0".as_ptr(), 0); }
11614            return str_to_buf(buf, (*tm).tm_zone);
11615        }
11616        b'%' => { buf[0] = b'%'; return (buf.as_ptr(), 1); }
11617        _ => { return (core::ptr::null(), 0); }
11618    }
11619    // fallthrough for 'e' (def_pad='_', same logic as 'd')
11620    val = (*tm).tm_mday as i64;
11621    num_fmt(buf, val, if pad != 0 { pad } else { def_pad }, width)
11622}
11623
11624unsafe fn __strftime_l(s: *mut c_char, n: usize, f: *const c_char, tm: *const tm) -> usize {
11625    let mut l: usize = 0;
11626    let mut fi: usize = 0;
11627    while l < n {
11628        let ch = *f.add(fi) as u8;
11629        if ch == 0 {
11630            *s.add(l) = 0;
11631            return l;
11632        }
11633        if ch != b'%' {
11634            *s.add(l) = ch as c_char;
11635            l += 1;
11636            fi += 1;
11637            continue;
11638        }
11639        fi += 1;
11640        // Parse flags
11641        let mut pad: u8 = 0;
11642        let fc = *f.add(fi) as u8;
11643        if fc == b'-' || fc == b'_' || fc == b'0' { pad = fc; fi += 1; }
11644        let plus = *f.add(fi) as u8 == b'+';
11645        if plus { fi += 1; }
11646        // Parse width
11647        let mut width: usize = 0;
11648        let mut p_idx = fi;
11649        {
11650            let fc2 = *f.add(fi) as u8;
11651            if fc2 >= b'0' && fc2 <= b'9' {
11652                let mut w: usize = 0;
11653                while { let c = *f.add(p_idx) as u8; c >= b'0' && c <= b'9' } {
11654                    w = w * 10 + (*f.add(p_idx) as usize - b'0' as usize);
11655                    p_idx += 1;
11656                }
11657                width = w;
11658            }
11659        }
11660        let spec_ch = *f.add(p_idx) as u8;
11661        if spec_ch == b'C' || spec_ch == b'F' || spec_ch == b'G' || spec_ch == b'Y' {
11662            if width == 0 && p_idx != fi { width = 1; }
11663        } else {
11664            width = 0;
11665        }
11666        fi = p_idx;
11667        // Skip E/O modifier
11668        let fc3 = *f.add(fi) as u8;
11669        if fc3 == b'E' || fc3 == b'O' { fi += 1; }
11670        let fch = *f.add(fi) as u8;
11671        // Call formatter
11672        let mut buf = [0u8; 100];
11673        let (t, k) = __strftime_fmt_1(&mut buf, fch, tm, pad);
11674        if t.is_null() { break; }
11675        let mut k = k;
11676        let mut t = t;
11677        if width != 0 {
11678            // Strip sign and leading zeros, count remaining digits
11679            if *t == b'+' || *t == b'-' { t = t.add(1); k -= 1; }
11680            while k > 0 && *t == b'0' && k > 1 && *t.add(1) >= b'0' && *t.add(1) <= b'9' {
11681                t = t.add(1); k -= 1;
11682            }
11683            if width < k { width = k; }
11684            let mut d: usize = 0;
11685            while d < k && *t.add(d) >= b'0' && *t.add(d) <= b'9' { d += 1; }
11686            if (*tm).tm_year < -1900 {
11687                if l < n { *s.add(l) = b'-' as c_char; }
11688                l += 1;
11689                width -= 1;
11690            } else if plus && d + (width - k) >= (if spec_ch == b'C' { 3 } else { 5 }) {
11691                if l < n { *s.add(l) = b'+' as c_char; }
11692                l += 1;
11693                width -= 1;
11694            }
11695            while width > k && l < n {
11696                *s.add(l) = b'0' as c_char;
11697                l += 1;
11698                width -= 1;
11699            }
11700        }
11701        let copy = if k > n - l { n - l } else { k };
11702        core::ptr::copy_nonoverlapping(t, s.add(l) as *mut u8, copy);
11703        l += copy;
11704        fi += 1;
11705    }
11706    if n > 0 {
11707        if l == n { l = n - 1; }
11708        *s.add(l) = 0;
11709    }
11710    0
11711}
11712
11713#[no_mangle]
11714pub unsafe extern "C" fn strftime(s: *mut c_char, maxsize: usize, fmt: *const c_char, tm: *const tm) -> usize {
11715    __strftime_l(s, maxsize, fmt, tm)
11716}
11717
11718// ============================================================
11719// Time: strptime
11720// ============================================================
11721
11722unsafe fn match_prefix(s: *const u8, prefix: &[u8]) -> bool {
11723    for i in 0..prefix.len() {
11724        if *s.add(i) == 0 || *s.add(i) != prefix[i] { return false; }
11725    }
11726    true
11727}
11728
11729unsafe fn match_ci_prefix(s: *const u8, prefix: &[u8]) -> bool {
11730    for i in 0..prefix.len() {
11731        let c = *s.add(i);
11732        if c == 0 { return false; }
11733        if c.to_ascii_lowercase() != prefix[i].to_ascii_lowercase() { return false; }
11734    }
11735    true
11736}
11737
11738unsafe fn parse_int(p: *const u8, max_digits: usize) -> (i32, *const u8) {
11739    let mut val = 0i32;
11740    let mut np = p;
11741    let mut count = 0;
11742    while *np >= b'0' && *np <= b'9' && count < max_digits {
11743        val = val * 10 + (*np - b'0') as i32;
11744        np = np.add(1);
11745        count += 1;
11746    }
11747    if count == 0 { (0, p) } else { (val, np) }
11748}
11749
11750unsafe fn parse_range(p: *const u8, min: i32, max: i32) -> (i32, *const u8) {
11751    let (val, np) = parse_int(p, 4);
11752    if np == p || val < min || val > max { (0, p) } else { (val, np) }
11753}
11754
11755fn is_ascii_space(c: u8) -> bool {
11756    c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == 0x0c || c == 0x0b
11757}
11758
11759const WDAY_FULL: [&[u8]; 7] = [
11760    b"Sunday", b"Monday", b"Tuesday", b"Wednesday", b"Thursday", b"Friday", b"Saturday",
11761];
11762const WDAY_ABBR: [&[u8]; 7] = [b"Sun", b"Mon", b"Tue", b"Wed", b"Thu", b"Fri", b"Sat"];
11763const MON_FULL: [&[u8]; 12] = [
11764    b"January", b"February", b"March", b"April", b"May", b"June",
11765    b"July", b"August", b"September", b"October", b"November", b"December",
11766];
11767const MON_ABBR: [&[u8]; 12] = [
11768    b"Jan", b"Feb", b"Mar", b"Apr", b"May", b"Jun",
11769    b"Jul", b"Aug", b"Sep", b"Oct", b"Nov", b"Dec",
11770];
11771
11772/// Parse a `%z` offset (`+hhmm`, `+hh`, or `+hhmmss` is not accepted) and
11773/// return the seconds east of UTC plus the first unconsumed byte.
11774unsafe fn parse_tz_offset(mut p: *const u8) -> Option<(i64, *const u8)> {
11775    if *p != b'+' && *p != b'-' { return None; }
11776    let neg = *p == b'-';
11777    p = p.add(1);
11778    let mut off = 0i64;
11779    let mut digits = 0;
11780    while digits < 4 && *p >= b'0' && *p <= b'9' {
11781        off = off * 10 + (*p - b'0') as i64;
11782        p = p.add(1);
11783        digits += 1;
11784    }
11785    if digits == 0 { return None; }
11786    let (hh, mm) = if digits <= 2 { (off, 0i64) } else { (off / 100, off % 100) };
11787    Some(((hh * 3600 + mm * 60) * if neg { -1 } else { 1 }, p))
11788}
11789
11790#[no_mangle]
11791pub unsafe extern "C" fn strptime(s: *const c_char, fmt: *const c_char, tm: *mut tm) -> *mut c_char {
11792    let mut p = s as *const u8;
11793    let mut f = fmt as *const u8;
11794    let mut want_century = 0i32;
11795    let mut century = 0i32;
11796    let mut relyear = 0i32;
11797    while *f != 0 {
11798        if *f != b'%' {
11799            if is_ascii_space(*f) {
11800                while *p != 0 && is_ascii_space(*p) { p = p.add(1); }
11801            } else {
11802                if *p != *f { return core::ptr::null_mut(); }
11803                p = p.add(1);
11804            }
11805            f = f.add(1);
11806            continue;
11807        }
11808        f = f.add(1);
11809        if *f == b'+' { f = f.add(1); }
11810        while *f >= b'0' && *f <= b'9' { f = f.add(1); }
11811        if *f == b'E' || *f == b'O' { f = f.add(1); }
11812        match *f {
11813            b'a' | b'A' => {
11814                let mut found = false;
11815                for i in 0..7 {
11816                    if match_prefix(p, WDAY_FULL[i]) { (*tm).tm_wday = i as c_int; p = p.add(WDAY_FULL[i].len()); found = true; break; }
11817                    if match_prefix(p, WDAY_ABBR[i]) { (*tm).tm_wday = i as c_int; p = p.add(WDAY_ABBR[i].len()); found = true; break; }
11818                }
11819                if !found { return core::ptr::null_mut(); }
11820            }
11821            b'b' | b'B' | b'h' => {
11822                let mut found = false;
11823                for i in 0..12 {
11824                    if match_prefix(p, MON_FULL[i]) { (*tm).tm_mon = i as c_int; p = p.add(MON_FULL[i].len()); found = true; break; }
11825                    if match_prefix(p, MON_ABBR[i]) { (*tm).tm_mon = i as c_int; p = p.add(MON_ABBR[i].len()); found = true; break; }
11826                }
11827                if !found { return core::ptr::null_mut(); }
11828            }
11829            b'C' => {
11830                let (v, np) = parse_int(p, 2);
11831                if np == p { return core::ptr::null_mut(); }
11832                century = v;
11833                want_century |= 2;
11834                p = np;
11835            }
11836            b'd' | b'e' => {
11837                let (v, np) = parse_range(p, 1, 31);
11838                if np == p { return core::ptr::null_mut(); }
11839                (*tm).tm_mday = v;
11840                p = np;
11841            }
11842            b'D' => {
11843                let r = strptime(p as *const c_char, b"%m/%d/%y\0".as_ptr() as *const c_char, tm);
11844                if r.is_null() { return core::ptr::null_mut(); }
11845                p = r as *const u8;
11846            }
11847            b'F' => {
11848                let r = strptime(p as *const c_char, b"%Y-%m-%d\0".as_ptr() as *const c_char, tm);
11849                if r.is_null() { return core::ptr::null_mut(); }
11850                p = r as *const u8;
11851            }
11852            b'H' | b'I' => {
11853                let (v, np) = parse_range(p, 0, 23);
11854                if np == p { return core::ptr::null_mut(); }
11855                (*tm).tm_hour = v;
11856                p = np;
11857            }
11858            b'j' => {
11859                let (v, np) = parse_range(p, 1, 366);
11860                if np == p { return core::ptr::null_mut(); }
11861                (*tm).tm_yday = v - 1;
11862                p = np;
11863            }
11864            b'm' => {
11865                let (v, np) = parse_range(p, 1, 12);
11866                if np == p { return core::ptr::null_mut(); }
11867                (*tm).tm_mon = v - 1;
11868                p = np;
11869            }
11870            b'M' => {
11871                let (v, np) = parse_range(p, 0, 59);
11872                if np == p { return core::ptr::null_mut(); }
11873                (*tm).tm_min = v;
11874                p = np;
11875            }
11876            b'n' | b't' => {
11877                while *p != 0 && is_ascii_space(*p) { p = p.add(1); }
11878            }
11879            b'p' => {
11880                if match_ci_prefix(p, b"AM") {
11881                    if (*tm).tm_hour == 12 { (*tm).tm_hour = 0; }
11882                    p = p.add(2);
11883                } else if match_ci_prefix(p, b"PM") {
11884                    if (*tm).tm_hour < 12 { (*tm).tm_hour += 12; }
11885                    p = p.add(2);
11886                } else { return core::ptr::null_mut(); }
11887            }
11888            b'r' => {
11889                let r = strptime(p as *const c_char, b"%I:%M:%S %p\0".as_ptr() as *const c_char, tm);
11890                if r.is_null() { return core::ptr::null_mut(); }
11891                p = r as *const u8;
11892            }
11893            b'R' => {
11894                let r = strptime(p as *const c_char, b"%H:%M\0".as_ptr() as *const c_char, tm);
11895                if r.is_null() { return core::ptr::null_mut(); }
11896                p = r as *const u8;
11897            }
11898            b's' => {
11899                let neg = if *p == b'-' { p = p.add(1); true } else { false };
11900                if *p < b'0' || *p > b'9' { return core::ptr::null_mut(); }
11901                let mut val = 0i64;
11902                while *p >= b'0' && *p <= b'9' {
11903                    val = val * 10 + (*p - b'0') as i64;
11904                    p = p.add(1);
11905                }
11906                if neg { val = -val; }
11907                secs_to_tm(val, &mut *tm);
11908            }
11909            b'S' => {
11910                let (v, np) = parse_range(p, 0, 60);
11911                if np == p { return core::ptr::null_mut(); }
11912                (*tm).tm_sec = v;
11913                p = np;
11914            }
11915            b'T' => {
11916                let r = strptime(p as *const c_char, b"%H:%M:%S\0".as_ptr() as *const c_char, tm);
11917                if r.is_null() { return core::ptr::null_mut(); }
11918                p = r as *const u8;
11919            }
11920            b'U' | b'W' => {
11921                let (_, np) = parse_range(p, 0, 53);
11922                if np == p { return core::ptr::null_mut(); }
11923                p = np;
11924            }
11925            b'V' => {
11926                let (_, np) = parse_range(p, 1, 53);
11927                if np == p { return core::ptr::null_mut(); }
11928                p = np;
11929            }
11930            b'w' => {
11931                let (v, np) = parse_range(p, 0, 6);
11932                if np == p { return core::ptr::null_mut(); }
11933                (*tm).tm_wday = v;
11934                p = np;
11935            }
11936            b'y' => {
11937                let (v, np) = parse_int(p, 2);
11938                if np == p { return core::ptr::null_mut(); }
11939                relyear = v;
11940                want_century |= 1;
11941                p = np;
11942            }
11943            b'Y' => {
11944                let neg = if *p == b'-' { p = p.add(1); true } else { false };
11945                let (v, np) = parse_int(p, 4);
11946                if np == p { return core::ptr::null_mut(); }
11947                (*tm).tm_year = if neg { -(v + 1900) } else { v - 1900 };
11948                want_century = 0;
11949                p = np;
11950            }
11951            b'z' => {
11952                let (off, np) = match parse_tz_offset(p) {
11953                    Some(v) => v,
11954                    None => return core::ptr::null_mut(),
11955                };
11956                (*tm).tm_gmtoff = off;
11957                p = np;
11958            }
11959            b'Z' => {
11960                let mut matched = false;
11961                for i in 0..2 {
11962                    let name = crate::tzname[i];
11963                    if name.is_null() { continue; }
11964                    let len = strlen(name);
11965                    if strncmp(p, name as *const u8, len) == 0 {
11966                        (*tm).tm_isdst = i as c_int;
11967                        p = p.add(len);
11968                        matched = true;
11969                        break;
11970                    }
11971                }
11972                if !matched {
11973                    // No match: skip an alphabetic zone abbreviation.
11974                    while *p != 0 && (*p | 32).wrapping_sub(b'a') <= 25 { p = p.add(1); }
11975                }
11976            }
11977            b'%' => {
11978                if *p != b'%' { return core::ptr::null_mut(); }
11979                p = p.add(1);
11980            }
11981            _ => { return core::ptr::null_mut(); }
11982        }
11983        f = f.add(1);
11984    }
11985    if want_century != 0 {
11986        (*tm).tm_year = relyear;
11987        if want_century & 2 != 0 { (*tm).tm_year += century * 100 - 1900; }
11988        else if (*tm).tm_year <= 68 { (*tm).tm_year += 100; }
11989    }
11990    p as *mut c_char
11991}
11992
11993// ============================================================
11994// Time: tzset / daylight / timezone / tzname
11995// ============================================================
11996
11997#[no_mangle]
11998pub static mut daylight: c_int = 0;
11999#[no_mangle]
12000pub static mut timezone: c_long = 0;
12001#[no_mangle]
12002pub 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];
12003
12004#[no_mangle]
12005pub unsafe extern "C" fn tzset() {
12006    tz_set();
12007}
12008
12009// ============================================================
12010// system()
12011// ============================================================
12012
12013#[no_mangle]
12014pub unsafe extern "C" fn system(cmd: *const c_char) -> c_int {
12015    if cmd.is_null() {
12016        // test shell availability via fork+exec
12017        let pid = sys_fork();
12018        if pid == 0 {
12019            let sh = b"/bin/sh\0".as_ptr() as *const c_char;
12020            let dash_c = b"-c\0".as_ptr() as *const c_char;
12021            let exit0 = b"exit 0\0".as_ptr() as *const c_char;
12022            let argv = [b"sh\0".as_ptr() as *const c_char, dash_c, exit0, core::ptr::null()];
12023            sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
12024            _exit(127);
12025        }
12026        if pid < 0 { return -1; }
12027        let mut status: c_int = 0;
12028        loop {
12029            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
12030            if r >= 0 { return status; }
12031            if r != -4 { return -1; } // not EINTR
12032        }
12033    }
12034
12035    let sa_ignore = KSigAction {
12036        sa_handler: SIG_IGN,
12037        sa_flags: SA_RESTORER,
12038        sa_restorer: sig_restorer as *const () as usize,
12039        sa_mask: [0],
12040    };
12041    let mut oldint: KSigAction = core::mem::zeroed();
12042    let mut oldquit: KSigAction = core::mem::zeroed();
12043
12044    sys_rt_sigaction(SIGINT, &sa_ignore, &mut oldint, 8);
12045    sys_rt_sigaction(SIGQUIT, &sa_ignore, &mut oldquit, 8);
12046
12047    let mut block_set: SigSetT = 0;
12048    block_set |= 1u64 << (SIGCHLD - 1);
12049    let mut oldmask: SigSetT = 0;
12050    sys_rt_sigprocmask(SIG_BLOCK, &block_set, &mut oldmask, 8);
12051
12052    let pid = sys_fork();
12053
12054    if pid == 0 {
12055        sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
12056        sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
12057        sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
12058
12059        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
12060        let argv = [
12061            b"sh\0".as_ptr() as *const c_char,
12062            b"-c\0".as_ptr() as *const c_char,
12063            cmd,
12064            core::ptr::null(),
12065        ];
12066        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
12067        _exit(127);
12068    }
12069
12070    let mut status: c_int = -1;
12071    if pid > 0 {
12072        loop {
12073            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
12074            if r >= 0 { break; }
12075            if r != -4 { break; } // not EINTR
12076        }
12077    }
12078
12079    sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
12080    sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
12081    sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
12082
12083    status
12084}
12085
12086// ============================================================
12087// errno: strerror / strerror_r / environ alias
12088// ============================================================
12089
12090// static error string table indexed by errno
12091static ERR_STRS: [&[u8]; 134] = [
12092    b"Success\0",                     // 0
12093    b"Operation not permitted\0",     // 1
12094    b"No such file or directory\0",   // 2
12095    b"No such process\0",             // 3
12096    b"Interrupted system call\0",     // 4
12097    b"Input/output error\0",          // 5
12098    b"No such device or address\0",   // 6
12099    b"Argument list too long\0",      // 7
12100    b"Exec format error\0",           // 8
12101    b"Bad file descriptor\0",         // 9
12102    b"No child processes\0",          // 10
12103    b"Resource temporarily unavailable\0", // 11
12104    b"Cannot allocate memory\0",      // 12
12105    b"Permission denied\0",           // 13
12106    b"Bad address\0",                 // 14
12107    b"Block device required\0",       // 15
12108    b"Device or resource busy\0",     // 16
12109    b"File exists\0",                 // 17
12110    b"Invalid cross-device link\0",   // 18
12111    b"No such device\0",              // 19
12112    b"Not a directory\0",             // 20
12113    b"Is a directory\0",              // 21
12114    b"Invalid argument\0",            // 22
12115    b"Too many open files in system\0", // 23
12116    b"Too many open files\0",         // 24
12117    b"Inappropriate ioctl for device\0", // 25
12118    b"Text file busy\0",              // 26
12119    b"File too large\0",              // 27
12120    b"No space left on device\0",     // 28
12121    b"Illegal seek\0",                // 29
12122    b"Read-only file system\0",       // 30
12123    b"Too many links\0",              // 31
12124    b"Broken pipe\0",                 // 32
12125    b"Numerical argument out of domain\0", // 33
12126    b"Numerical result out of range\0", // 34
12127    b"Resource deadlock avoided\0",   // 35
12128    b"File name too long\0",          // 36
12129    b"No locks available\0",          // 37
12130    b"Function not implemented\0",    // 38
12131    b"Directory not empty\0",         // 39
12132    b"Too many levels of symbolic links\0", // 40
12133    b"Unknown error 41\0",            // 41
12134    b"No message of desired type\0",  // 42
12135    b"Identifier removed\0",          // 43
12136    b"Channel number out of range\0", // 44
12137    b"Level 2 not synchronized\0",    // 45
12138    b"Level 3 halted\0",              // 46
12139    b"Level 3 reset\0",               // 47
12140    b"Link number out of range\0",    // 48
12141    b"Protocol driver not attached\0", // 49
12142    b"No CSI structure available\0",  // 50
12143    b"Level 2 halted\0",              // 51
12144    b"Invalid exchange\0",            // 52
12145    b"Invalid request descriptor\0",  // 53
12146    b"Exchange full\0",               // 54
12147    b"No anode\0",                    // 55
12148    b"Invalid request code\0",        // 56
12149    b"Invalid slot\0",                // 57
12150    b"Unknown error 58\0",            // 58
12151    b"Bad font file format\0",        // 59
12152    b"Device not a stream\0",         // 60
12153    b"No data available\0",           // 61
12154    b"Timer expired\0",               // 62
12155    b"Out of streams resources\0",    // 63
12156    b"Machine is not on the network\0", // 64
12157    b"Package not installed\0",       // 65
12158    b"Object is remote\0",            // 66
12159    b"Link has been severed\0",       // 67
12160    b"Advertise error\0",             // 68
12161    b"Srmount error\0",               // 69
12162    b"Communication error on send\0", // 70
12163    b"Protocol error\0",              // 71
12164    b"Multihop attempted\0",          // 72
12165    b"RFS specific error\0",          // 73
12166    b"Bad message\0",                 // 74
12167    b"Value too large for defined data type\0", // 75
12168    b"Name not unique on network\0",  // 76
12169    b"File descriptor in bad state\0", // 77
12170    b"Remote address changed\0",      // 78
12171    b"Can not access a needed shared library\0", // 79
12172    b"Accessing a corrupted shared library\0", // 80
12173    b".lib section in a.out corrupted\0", // 81
12174    b"Attempting to link in too many shared libraries\0", // 82
12175    b"Cannot exec a shared library directly\0", // 83
12176    b"Invalid or incomplete multibyte or wide character\0", // 84
12177    b"Interrupted system call should be restarted\0", // 85
12178    b"Streams pipe error\0",          // 86
12179    b"Too many users\0",              // 87
12180    b"Socket operation on non-socket\0", // 88
12181    b"Destination address required\0", // 89
12182    b"Message too long\0",            // 90
12183    b"Protocol wrong type for socket\0", // 91
12184    b"Protocol not available\0",      // 92
12185    b"Protocol not supported\0",      // 93
12186    b"Socket type not supported\0",   // 94
12187    b"Operation not supported\0",     // 95
12188    b"Protocol family not supported\0", // 96
12189    b"Address family not supported by protocol\0", // 97
12190    b"Address already in use\0",      // 98
12191    b"Cannot assign requested address\0", // 99
12192    b"Network is down\0",             // 100
12193    b"Network is unreachable\0",      // 101
12194    b"Network dropped connection on reset\0", // 102
12195    b"Software caused connection abort\0", // 103
12196    b"Connection reset by peer\0",    // 104
12197    b"No buffer space available\0",   // 105
12198    b"Transport endpoint is already connected\0", // 106
12199    b"Transport endpoint is not connected\0", // 107
12200    b"Cannot send after transport endpoint shutdown\0", // 108
12201    b"Too many references: cannot splice\0", // 109
12202    b"Connection timed out\0",        // 110
12203    b"Connection refused\0",          // 111
12204    b"Host is down\0",                // 112
12205    b"No route to host\0",            // 113
12206    b"Operation already in progress\0", // 114
12207    b"Operation now in progress\0",   // 115
12208    b"Stale file handle\0",           // 116
12209    b"Structure needs cleaning\0",    // 117
12210    b"Not a XENIX named type file\0", // 118
12211    b"No XENIX semaphores available\0", // 119
12212    b"Is a named type file\0",        // 120
12213    b"Remote I/O error\0",            // 121
12214    b"Quota exceeded\0",              // 122
12215    b"No medium found\0",             // 123
12216    b"Wrong medium type\0",           // 124
12217    b"Operation canceled\0",          // 125
12218    b"Required key not available\0",  // 126
12219    b"Key has expired\0",             // 127
12220    b"Key has been revoked\0",        // 128
12221    b"Key was rejected by service\0", // 129
12222    b"Owner died\0",                  // 130
12223    b"State not recoverable\0",       // 131
12224    b"Operation not possible due to RF-kill\0", // 132
12225    b"Memory page has hardware error\0", // 133
12226];
12227
12228#[no_mangle]
12229pub unsafe extern "C" fn strerror(errnum: c_int) -> *mut c_char {
12230    if errnum < 0 || errnum as usize >= ERR_STRS.len() {
12231        // static buf for unknown errors
12232        static mut UNKNOWN_BUF: [c_char; 64] = [0; 64];
12233        let prefix = b"Unknown error \0";
12234        let mut i = 0;
12235        while prefix[i] != 0 {
12236            UNKNOWN_BUF[i] = prefix[i] as c_char;
12237            i += 1;
12238        }
12239        let (buf, len) = format_u64(errnum.unsigned_abs() as u64);
12240        for j in 0..len {
12241            UNKNOWN_BUF[i] = buf[20 - len + j] as c_char;
12242            i += 1;
12243        }
12244        UNKNOWN_BUF[i] = 0;
12245        return core::ptr::addr_of_mut!(UNKNOWN_BUF).cast::<c_char>();
12246    }
12247    ERR_STRS[errnum as usize].as_ptr() as *mut c_char
12248}
12249
12250#[no_mangle]
12251pub unsafe extern "C" fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: usize) -> c_int {
12252    let s = strerror(errnum);
12253    let slen = strlen(s as *const c_char);
12254    if slen >= buflen {
12255        if buflen > 0 {
12256            core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, buflen - 1);
12257            *buf.add(buflen - 1) = 0;
12258        }
12259        return 34; // ERANGE
12260    }
12261    core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, slen + 1);
12262    0
12263}
12264
12265// Alias for programs that declare `extern char **environ`.
12266#[no_mangle]
12267pub static mut environ: *mut *mut c_char = core::ptr::null_mut();
12268
12269// keep environ in sync with __environ
12270unsafe fn sync_environ() {
12271    environ = __environ;
12272}
12273
12274// ============================================================
12275// unistd extensions: pipe, dup, dup2, fcntl, access, unlink, etc.
12276// ============================================================
12277
12278#[inline]
12279unsafe fn sys_dup(oldfd: i32) -> i64 {
12280    <Arch as Syscalls>::syscall1(SYS_DUP, oldfd as i64)
12281}
12282
12283#[inline]unsafe fn sys_dup2(oldfd: i32, newfd: i32) -> i64 {
12284    // dup3 with flags=0 is equivalent to dup2
12285    sys_dup3(oldfd, newfd, 0)
12286}
12287
12288#[inline]
12289unsafe fn sys_access(path: *const u8, mode: i32) -> i64 {
12290    <Arch as Syscalls>::syscall4(SYS_FACCESSAT, AT_FDCWD as i64, path as i64, mode as i64, 0)
12291}
12292
12293#[inline]unsafe fn sys_unlink(path: *const u8) -> i64 {
12294    sys_unlinkat(AT_FDCWD, path, 0)
12295}
12296
12297#[inline]unsafe fn sys_rmdir(path: *const u8) -> i64 {
12298    sys_unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
12299}
12300
12301#[inline]
12302unsafe fn sys_chdir(path: *const u8) -> i64 {
12303    <Arch as Syscalls>::syscall1(SYS_CHDIR, path as i64)
12304}
12305
12306#[inline]
12307unsafe fn sys_getcwd(buf: *mut u8, size: usize) -> i64 {
12308    <Arch as Syscalls>::syscall2(SYS_GETCWD, buf as i64, size as i64)
12309}
12310
12311#[inline]
12312unsafe fn sys_sethostname(name: *const u8, len: usize) -> i64 {
12313    <Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)
12314}
12315
12316#[inline]
12317unsafe fn sys_gethostname(buf: *mut u8, len: usize) -> i64 {
12318    #[repr(C)]
12319    struct UtsName {
12320        sysname: [u8; 65],
12321        nodename: [u8; 65],
12322        release: [u8; 65],
12323        version: [u8; 65],
12324        machine: [u8; 65],
12325        domainname: [u8; 65],
12326    }
12327    let mut uts: UtsName = core::mem::zeroed();
12328    let result = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
12329    if result < 0 {
12330        return result;
12331    }
12332    let nlen = strlen(uts.nodename.as_ptr() as *const c_char);
12333    let copylen = if nlen < len { nlen } else { if len > 0 { len - 1 } else { 0 } };
12334    core::ptr::copy_nonoverlapping(uts.nodename.as_ptr(), buf, copylen);
12335    if len > 0 { *buf.add(copylen) = 0; }
12336    0
12337}
12338
12339unsafe fn sys_truncate(path: *const u8, length: i64) -> i64 {
12340    <Arch as Syscalls>::syscall2(SYS_TRUNCATE, path as i64, length as i64)
12341}
12342
12343unsafe fn sys_ftruncate(fd: i32, length: i64) -> i64 {
12344    <Arch as Syscalls>::syscall2(SYS_FTRUNCATE, fd as i64, length as i64)
12345}
12346
12347unsafe fn sys_nanosleep(req: *const timespec, rem: *mut timespec) -> i64 {
12348    <Arch as Syscalls>::syscall2(SYS_NANOSLEEP, req as i64, rem as i64)
12349}
12350
12351const ITIMER_REAL: i32 = 0;
12352
12353#[repr(C)]
12354struct itimerval {
12355    it_interval: timeval,
12356    it_value: timeval,
12357}
12358
12359unsafe fn sys_alarm(seconds: c_uint) -> i64 {
12360    let mut new: itimerval = core::mem::zeroed();
12361    new.it_value.tv_sec = seconds as c_long;
12362    let mut old: itimerval = core::mem::zeroed();
12363    let r = <Arch as Syscalls>::syscall3(
12364        SYS_SETITIMER,
12365        ITIMER_REAL as i64,
12366        &new as *const _ as i64,
12367        &mut old as *mut _ as i64,
12368    );
12369    if r < 0 {
12370        return r;
12371    }
12372    old.it_value.tv_sec as i64 + (old.it_value.tv_usec != 0) as i64
12373}
12374
12375unsafe fn sys_pause() -> i64 {
12376    #[cfg(target_arch = "x86_64")]
12377    { <Arch as Syscalls>::syscall0(SYS_PAUSE) }
12378    #[cfg(target_arch = "aarch64")]
12379    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
12380    #[cfg(target_arch = "riscv64")]
12381    { <Arch as Syscalls>::syscall4(SYS_PPOLL, 0, 0, 0, 0) }
12382}
12383
12384unsafe fn sys_fsync(fd: i32) -> i64 {
12385    <Arch as Syscalls>::syscall1(SYS_FSYNC, fd as i64)
12386}
12387
12388unsafe fn sys_fdatasync(fd: i32) -> i64 {
12389    <Arch as Syscalls>::syscall1(SYS_FDATASYNC, fd as i64)
12390}
12391
12392unsafe fn sys_sync() {
12393    let _ = <Arch as Syscalls>::syscall0(SYS_SYNC);
12394}
12395
12396unsafe fn sys_symlink(target: *const u8, linkpath: *const u8) -> i64 {
12397    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, AT_FDCWD as i64, linkpath as i64)
12398}
12399
12400unsafe fn sys_symlinkat(target: *const u8, newdirfd: i32, linkpath: *const u8) -> i64 {
12401    <Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)
12402}
12403
12404unsafe fn sys_readlinkat(dirfd: i32, path: *const u8, buf: *mut u8, bufsiz: usize) -> i64 {
12405    <Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, path as i64, buf as i64, bufsiz as i64)
12406}
12407
12408unsafe fn sys_linkat(olddirfd: i32, oldpath: *const u8, newdirfd: i32, newpath: *const u8, flags: i32) -> i64 {
12409    <Arch as Syscalls>::syscall5(SYS_LINKAT, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, flags as i64)
12410}
12411
12412unsafe fn sys_fchmod(fd: i32, mode: u32) -> i64 {
12413    <Arch as Syscalls>::syscall2(SYS_FCHMOD, fd as i64, mode as i64)
12414}
12415
12416unsafe fn sys_fchmodat(dirfd: i32, path: *const u8, mode: u32, flags: i32) -> i64 {
12417    <Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, path as i64, mode as i64, flags as i64)
12418}
12419
12420unsafe fn sys_umask(mask: u32) -> u32 {
12421    <Arch as Syscalls>::syscall1(SYS_UMASK, mask as i64) as u32
12422}
12423
12424unsafe fn sys_getgroups(size: i32, list: *mut c_uint) -> i64 {
12425    <Arch as Syscalls>::syscall2(SYS_GETGROUPS, size as i64, list as i64)
12426}
12427
12428unsafe fn sys_setuid(uid: c_uint) -> i64 {
12429    <Arch as Syscalls>::syscall1(SYS_SETUID, uid as i64)
12430}
12431
12432unsafe fn sys_setgid(gid: c_uint) -> i64 {
12433    <Arch as Syscalls>::syscall1(SYS_SETGID, gid as i64)
12434}
12435
12436unsafe fn sys_setsid() -> i64 {
12437    <Arch as Syscalls>::syscall0(SYS_SETSID)
12438}
12439
12440unsafe fn sys_setpgid(pid: c_int, pgid: c_int) -> i64 {
12441    <Arch as Syscalls>::syscall2(SYS_SETPGID, pid as i64, pgid as i64)
12442}
12443
12444unsafe fn sys_getpgid(pid: c_int) -> i64 {
12445    <Arch as Syscalls>::syscall1(SYS_GETPGID, pid as i64)
12446}
12447
12448unsafe fn sys_getsid(pid: c_int) -> i64 {
12449    <Arch as Syscalls>::syscall1(SYS_GETSID, pid as i64)
12450}
12451
12452unsafe fn sys_mkdirat(dirfd: i32, path: *const u8, mode: u32) -> i64 {
12453    <Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, path as i64, mode as i64)
12454}
12455
12456// Public C ABI wrappers for unistd
12457
12458#[no_mangle]
12459pub unsafe extern "C" fn pipe(fds: *mut c_int) -> c_int {
12460    let r = sys_pipe2(fds, 0);
12461    syscall_ret(r) as c_int
12462}
12463
12464#[no_mangle]
12465pub unsafe extern "C" fn pipe2(fds: *mut c_int, flags: c_int) -> c_int {
12466    let r = sys_pipe2(fds, flags);
12467    syscall_ret(r) as c_int
12468}
12469
12470#[no_mangle]
12471pub unsafe extern "C" fn dup(oldfd: c_int) -> c_int {
12472    let r = sys_dup(oldfd);
12473    syscall_ret(r) as c_int
12474}
12475
12476#[no_mangle]
12477pub unsafe extern "C" fn dup2(oldfd: c_int, newfd: c_int) -> c_int {
12478    if oldfd == newfd {
12479        // dup3 rejects equal descriptors with EINVAL; dup2 must validate the
12480        // descriptor and return newfd unchanged.
12481        let r = sys_fcntl(oldfd, 1 /* F_GETFD */, 0);
12482        if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12483        return newfd;
12484    }
12485    let r = sys_dup2(oldfd, newfd);
12486    syscall_ret(r) as c_int
12487}
12488
12489#[no_mangle]
12490pub unsafe extern "C" fn dup3(oldfd: c_int, newfd: c_int, flags: c_int) -> c_int {
12491    let r = sys_dup3(oldfd, newfd, flags);
12492    syscall_ret(r) as c_int
12493}
12494
12495#[no_mangle]
12496pub unsafe extern "C" fn fcntl(fd: c_int, cmd: c_int, mut args: ...) -> c_int {
12497    // Commands without an argument. Everything else (including seals,
12498    // pipe sizes, ownership and locks) takes the third argument.
12499    let no_arg = matches!(cmd, F_GETFD | F_GETFL | F_GETOWN | F_GETSIG
12500        | F_GETLEASE | F_GETPIPE_SZ | F_GET_SEALS);
12501    let r = if no_arg {
12502        sys_fcntl(fd, cmd, 0)
12503    } else {
12504        let arg = args.next_arg::<c_long>();
12505        sys_fcntl(fd, cmd, arg)
12506    };
12507    syscall_ret(r) as c_int
12508}
12509
12510#[no_mangle]
12511pub unsafe extern "C" fn access(path: *const c_char, mode: c_int) -> c_int {
12512    let r = sys_access(path as *const u8, mode);
12513    syscall_ret(r) as c_int
12514}
12515
12516#[no_mangle]
12517pub unsafe extern "C" fn unlink(path: *const c_char) -> c_int {
12518    let r = sys_unlink(path as *const u8);
12519    syscall_ret(r) as c_int
12520}
12521
12522#[no_mangle]
12523pub unsafe extern "C" fn rmdir(path: *const c_char) -> c_int {
12524    let r = sys_rmdir(path as *const u8);
12525    syscall_ret(r) as c_int
12526}
12527
12528#[no_mangle]
12529pub unsafe extern "C" fn chdir(path: *const c_char) -> c_int {
12530    let r = sys_chdir(path as *const u8);
12531    syscall_ret(r) as c_int
12532}
12533
12534#[no_mangle]
12535pub unsafe extern "C" fn getcwd(buf: *mut c_char, size: usize) -> *mut c_char {
12536    if buf.is_null() {
12537        // allocate
12538        let alloc_size = if size == 0 { 256 } else { size };
12539        let p = malloc(alloc_size) as *mut c_char;
12540        if p.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
12541        let r = sys_getcwd(p as *mut u8, alloc_size);
12542        if r < 0 { free(p as *mut c_void); ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
12543        // The kernel returns "(unreachable)..." when cwd is outside the
12544        // current root; POSIX getcwd must fail with ENOENT in that case.
12545        if *p as u8 != b'/' {
12546            free(p as *mut c_void);
12547            ERRNO!() = ENOENT;
12548            return core::ptr::null_mut();
12549        }
12550        return p;
12551    }
12552    if size == 0 { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
12553    let r = sys_getcwd(buf as *mut u8, size);
12554    if r < 0 { ERRNO!() = (-r) as c_int; return core::ptr::null_mut(); }
12555    if *buf as u8 != b'/' {
12556        ERRNO!() = ENOENT;
12557        return core::ptr::null_mut();
12558    }
12559    buf
12560}
12561
12562#[no_mangle]
12563pub unsafe extern "C" fn gethostname(name: *mut c_char, len: usize) -> c_int {
12564    let r = sys_gethostname(name as *mut u8, len);
12565    syscall_ret(r) as c_int
12566}
12567
12568// Linux page size.  This is hardcoded to 4096 on every architecture; that
12569// is correct for the CI hosts but not for aarch64/riscv64 kernels with a
12570// larger base page size.  See sysconf(_SC_PAGE_SIZE) for the same value.
12571#[no_mangle]
12572pub extern "C" fn getpagesize() -> c_int {
12573    PAGE as c_int
12574}
12575
12576#[no_mangle]
12577pub unsafe extern "C" fn truncate(path: *const c_char, length: i64) -> c_int {
12578    let r = sys_truncate(path as *const u8, length);
12579    syscall_ret(r) as c_int
12580}
12581
12582#[no_mangle]
12583pub unsafe extern "C" fn ftruncate(fd: c_int, length: i64) -> c_int {
12584    let r = sys_ftruncate(fd, length);
12585    syscall_ret(r) as c_int
12586}
12587
12588#[no_mangle]
12589pub unsafe extern "C" fn nanosleep(req: *const timespec, rem: *mut timespec) -> c_int {
12590    pthread_testcancel();
12591    let r = sys_nanosleep(req, rem);
12592    pthread_testcancel();
12593    syscall_ret(r) as c_int
12594}
12595
12596#[no_mangle]
12597pub unsafe extern "C" fn sleep(seconds: c_uint) -> c_uint {
12598    let req = timespec { tv_sec: seconds as c_long, tv_nsec: 0 };
12599    let mut rem: timespec = core::mem::zeroed();
12600    pthread_testcancel();
12601    let r = sys_nanosleep(&req, &mut rem);
12602    pthread_testcancel();
12603    if r < 0 {
12604        let e = (-r) as c_int;
12605        if e == EINTR { return rem.tv_sec as c_uint; }
12606    }
12607    0
12608}
12609
12610#[no_mangle]
12611pub unsafe extern "C" fn usleep(usec: c_uint) -> c_int {
12612    let req = timespec { tv_sec: (usec / 1000000) as c_long, tv_nsec: ((usec % 1000000) * 1000) as c_long };
12613    pthread_testcancel();
12614    let r = sys_nanosleep(&req, core::ptr::null_mut());
12615    pthread_testcancel();
12616    syscall_ret(r) as c_int
12617}
12618
12619#[no_mangle]
12620pub unsafe extern "C" fn alarm(seconds: c_uint) -> c_uint {
12621    // POSIX rounds a nonzero fractional remainder up to one second;
12622    // sys_alarm() already performs that rounding.
12623    let r = sys_alarm(seconds);
12624    if r < 0 { 0 } else { r as c_uint }
12625}
12626
12627#[no_mangle]
12628pub unsafe extern "C" fn pause() -> c_int {
12629    pthread_testcancel();
12630    sys_pause();
12631    pthread_testcancel();
12632    ERRNO!() = EINTR;
12633    -1
12634}
12635
12636#[no_mangle]
12637pub unsafe extern "C" fn fsync(fd: c_int) -> c_int {
12638    let r = sys_fsync(fd);
12639    syscall_ret(r) as c_int
12640}
12641
12642#[no_mangle]
12643pub unsafe extern "C" fn fdatasync(fd: c_int) -> c_int {
12644    let r = sys_fdatasync(fd);
12645    syscall_ret(r) as c_int
12646}
12647
12648#[no_mangle]
12649pub unsafe extern "C" fn sync() {
12650    sys_sync();
12651}
12652
12653#[no_mangle]
12654pub unsafe extern "C" fn symlink(target: *const c_char, linkpath: *const c_char) -> c_int {
12655    let r = sys_symlinkat(target as *const u8, AT_FDCWD, linkpath as *const u8);
12656    syscall_ret(r) as c_int
12657}
12658
12659#[no_mangle]
12660pub unsafe extern "C" fn readlink(path: *const c_char, buf: *mut c_char, bufsiz: usize) -> isize {
12661    let r = sys_readlinkat(AT_FDCWD, path as *const u8, buf as *mut u8, bufsiz);
12662    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
12663    r as isize
12664}
12665
12666#[no_mangle]
12667pub unsafe extern "C" fn link(oldpath: *const c_char, newpath: *const c_char) -> c_int {
12668    let r = sys_linkat(AT_FDCWD, oldpath as *const u8, AT_FDCWD, newpath as *const u8, 0);
12669    syscall_ret(r) as c_int
12670}
12671
12672#[no_mangle]
12673pub unsafe extern "C" fn chmod(path: *const c_char, mode: c_uint) -> c_int {
12674    let r = sys_fchmodat(AT_FDCWD, path as *const u8, mode, 0);
12675    syscall_ret(r) as c_int
12676}
12677
12678#[no_mangle]
12679pub unsafe extern "C" fn fchmod(fd: c_int, mode: c_uint) -> c_int {
12680    let r = sys_fchmod(fd, mode);
12681    syscall_ret(r) as c_int
12682}
12683
12684#[no_mangle]
12685pub unsafe extern "C" fn umask(mask: c_uint) -> c_uint {
12686    sys_umask(mask) as c_uint
12687}
12688
12689#[no_mangle]
12690pub unsafe extern "C" fn isatty(fd: c_int) -> c_int {
12691    let mut ws: winsize = core::mem::zeroed();
12692    if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 { 1 } else { 0 }
12693}
12694
12695#[no_mangle]
12696pub unsafe extern "C" fn getlogin() -> *mut c_char {
12697    crate::getenv(b"LOGNAME\0".as_ptr() as *const c_char)
12698}
12699
12700#[no_mangle]
12701pub unsafe extern "C" fn getgroups(size: c_int, list: *mut c_uint) -> c_int {
12702    let r = sys_getgroups(size, list);
12703    syscall_ret(r) as c_int
12704}
12705
12706#[no_mangle]
12707pub unsafe extern "C" fn setuid(uid: c_uint) -> c_int {
12708    let r = sys_setuid(uid);
12709    syscall_ret(r) as c_int
12710}
12711
12712#[no_mangle]
12713pub unsafe extern "C" fn setgid(gid: c_uint) -> c_int {
12714    let r = sys_setgid(gid);
12715    syscall_ret(r) as c_int
12716}
12717
12718#[no_mangle]
12719pub unsafe extern "C" fn seteuid(euid: c_uint) -> c_int {
12720    // Setting only the effective uid must keep the real and saved uids, so a
12721    // process can drop privileges and later restore them (setuid would clear
12722    // the saved uid for root).
12723    setresuid(u32::MAX, euid, u32::MAX)
12724}
12725
12726#[no_mangle]
12727pub unsafe extern "C" fn setegid(egid: c_uint) -> c_int {
12728    setresgid(u32::MAX, egid, u32::MAX)
12729}
12730
12731#[no_mangle]
12732pub unsafe extern "C" fn setreuid(ruid: c_uint, euid: c_uint) -> c_int {
12733    let r = <Arch as Syscalls>::syscall2(SYS_SETREUID, ruid as i64, euid as i64);
12734    syscall_ret(r) as c_int
12735}
12736
12737
12738
12739#[no_mangle]
12740pub unsafe extern "C" fn setsid() -> c_int {
12741    let r = sys_setsid();
12742    syscall_ret(r) as c_int
12743}
12744
12745#[no_mangle]
12746pub unsafe extern "C" fn setpgid(pid: c_int, pgid: c_int) -> c_int {
12747    let r = sys_setpgid(pid, pgid);
12748    syscall_ret(r) as c_int
12749}
12750
12751#[no_mangle]
12752pub unsafe extern "C" fn getpgid(pid: c_int) -> c_int {
12753    let r = sys_getpgid(pid);
12754    syscall_ret(r) as c_int
12755}
12756
12757#[no_mangle]
12758pub unsafe extern "C" fn getsid(pid: c_int) -> c_int {
12759    let r = sys_getsid(pid);
12760    syscall_ret(r) as c_int
12761}
12762
12763#[no_mangle]
12764pub unsafe extern "C" fn getpgrp() -> c_int {
12765    sys_getpgid(0) as c_int
12766}
12767
12768#[no_mangle]
12769pub unsafe extern "C" fn setpgrp() -> c_int {
12770    setpgid(0, 0)
12771}
12772
12773#[no_mangle]
12774unsafe fn mkstemps_impl(template: *mut c_char, suffixlen: i32) -> c_int {
12775    mkstemps_flags(template, suffixlen, 0)
12776}
12777
12778unsafe fn mkstemps_flags(template: *mut c_char, suffixlen: i32, flags: i32) -> c_int {
12779    if template.is_null() || suffixlen < 0 {
12780        ERRNO!() = EINVAL;
12781        return -1;
12782    }
12783    let len = strlen(template as *const c_char);
12784    let suffix = suffixlen as usize;
12785    if len < 6 + suffix {
12786        ERRNO!() = EINVAL;
12787        return -1;
12788    }
12789    let x_start = len - suffix - 6;
12790    for i in x_start..x_start + 6 {
12791        if *template.add(i) != b'X' as c_char {
12792            ERRNO!() = EINVAL;
12793            return -1;
12794        }
12795    }
12796    let mut ts: timespec = core::mem::zeroed();
12797    let _ = sys_clock_gettime(CLOCK_REALTIME, &mut ts);
12798    let mut ctr: u32 = ts.tv_nsec as u32;
12799    for _ in 0..100 {
12800        ctr = ctr.wrapping_mul(1103515245).wrapping_add(12345);
12801        let mut seed = ctr;
12802        let hex = b"0123456789abcdef";
12803        for i in x_start..x_start + 6 {
12804            *template.add(i) = hex[(seed & 0xf) as usize] as c_char;
12805            seed >>= 4;
12806        }
12807        let fd = sys_open(template as *const u8, (O_RDWR | O_CREAT | O_EXCL | flags) as i64, 0o600);
12808        if fd >= 0 {
12809            return fd as c_int;
12810        }
12811        let e = (-fd) as c_int;
12812        if e != EEXIST {
12813            ERRNO!() = e;
12814            return -1;
12815        }
12816    }
12817    ERRNO!() = EEXIST;
12818    -1
12819}
12820
12821#[no_mangle]
12822pub unsafe extern "C" fn mkstemp(template: *mut c_char) -> c_int {
12823    mkstemps_impl(template, 0)
12824}
12825
12826#[no_mangle]
12827pub unsafe extern "C" fn mkdir(path: *const c_char, mode: c_uint) -> c_int {
12828    let r = sys_mkdirat(AT_FDCWD, path as *const u8, mode);
12829    syscall_ret(r) as c_int
12830}
12831
12832// ============================================================
12833// libgen: basename / dirname
12834// ============================================================
12835
12836#[no_mangle]
12837pub unsafe extern "C" fn dirname(s: *mut c_char) -> *mut c_char {
12838    if s.is_null() || *s == 0 {
12839        return b".\0".as_ptr() as *mut c_char;
12840    }
12841    let mut i = strlen(s as *const c_char);
12842    i = i.wrapping_sub(1);
12843    // skip trailing slashes
12844    while i > 0 && *s.add(i) == b'/' as c_char {
12845        i = i.wrapping_sub(1);
12846    }
12847    if i == 0 && *s.add(0) == b'/' as c_char {
12848        return b"/\0".as_ptr() as *mut c_char;
12849    }
12850    // skip non-slashes
12851    while i > 0 && *s.add(i) != b'/' as c_char {
12852        i = i.wrapping_sub(1);
12853    }
12854    if i == 0 {
12855        if *s.add(0) == b'/' as c_char {
12856            return b"/\0".as_ptr() as *mut c_char;
12857        }
12858        return b".\0".as_ptr() as *mut c_char;
12859    }
12860    // skip slashes
12861    while i > 0 && *s.add(i - 1) == b'/' as c_char {
12862        i = i.wrapping_sub(1);
12863    }
12864    if i == 0 {
12865        return b"/\0".as_ptr() as *mut c_char;
12866    }
12867    *s.add(i) = 0;
12868    s
12869}
12870
12871#[no_mangle]
12872pub unsafe extern "C" fn basename(s: *mut c_char) -> *mut c_char {
12873    if s.is_null() || *s == 0 {
12874        return b".\0".as_ptr() as *mut c_char;
12875    }
12876    let mut i = strlen(s as *const c_char);
12877    i = i.wrapping_sub(1);
12878    // strip trailing slashes
12879    while i > 0 && *s.add(i) == b'/' as c_char {
12880        *s.add(i) = 0;
12881        i = i.wrapping_sub(1);
12882    }
12883    // find last slash
12884    while i > 0 && *s.add(i - 1) != b'/' as c_char {
12885        i = i.wrapping_sub(1);
12886    }
12887    s.add(i)
12888}
12889
12890// ============================================================
12891// arpa/inet: inet_pton / inet_ntop / inet_addr / inet_ntoa / inet_aton
12892// ============================================================
12893
12894const AF_INET_VAL: c_int = 2;
12895const AF_INET6_VAL: c_int = 10;
12896
12897unsafe fn inet_pton_v4(s: *const u8, a: *mut u8) -> c_int {
12898    let mut p = s;
12899    let mut i = 0;
12900    while i < 4 {
12901        let oct_start = p;
12902        let mut v: u32 = 0;
12903        let mut j: u32 = 0;
12904        while j < 3 && *p >= b'0' && *p <= b'9' {
12905            v = v * 10 + (*p - b'0') as u32;
12906            p = p.add(1);
12907            j += 1;
12908        }
12909        if j == 0 || (j > 1 && *oct_start == b'0') || v > 255 { return 0; }
12910        *a.add(i) = v as u8;
12911        if *p == 0 && i == 3 { return 1; }
12912        if *p != b'.' { return 0; }
12913        p = p.add(1);
12914        i += 1;
12915    }
12916    0
12917}
12918
12919unsafe fn inet_pton_v6(s: *const u8, a: *mut u8) -> c_int {
12920    let mut ip = [0u16; 8];
12921    let mut p = s;
12922    let mut i: usize = 0;
12923    let mut brk: isize = -1;
12924    let mut need_v4 = false;
12925    let mut v4_start: *const u8 = core::ptr::null();
12926
12927    if *p == b':' {
12928        p = p.add(1);
12929        if *p != b':' { return 0; }
12930    }
12931
12932    loop {
12933        if *p == b':' && brk < 0 {
12934            brk = i as isize;
12935            ip[i & 7] = 0;
12936            p = p.add(1);
12937            if *p == 0 { break; }
12938            if i == 7 { return 0; }
12939            i += 1;
12940            continue;
12941        }
12942        v4_start = p;
12943        let mut v: u16 = 0;
12944        let mut j = 0;
12945        while j < 4 {
12946            let d = hex_digit(*p);
12947            if d < 0 { break; }
12948            v = v * 16 + d as u16;
12949            p = p.add(1);
12950            j += 1;
12951        }
12952        if j == 0 { return 0; }
12953        ip[i & 7] = v;
12954        if *p == 0 && (brk >= 0 || i == 7) { break; }
12955        if i == 7 { return 0; }
12956        if *p != b':' {
12957            if *p != b'.' || (i < 6 && brk < 0) { return 0; }
12958            need_v4 = true;
12959            i += 1;
12960            ip[i & 7] = 0;
12961            break;
12962        }
12963        p = p.add(1);
12964        i += 1;
12965    }
12966
12967    if brk >= 0 {
12968        // expand :: : move trailing fields to the end and zero the gap
12969        let trail_count = i + 1 - brk as usize;
12970        let dest_start = brk as usize + 7 - i;
12971        // move backwards to avoid overwrite in the overlapping case
12972        for j in (0..trail_count).rev() {
12973            ip[dest_start + j] = ip[brk as usize + j];
12974        }
12975        for j in 0..(7 - i) {
12976            ip[brk as usize + j] = 0;
12977        }
12978    }
12979
12980    for k in 0..8 {
12981        *a.add(k * 2) = (ip[k] >> 8) as u8;
12982        *a.add(k * 2 + 1) = (ip[k] & 0xff) as u8;
12983    }
12984
12985    if need_v4 {
12986        if inet_pton_v4(v4_start, a.add(12)) <= 0 { return 0; }
12987    }
12988    1
12989}
12990
12991unsafe fn hex_digit(c: u8) -> i32 {
12992    if c >= b'0' && c <= b'9' { (c - b'0') as i32 }
12993    else if c >= b'a' && c <= b'f' { (c - b'a' + 10) as i32 }
12994    else if c >= b'A' && c <= b'F' { (c - b'A' + 10) as i32 }
12995    else { -1 }
12996}
12997
12998#[no_mangle]
12999pub unsafe extern "C" fn inet_pton(af: c_int, s: *const c_char, a: *mut c_void) -> c_int {
13000    if af == AF_INET_VAL {
13001        inet_pton_v4(s as *const u8, a as *mut u8)
13002    } else if af == AF_INET6_VAL {
13003        inet_pton_v6(s as *const u8, a as *mut u8)
13004    } else {
13005        ERRNO!() = EAFNOSUPPORT;
13006        -1
13007    }
13008}
13009
13010#[no_mangle]
13011pub unsafe extern "C" fn inet_ntop(af: c_int, a: *const c_void, s: *mut c_char, size: u32) -> *mut c_char {
13012    if af == AF_INET_VAL {
13013        let b = a as *const u8;
13014        let needed = 16; // "255.255.255.255\0"
13015        if size < needed as u32 { ERRNO!() = ENOSPC; return core::ptr::null_mut(); }
13016        let mut pos = 0;
13017        for i in 0..4 {
13018            if i > 0 { *s.add(pos) = b'.' as c_char; pos += 1; }
13019            let (buf, len) = format_u64(*b.add(i) as u64);
13020            for j in 0..len { *s.add(pos) = buf[j] as c_char; pos += 1; }
13021        }
13022        *s.add(pos) = 0;
13023        s
13024    } else if af == AF_INET6_VAL {
13025        let b = a as *const u8;
13026        let needed = 46; // max IPv6
13027        if size < needed as u32 { ERRNO!() = ENOSPC; return core::ptr::null_mut(); }
13028        let mut words = [0u16; 8];
13029        for i in 0..8 {
13030            words[i] = ((*b.add(i * 2) as u16) << 8) | (*b.add(i * 2 + 1) as u16);
13031        }
13032        // IPv4-mapped: ::ffff:a.b.c.d
13033        let mut pos = 0usize;
13034        if words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0
13035            && words[4] == 0 && words[5] == 0xffff
13036        {
13037            let prefix = b"::ffff:";
13038            for k in 0..prefix.len() { *s.add(pos) = prefix[k] as c_char; pos += 1; }
13039            for idx in 0..4 {
13040                if idx > 0 { *s.add(pos) = b'.' as c_char; pos += 1; }
13041                let octet = *b.add(12 + idx);
13042                if octet >= 100 {
13043                    *s.add(pos) = (b'0' + octet / 100) as c_char; pos += 1;
13044                    *s.add(pos) = (b'0' + (octet / 10) % 10) as c_char; pos += 1;
13045                } else if octet >= 10 {
13046                    *s.add(pos) = (b'0' + octet / 10) as c_char; pos += 1;
13047                }
13048                *s.add(pos) = (b'0' + octet % 10) as c_char; pos += 1;
13049            }
13050            *s.add(pos) = 0;
13051            return s;
13052        }
13053        // find longest run of zeros
13054        let mut best_start: isize = -1;
13055        let mut best_len: usize = 0;
13056        let mut j: usize = 0;
13057        while j < 8 {
13058            if words[j] == 0 {
13059                let mut k = j;
13060                while k < 8 && words[k] == 0 { k += 1; }
13061                let run = k - j;
13062                if run > best_len { best_start = j as isize; best_len = run; }
13063                j = k;
13064            } else {
13065                j += 1;
13066            }
13067        }
13068        let mut i: usize = 0;
13069        let mut prev_in_run = false;
13070        while i < 8 {
13071            let in_run = best_len >= 2 && i >= best_start as usize && i < best_start as usize + best_len;
13072            if in_run {
13073                if i == best_start as usize {
13074                    *s.add(pos) = b':' as c_char; pos += 1;
13075                    *s.add(pos) = b':' as c_char; pos += 1;
13076                }
13077                i += 1;
13078                prev_in_run = true;
13079                continue;
13080            }
13081            if i > 0 && !prev_in_run {
13082                *s.add(pos) = b':' as c_char; pos += 1;
13083            }
13084            let (buf, len) = format_hex(words[i] as u64, false);
13085            for k in 0..len { *s.add(pos) = buf[k] as c_char; pos += 1; }
13086            i += 1;
13087            prev_in_run = false;
13088        }
13089        *s.add(pos) = 0;
13090        s
13091    } else {
13092        ERRNO!() = EAFNOSUPPORT;
13093        core::ptr::null_mut()
13094    }
13095}
13096
13097#[no_mangle]
13098pub unsafe extern "C" fn inet_aton(s: *const c_char, dest: *mut c_void) -> c_int {
13099    let a = dest as *mut u8;
13100    let mut p = s as *const u8;
13101    let mut vals = [0u64; 4];
13102    let mut i = 0usize;
13103    while i < 4 {
13104        if *p < b'0' || *p > b'9' { return 0; }
13105        let mut base = 10u32;
13106        if *p == b'0' {
13107            let c = *p.add(1);
13108            if c == b'x' || c == b'X' {
13109                base = 16;
13110                p = p.add(2);
13111                if !((*p >= b'0' && *p <= b'9')
13112                    || (*p >= b'a' && *p <= b'f')
13113                    || (*p >= b'A' && *p <= b'F')) {
13114                    return 0;
13115                }
13116            } else {
13117                base = 8;
13118            }
13119        }
13120        let mut v: u64 = 0;
13121        let start = p;
13122        loop {
13123            let c = *p;
13124            let d = if c >= b'0' && c <= b'9' {
13125                (c - b'0') as u64
13126            } else if base == 16 && c >= b'a' && c <= b'f' {
13127                (c - b'a' + 10) as u64
13128            } else if base == 16 && c >= b'A' && c <= b'F' {
13129                (c - b'A' + 10) as u64
13130            } else {
13131                break;
13132            };
13133            v = v * (base as u64) + d;
13134            p = p.add(1);
13135        }
13136        if p == start { return 0; }
13137        vals[i] = v;
13138        if *p == 0 {
13139            break;
13140        }
13141        if *p != b'.' || i == 3 { return 0; }
13142        p = p.add(1);
13143        i += 1;
13144    }
13145    if i == 4 { return 0; }
13146    if i < 1 { vals[1] = vals[0] & 0xffffff; vals[0] >>= 24; }
13147    if i < 2 { vals[2] = vals[1] & 0xffff; vals[1] >>= 16; }
13148    if i < 3 { vals[3] = vals[2] & 0xff; vals[2] >>= 8; }
13149    for j in 0..4 {
13150        if vals[j] > 255 { return 0; }
13151        *a.add(j) = vals[j] as u8;
13152    }
13153    1
13154}
13155
13156#[no_mangle]
13157pub unsafe extern "C" fn inet_addr(s: *const c_char) -> u32 {
13158    let mut a = [0u8; 4];
13159    if inet_aton(s, a.as_mut_ptr() as *mut c_void) == 1 {
13160        u32::from_ne_bytes(a)
13161    } else {
13162        !0u32 // INADDR_NONE
13163    }
13164}
13165
13166#[no_mangle]
13167pub unsafe extern "C" fn inet_ntoa(addr: u32) -> *mut c_char {
13168    static mut NTOA_BUF: [c_char; 16] = [0; 16];
13169    let b = addr.to_ne_bytes();
13170    let mut pos = 0;
13171    for i in 0..4 {
13172        if i > 0 { NTOA_BUF[pos] = b'.' as c_char; pos += 1; }
13173        let (buf, len) = format_u64(b[i] as u64);
13174        for j in 0..len { NTOA_BUF[pos] = buf[j] as c_char; pos += 1; }
13175    }
13176    NTOA_BUF[pos] = 0;
13177    core::ptr::addr_of_mut!(NTOA_BUF).cast::<c_char>()
13178}
13179
13180// inet_network/inet_makeaddr/inet_lnaof/inet_netof - simple implementations
13181#[no_mangle]
13182pub unsafe extern "C" fn inet_network(s: *const c_char) -> u32 {
13183    inet_addr(s).to_be()
13184}
13185
13186#[no_mangle]
13187pub extern "C" fn inet_makeaddr(net: c_int, host: c_int) -> u32 {
13188    // musl's inet_legacy: class A when the network number fits in 8 bits,
13189    // class B when it fits in 16, otherwise the top 24 bits.
13190    let n = net as u32;
13191    let mut h = host as u32;
13192    if n < 256 {
13193        h |= n << 24;
13194    } else if n < 65536 {
13195        h |= n << 16;
13196    } else {
13197        h |= n << 8;
13198    }
13199    h
13200}
13201
13202#[no_mangle]
13203pub extern "C" fn inet_lnaof(addr: u32) -> c_int {
13204    // s_addr already carries the network-order numeric value, exactly like
13205    // musl's inet_legacy.c; do not byte-swap it again.
13206    let h = addr;
13207    if h < 0x80000000 { (h & 0x00ffffff) as c_int }
13208    else if h < 0xc0000000 { (h & 0x0000ffff) as c_int }
13209    else { (h & 0x000000ff) as c_int }
13210}
13211
13212#[no_mangle]
13213pub extern "C" fn inet_netof(addr: u32) -> c_int {
13214    let h = addr;
13215    if h < 0x80000000 { (h >> 24) as c_int }
13216    else if h < 0xc0000000 { (h >> 16) as c_int }
13217    else { (h >> 8) as c_int }
13218}
13219
13220// ============================================================
13221// stdlib: strtod / strtof / strtold
13222// ============================================================
13223
13224// Correctly-rounded float parser.
13225// Decimal: collects digits into buffer, uses core::str::FromStr.
13226// Hex: u128 integer arithmetic with round-to-nearest-even.
13227// is_f32: true for strtof (f32::from_str), false for strtod/strtold (f64::from_str).
13228unsafe fn parse_float(s: *const u8, endptr: *mut *mut u8, is_f32: bool) -> f64 {
13229    let mut p = s;
13230    // skip whitespace
13231    while *p == b' ' || *p == b'\t' || *p == b'\n' || *p == b'\r' { p = p.add(1); }
13232    let mut neg = false;
13233    if *p == b'-' { neg = true; p = p.add(1); }
13234    else if *p == b'+' { p = p.add(1); }
13235
13236    // inf
13237    if (*p | 0x20) == b'i'
13238        && (*p.add(1) | 0x20) == b'n'
13239        && (*p.add(2) | 0x20) == b'f'
13240    {
13241        p = p.add(3);
13242        // optionally consume "inity"
13243        if (*p | 0x20) == b'i'
13244            && (*p.add(1) | 0x20) == b't'
13245            && (*p.add(2) | 0x20) == b'y'
13246        {
13247            p = p.add(3);
13248        }
13249        if !endptr.is_null() { *endptr = p as *mut u8; }
13250        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13251    }
13252    // nan
13253    if (*p | 0x20) == b'n'
13254        && (*p.add(1) | 0x20) == b'a'
13255        && (*p.add(2) | 0x20) == b'n'
13256    {
13257        p = p.add(3);
13258        // optionally consume (n-char-sequence)
13259        if *p == b'(' {
13260            p = p.add(1);
13261            while *p != 0 && *p != b')' { p = p.add(1); }
13262            if *p == b')' { p = p.add(1); }
13263        }
13264        if !endptr.is_null() { *endptr = p as *mut u8; }
13265        return if neg { -f64::NAN } else { f64::NAN };
13266    }
13267
13268    // hex float
13269    if *p == b'0' && (*p.add(1) == b'x' || *p.add(1) == b'X') {
13270        p = p.add(2);
13271        let mut mant: u128 = 0;
13272        let mut frac_hex: i64 = 0;
13273        let mut dropped: i64 = 0;
13274        let mut tail_nonzero = false;
13275        let mut found = false;
13276        let mut in_frac = false;
13277
13278        loop {
13279            if let Some(d) = hex_val(*p) {
13280                if mant <= u128::MAX / 16 {
13281                    mant = mant * 16 + d as u128;
13282                } else {
13283                    // Too many significant digits for u128: keep the leading
13284                    // ones and remember that the dropped tail is nonzero.
13285                    dropped += 1;
13286                    if d != 0 { tail_nonzero = true; }
13287                }
13288                if in_frac { frac_hex += 1; }
13289                p = p.add(1);
13290                found = true;
13291            } else if *p == b'.' && !in_frac {
13292                in_frac = true;
13293                p = p.add(1);
13294            } else {
13295                break;
13296            }
13297        }
13298
13299        if !found {
13300            if !endptr.is_null() { *endptr = s as *mut u8; }
13301            return 0.0;
13302        }
13303
13304        // binary exponent p[+-]N
13305        let mut bin_exp: i32 = 0;
13306        if *p == b'p' || *p == b'P' {
13307            p = p.add(1);
13308            let mut exp_neg = false;
13309            if *p == b'-' { exp_neg = true; p = p.add(1); }
13310            else if *p == b'+' { p = p.add(1); }
13311            while *p >= b'0' && *p <= b'9' {
13312                if bin_exp < 100000 {
13313                    bin_exp = bin_exp * 10 + (*p - b'0') as i32;
13314                }
13315                p = p.add(1);
13316            }
13317            if exp_neg { bin_exp = -bin_exp; }
13318        }
13319
13320        if !endptr.is_null() { *endptr = p as *mut u8; }
13321        if mant == 0 { return if neg { -0.0 } else { 0.0 }; }
13322
13323        // The exponent must account for every fractional digit, including
13324        // the ones dropped from `mant`.
13325        let total_exp = bin_exp as i64 - 4 * (frac_hex - dropped);
13326        let r = hex_mant_to_f64(mant, total_exp, neg, tail_nonzero);
13327        note_float_range(r, true, is_f32);
13328        return r;
13329    }
13330
13331    // decimal: collect the significant digits into a bounded buffer and let
13332    // Rust's parser do the correctly-rounded conversion. Keeping only the
13333    // leading digits (and folding the rest into the exponent) keeps the stack
13334    // footprint small without changing the result.
13335    const MAX_SIG_DIGITS: usize = 768;
13336    let mut buf = [0u8; MAX_SIG_DIGITS + 32];
13337    let mut n = 0usize;
13338    let mut found_digit = false;
13339    let mut nonzero = false;
13340    let mut frac_kept: i64 = 0;
13341    let mut frac_lead_zeros: i64 = 0;
13342    let mut int_dropped: i64 = 0;
13343
13344    while *p >= b'0' && *p <= b'9' {
13345        if *p != b'0' { nonzero = true; }
13346        if nonzero {
13347            if n < MAX_SIG_DIGITS {
13348                buf[n] = *p;
13349                n += 1;
13350            } else {
13351                int_dropped += 1;
13352            }
13353        }
13354        p = p.add(1);
13355        found_digit = true;
13356    }
13357    if *p == b'.' {
13358        p = p.add(1);
13359        while *p >= b'0' && *p <= b'9' {
13360            if *p != b'0' { nonzero = true; }
13361            if !nonzero {
13362                // Leading fractional zeros still shift the exponent.
13363                frac_lead_zeros += 1;
13364            } else if n < MAX_SIG_DIGITS {
13365                buf[n] = *p;
13366                n += 1;
13367                frac_kept += 1;
13368            }
13369            p = p.add(1);
13370            found_digit = true;
13371        }
13372    }
13373    if !found_digit {
13374        ERRNO!() = EINVAL;
13375        if !endptr.is_null() { *endptr = s as *mut u8; }
13376        return 0.0;
13377    }
13378    let mut exp10: i64 = int_dropped - frac_kept - frac_lead_zeros;
13379    if *p == b'e' || *p == b'E' {
13380        let mut q = p.add(1);
13381        let mut exp_neg = false;
13382        if *q == b'-' { exp_neg = true; q = q.add(1); }
13383        else if *q == b'+' { q = q.add(1); }
13384        // Without at least one exponent digit the 'e' is not part of the
13385        // number; leave the end pointer on it.
13386        if *q >= b'0' && *q <= b'9' {
13387            let mut e: i64 = 0;
13388            while *q >= b'0' && *q <= b'9' {
13389                e = e.saturating_mul(10).saturating_add((*q - b'0') as i64);
13390                if e > 1_000_000 { e = 1_000_000; }
13391                q = q.add(1);
13392            }
13393            exp10 += if exp_neg { -e } else { e };
13394            p = q;
13395        }
13396    }
13397    if !endptr.is_null() { *endptr = p as *mut u8; }
13398    if n == 0 {
13399        // Every digit was zero.
13400        return if neg { -0.0 } else { 0.0 };
13401    }
13402
13403    // Represent the kept digits as an integer times a power of ten.
13404    buf[n] = b'e';
13405    n += 1;
13406    let mut tmp = [0u8; 24];
13407    let mut tn = 0usize;
13408    let e_abs = exp10.unsigned_abs();
13409    if e_abs == 0 {
13410        tmp[0] = b'0';
13411        tn = 1;
13412    } else {
13413        let mut v = e_abs;
13414        while v > 0 && tn < tmp.len() {
13415            tmp[tn] = b'0' + (v % 10) as u8;
13416            v /= 10;
13417            tn += 1;
13418        }
13419    }
13420    if exp10 < 0 { buf[n] = b'-'; n += 1; }
13421    for k in (0..tn).rev() {
13422        buf[n] = tmp[k];
13423        n += 1;
13424    }
13425
13426    let s_str = core::str::from_utf8_unchecked(
13427        core::slice::from_raw_parts(buf.as_ptr(), n),
13428    );
13429    if is_f32 {
13430        match <f32 as core::str::FromStr>::from_str(s_str) {
13431            Ok(v) => {
13432                let r = if neg { -(v as f64) } else { v as f64 };
13433                note_float_range(r, nonzero, true);
13434                r
13435            }
13436            Err(_) => { if !endptr.is_null() { *endptr = s as *mut u8; } 0.0 }
13437        }
13438    } else {
13439        match <f64 as core::str::FromStr>::from_str(s_str) {
13440            Ok(v) => {
13441                let r = if neg { -v } else { v };
13442                note_float_range(r, nonzero, false);
13443                r
13444            }
13445            Err(_) => { if !endptr.is_null() { *endptr = s as *mut u8; } 0.0 }
13446        }
13447    }
13448}
13449
13450/// Set ERANGE for overflow and underflow, like musl's floatscan.
13451unsafe fn note_float_range(r: f64, nonzero: bool, is_f32: bool) {
13452    let (infinite, zero, subnormal) = if is_f32 {
13453        let v = r as f32;
13454        (v.is_infinite(), v == 0.0, v != 0.0 && v.abs() < f32::MIN_POSITIVE)
13455    } else {
13456        (r.is_infinite(), r == 0.0, r != 0.0 && r.abs() < f64::MIN_POSITIVE)
13457    };
13458    if infinite || subnormal || (zero && nonzero) {
13459        ERRNO!() = ERANGE;
13460    }
13461}
13462
13463// Convert hex mantissa integer to f64 with correct rounding.
13464// mant: integer from parsed hex digits. total_exp: bin_exp - 4 * frac_hex_digits.
13465// tail_nonzero records dropped digits below `mant` for the sticky bit.
13466// Value = mant * 2^total_exp.
13467fn hex_mant_to_f64(mant: u128, total_exp: i64, neg: bool, tail_nonzero: bool) -> f64 {
13468    if mant == 0 { return if neg { -0.0 } else { 0.0 }; }
13469
13470    let msb = (127 - mant.leading_zeros()) as i64;
13471    let unbiased_exp = msb + total_exp;
13472    let biased_exp = unbiased_exp + 1023;
13473
13474    // Overflow → infinity
13475    if biased_exp >= 2047 {
13476        return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13477    }
13478
13479    // Subnormal or underflow
13480    if biased_exp <= 0 {
13481        // subnormal: biased_exp=0, effective exponent=-1022
13482        // mantissa = round(mant * 2^(total_exp + 1074))
13483        let shift = total_exp + 1074;
13484        if shift < 0 {
13485            return if neg { -0.0 } else { 0.0 };
13486        }
13487        if shift > 128 {
13488            return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13489        }
13490        let shifted = mant << (shift as u32);
13491        let mantissa52 = (shifted as u64) & 0x000FFFFFFFFFFFFF;
13492        let guard = ((shifted >> 52) & 1) != 0;
13493        let sticky = (shifted >> 53) != 0 || tail_nonzero;
13494        let mut result = mantissa52;
13495        if guard && (sticky || (result & 1) != 0) {
13496            result += 1;
13497            if result > 0x000FFFFFFFFFFFFF {
13498                // carry → smallest normal
13499                return if neg { -f64::from_bits(1u64 << 52) } else { f64::from_bits(1u64 << 52) };
13500            }
13501        }
13502        return if neg { -f64::from_bits(result) } else { f64::from_bits(result) };
13503    }
13504
13505    // Normal: biased_exp in [1, 2046]
13506    let shift = msb - 52;
13507
13508    if shift <= 0 {
13509        // fewer than 53 bits, no rounding needed
13510        let mantissa = ((mant as u64) & ((1u64 << msb as u32) - 1)) << ((-shift) as u32);
13511        let bits = ((biased_exp as u64) << 52) | mantissa;
13512        return if neg { -f64::from_bits(bits) } else { f64::from_bits(bits) };
13513    }
13514
13515    // shift > 0: round to nearest even
13516    let mantissa = ((mant >> shift as u32) as u64) & 0x000FFFFFFFFFFFFF;
13517    let guard = ((mant >> (shift as u32 - 1)) & 1) != 0;
13518    let sticky = (if shift > 1 {
13519        (mant & ((1u128 << (shift as u32 - 1)) - 1)) != 0
13520    } else { false }) || tail_nonzero;
13521
13522    let mut result_mant = mantissa;
13523    let mut result_exp = biased_exp;
13524    if guard && (sticky || (result_mant & 1) != 0) {
13525        result_mant += 1;
13526        if result_mant > 0x000FFFFFFFFFFFFF {
13527            result_mant = 0;
13528            result_exp += 1;
13529            if result_exp >= 2047 {
13530                return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
13531            }
13532        }
13533    }
13534
13535    let bits = ((result_exp as u64) << 52) | result_mant;
13536    if neg { -f64::from_bits(bits) } else { f64::from_bits(bits) }
13537}
13538
13539unsafe fn hex_val(c: u8) -> Option<u8> {
13540    if c >= b'0' && c <= b'9' { Some(c - b'0') }
13541    else if c >= b'a' && c <= b'f' { Some(c - b'a' + 10) }
13542    else if c >= b'A' && c <= b'F' { Some(c - b'A' + 10) }
13543    else { None }
13544}
13545
13546#[no_mangle]
13547pub unsafe extern "C" fn strtod(s: *const c_char, endptr: *mut *mut c_char) -> f64 {
13548    let mut end: *mut u8 = s as *mut u8;
13549    let r = parse_float(s as *const u8, &mut end, false);
13550    if !endptr.is_null() { *endptr = end as *mut c_char; }
13551    r
13552}
13553
13554#[no_mangle]
13555pub unsafe extern "C" fn strtof(s: *const c_char, endptr: *mut *mut c_char) -> f32 {
13556    let mut end: *mut u8 = s as *mut u8;
13557    let r = parse_float(s as *const u8, &mut end, true);
13558    if !endptr.is_null() { *endptr = end as *mut c_char; }
13559    r as f32
13560}
13561
13562#[no_mangle]
13563#[cfg(target_arch = "x86_64")]
13564pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f64 {
13565    strtod(s, endptr)
13566}
13567
13568#[no_mangle]
13569#[cfg(target_arch = "aarch64")]
13570pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f128 {
13571    f64_to_f128(strtod(s, endptr))
13572}
13573
13574#[no_mangle]
13575#[cfg(target_arch = "riscv64")]
13576pub unsafe extern "C" fn strtold(s: *const c_char, endptr: *mut *mut c_char) -> f128 {
13577    f64_to_f128(strtod(s, endptr))
13578}
13579
13580#[no_mangle]
13581pub unsafe extern "C" fn atof(s: *const c_char) -> f64 {
13582    strtod(s, core::ptr::null_mut())
13583}
13584
13585// ============================================================
13586// stdio: open_memstream / fmemopen
13587// ============================================================
13588
13589#[repr(C)]
13590struct MsCookie {
13591    bufp: *mut *mut c_char,
13592    sizep: *mut usize,
13593    pos: usize,
13594    len: usize,
13595    buf: *mut u8,
13596    space: usize,
13597}
13598
13599#[repr(C)]
13600struct MfCookie {
13601    pos: usize,
13602    len: usize,
13603    size: usize,
13604    buf: *mut u8,
13605    mode: c_char,
13606}
13607
13608unsafe extern "C" fn ms_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
13609    let c = (*f).cookie as *mut MsCookie;
13610    if whence < 0 || whence > 2 { ERRNO!() = EINVAL; return -1; }
13611    let base: i64 = match whence {
13612        0 => 0,
13613        1 => (*c).pos as i64,
13614        2 => (*c).len as i64,
13615        _ => { ERRNO!() = EINVAL; return -1; }
13616    };
13617    if off < -base || off > isize::MAX as i64 - base { ERRNO!() = EINVAL; return -1; }
13618    (*c).pos = (base + off) as usize;
13619    (*c).pos as i64
13620}
13621
13622unsafe extern "C" fn ms_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
13623    let c = (*f).cookie as *mut MsCookie;
13624    let buffered = (*f).wpos as usize - (*f).wbase as usize;
13625    if buffered > 0 {
13626        (*f).wpos = (*f).wbase;
13627        if ms_write(f, (*f).wbase, buffered) < buffered { return 0; }
13628    }
13629    if len == 0 { return 0; }
13630    if (*c).pos + len >= (*c).space {
13631        let new_space = 2 * (*c).space + 1 | (*c).pos + len + 1;
13632        let newbuf = realloc((*c).buf as *mut c_void, new_space) as *mut u8;
13633        if newbuf.is_null() { return 0; }
13634        *(*c).bufp = newbuf as *mut c_char;
13635        core::ptr::write_bytes(newbuf.add((*c).space), 0, new_space - (*c).space);
13636        (*c).buf = newbuf;
13637        (*c).space = new_space;
13638    }
13639    core::ptr::copy_nonoverlapping(buf, (*c).buf.add((*c).pos), len);
13640    (*c).pos += len;
13641    if (*c).pos >= (*c).len { (*c).len = (*c).pos; }
13642    *(*c).sizep = (*c).pos;
13643    len
13644}
13645
13646unsafe extern "C" fn ms_close(f: *mut FILE) -> c_int {
13647    // The byte buffer belongs to the caller; free only the cookie.
13648    if !f.is_null() && !(*f).cookie.is_null() {
13649        free((*f).cookie);
13650        (*f).cookie = core::ptr::null_mut();
13651    }
13652    0
13653}
13654
13655#[no_mangle]
13656pub unsafe extern "C" fn open_memstream(bufp: *mut *mut c_char, sizep: *mut usize) -> *mut FILE {
13657    if bufp.is_null() || sizep.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
13658    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
13659    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13660    let buf_area = buf_ptr(f);
13661    init_file(f, -1, b"w\0".as_ptr() as *const c_char, Some(ms_close), buf_area, BUFSIZ);
13662    (*f).flags = F_NORD | F_SVB;
13663    (*f).lbf = -1;
13664    let c = calloc(1, core::mem::size_of::<MsCookie>()) as *mut MsCookie;
13665    if c.is_null() { free(f as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13666    (*c).bufp = bufp;
13667    (*c).sizep = sizep;
13668    (*c).pos = 0;
13669    (*c).len = 0;
13670    let initial = crate::malloc(1) as *mut u8;
13671    if initial.is_null() {
13672        crate::free(c as *mut c_void);
13673        crate::free(f as *mut c_void);
13674        ERRNO!() = ENOMEM;
13675        return core::ptr::null_mut();
13676    }
13677    *initial = 0;
13678    (*c).buf = initial;
13679    (*c).space = 1;
13680    (*f).cookie = c as *mut c_void;
13681    (*f).write_fn = Some(ms_write);
13682    (*f).seek_fn = Some(ms_seek);
13683    *bufp = initial as *mut c_char;
13684    *sizep = 0;
13685    f
13686}
13687
13688unsafe extern "C" fn mseek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
13689    let c = (*f).cookie as *mut MfCookie;
13690    if whence < 0 || whence > 2 { ERRNO!() = EINVAL; return -1; }
13691    let base: i64 = match whence {
13692        0 => 0,
13693        1 => (*c).pos as i64,
13694        2 => (*c).len as i64,
13695        _ => { ERRNO!() = EINVAL; return -1; }
13696    };
13697    if off < -base || off > (*c).size as i64 - base { ERRNO!() = EINVAL; return -1; }
13698    (*c).pos = (base + off) as usize;
13699    (*c).pos as i64
13700}
13701
13702unsafe extern "C" fn mread(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
13703    let c = (*f).cookie as *mut MfCookie;
13704    let mut rem = if (*c).pos <= (*c).len { (*c).len - (*c).pos } else { 0 };
13705    let mut l = len;
13706    if l > rem {
13707        l = rem;
13708        (*f).flags |= F_EOF;
13709    }
13710    core::ptr::copy_nonoverlapping((*c).buf.add((*c).pos), buf, l);
13711    (*c).pos += l;
13712    rem -= l;
13713    if rem > (*f).buf_size { rem = (*f).buf_size; }
13714    (*f).rpos = (*f).buf;
13715    (*f).rend = (*f).buf.add(rem);
13716    core::ptr::copy_nonoverlapping((*c).buf.add((*c).pos), (*f).rpos, rem);
13717    (*c).pos += rem;
13718    l
13719}
13720
13721unsafe extern "C" fn mwrite(f: *mut FILE, buf: *const u8, len: usize) -> usize {
13722    let c = (*f).cookie as *mut MfCookie;
13723    let buffered = (*f).wpos as usize - (*f).wbase as usize;
13724    if buffered > 0 {
13725        (*f).wpos = (*f).wbase;
13726        if mwrite(f, (*f).wbase, buffered) < buffered { return 0; }
13727    }
13728    if len == 0 { return 0; }
13729    if (*c).mode == b'a' as c_char { (*c).pos = (*c).len; }
13730    let rem = (*c).size - (*c).pos;
13731    let mut l = len;
13732    if l > rem { l = rem; }
13733    core::ptr::copy_nonoverlapping(buf, (*c).buf.add((*c).pos), l);
13734    (*c).pos += l;
13735    if (*c).pos > (*c).len {
13736        (*c).len = (*c).pos;
13737        if (*c).len < (*c).size {
13738            *(*c).buf.add((*c).len) = 0;
13739        } else if ((*f).flags & F_NORD) != 0 && (*c).size > 0 {
13740            *(*c).buf.add((*c).size - 1) = 0;
13741        }
13742    }
13743    l
13744}
13745
13746unsafe extern "C" fn mclose(_f: *mut FILE) -> c_int {
13747    0
13748}
13749
13750#[no_mangle]
13751pub unsafe extern "C" fn fmemopen(buf: *mut c_void, size: usize, mode: *const c_char) -> *mut FILE {
13752    if mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
13753    let m = *mode;
13754    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
13755        ERRNO!() = EINVAL; return core::ptr::null_mut();
13756    }
13757    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
13758    let need_alloc = buf.is_null();
13759    let alloc_size = core::mem::size_of::<FILE>() + UNGET + BUFSIZ + if need_alloc { size } else { 0 };
13760    let f = calloc(1, alloc_size) as *mut FILE;
13761    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13762    let buf_area = buf_ptr(f);
13763    init_file(f, -1, mode, Some(mclose), buf_area, BUFSIZ);
13764    (*f).flags |= F_SVB;
13765    let actual_buf: *mut u8 = if need_alloc {
13766        (f as *mut u8).add(alloc_size - size)
13767    } else {
13768        buf as *mut u8
13769    };
13770    if need_alloc { core::ptr::write_bytes(actual_buf, 0, size); }
13771    let c = calloc(1, core::mem::size_of::<MfCookie>()) as *mut MfCookie;
13772    if c.is_null() { free(f as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
13773    (*c).buf = actual_buf;
13774    (*c).size = size;
13775    (*c).mode = m;
13776    (*f).cookie = c as *mut c_void;
13777    (*f).read_fn = Some(mread);
13778    (*f).write_fn = Some(mwrite);
13779    (*f).seek_fn = Some(mseek);
13780    if !has_plus { (*f).flags = if m == b'r' as c_char { F_NOWR } else { F_NORD }; }
13781    if m == b'r' as c_char {
13782        (*c).len = size;
13783    } else if m == b'a' as c_char {
13784        (*c).len = strnlen(actual_buf, size);
13785        (*c).pos = (*c).len;
13786    } else if has_plus {
13787        *actual_buf = 0;
13788    }
13789    f
13790}
13791
13792// ============================================================
13793// Stat (for ftok)
13794// ============================================================
13795
13796#[repr(C)]
13797struct kernel_stat64 {
13798    st_dev: u64,
13799    st_ino: u64,
13800    st_nlink: u64,
13801    st_mode: u32,
13802    st_uid: u32,
13803    st_gid: u32,
13804    __pad0: c_int,
13805    st_rdev: u64,
13806    st_size: i64,
13807    st_blksize: i64,
13808    st_blocks: i64,
13809    st_atime: i64,
13810    st_atime_nsec: i64,
13811    st_mtime: i64,
13812    st_mtime_nsec: i64,
13813    st_ctime: i64,
13814    st_ctime_nsec: i64,
13815    __unused: [i64; 3],
13816}
13817
13818// sys_stat = 4 on x86_64
13819#[inline]
13820unsafe fn sys_stat(path: *const u8, statbuf: *mut kernel_stat64) -> i64 {
13821    <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, statbuf as i64, 0)
13822}
13823
13824// ============================================================
13825// Search: hcreate/hdestroy/hsearch (hash table)
13826// ============================================================
13827
13828const HSEARCH_MINSIZE: usize = 8;
13829
13830#[repr(C)]
13831#[derive(Copy, Clone)]
13832pub struct HSearchEntry {
13833    key: *mut c_char,
13834    data: *mut c_void,
13835}
13836
13837#[repr(C)]
13838struct HTab {
13839    entries: *mut HSearchEntry,
13840    mask: usize,
13841    used: usize,
13842}
13843
13844#[repr(C)]
13845pub struct HSearchData {
13846    tab: *mut HTab,
13847    __unused1: c_uint,
13848    __unused2: c_uint,
13849}
13850
13851// Single static hash table for the non-_r variants.
13852static mut HTAB_DATA: HSearchData = HSearchData {
13853    tab: core::ptr::null_mut(),
13854    __unused1: 0,
13855    __unused2: 0,
13856};
13857
13858unsafe fn keyhash(k: *const c_char) -> usize {
13859    let mut h: usize = 0;
13860    let mut p = k;
13861    while *p != 0 {
13862        h = h.wrapping_mul(31).wrapping_add(*p as usize);
13863        p = p.add(1);
13864    }
13865    h
13866}
13867
13868unsafe fn htab_lookup(key: *const c_char, hash: usize, htab: *mut HSearchData) -> *mut HSearchEntry {
13869    let tab = (*htab).tab;
13870    let mask = (*tab).mask;
13871    let entries = (*tab).entries;
13872    let mut i = hash;
13873    let mut j: usize = 1;
13874    loop {
13875        let e = entries.add(i & mask);
13876        if (*e).key.is_null() || strcmp((*e).key as *const u8, key as *const u8) == 0 {
13877            return e;
13878        }
13879        i = i.wrapping_add(j);
13880        j += 1;
13881    }
13882}
13883
13884unsafe fn htab_resize(nel: usize, htab: *mut HSearchData) -> c_int {
13885    let tab = (*htab).tab;
13886    let old_entries = (*tab).entries;
13887    let old_size = (*tab).mask + 1;
13888
13889    let mut newsize: usize = HSEARCH_MINSIZE;
13890    while newsize < nel {
13891        let Some(next) = newsize.checked_mul(2) else {
13892            ERRNO!() = ENOMEM;
13893            return 0;
13894        };
13895        newsize = next;
13896    }
13897
13898    let new_entries = calloc(newsize, core::mem::size_of::<HSearchEntry>()) as *mut HSearchEntry;
13899    if new_entries.is_null() {
13900        ERRNO!() = ENOMEM;
13901        return 0;
13902    }
13903    (*tab).entries = new_entries;
13904    (*tab).mask = newsize - 1;
13905
13906    if !old_entries.is_null() {
13907        for idx in 0..old_size {
13908            let old_e = old_entries.add(idx);
13909            if !(*old_e).key.is_null() {
13910                let h = keyhash((*old_e).key);
13911                let mut i = h;
13912                let mut j: usize = 1;
13913                loop {
13914                    let e = new_entries.add(i & (*tab).mask);
13915                    if (*e).key.is_null() {
13916                        *e = *old_e;
13917                        break;
13918                    }
13919                    i = i.wrapping_add(j);
13920                    j += 1;
13921                }
13922            }
13923        }
13924        free(old_entries as *mut c_void);
13925    }
13926    1
13927}
13928
13929unsafe fn hcreate_r_impl(nel: usize, htab: *mut HSearchData) -> c_int {
13930    if nel == 0 || nel > (1usize << 30) {
13931        ERRNO!() = ENOMEM;
13932        return 0;
13933    }
13934    (*htab).tab = calloc(1, core::mem::size_of::<HTab>()) as *mut HTab;
13935    if (*htab).tab.is_null() {
13936        ERRNO!() = ENOMEM;
13937        return 0;
13938    }
13939    if htab_resize(nel, htab) == 0 {
13940        free((*htab).tab as *mut c_void);
13941        (*htab).tab = core::ptr::null_mut();
13942        return 0;
13943    }
13944    1
13945}
13946
13947unsafe fn hdestroy_r_impl(htab: *mut HSearchData) {
13948    if !(*htab).tab.is_null() {
13949        if !(*(*htab).tab).entries.is_null() {
13950            free((*(*htab).tab).entries as *mut c_void);
13951        }
13952        free((*htab).tab as *mut c_void);
13953        (*htab).tab = core::ptr::null_mut();
13954    }
13955}
13956
13957unsafe fn hsearch_r_impl(item: HSearchEntry, action: c_int, retval: *mut *mut HSearchEntry, htab: *mut HSearchData) -> c_int {
13958    let hash = keyhash(item.key);
13959    let e = htab_lookup(item.key, hash, htab);
13960
13961    if !(*e).key.is_null() {
13962        *retval = e;
13963        return 1;
13964    }
13965    if action == 0 { // FIND
13966        *retval = core::ptr::null_mut();
13967        return 0;
13968    }
13969    // ENTER
13970    let item_key = item.key;
13971    *e = item;
13972    (*(*htab).tab).used += 1;
13973    if (*(*htab).tab).used > (*(*htab).tab).mask - (*(*htab).tab).mask / 4 {
13974        if htab_resize(2 * (*(*htab).tab).used, htab) == 0 {
13975            (*(*htab).tab).used -= 1;
13976            (*e).key = core::ptr::null_mut();
13977            *retval = core::ptr::null_mut();
13978            return 0;
13979        }
13980        let e2 = htab_lookup(item_key, hash, htab);
13981        *retval = e2;
13982        return 1;
13983    }
13984    *retval = e;
13985    1
13986}
13987
13988#[no_mangle]
13989pub unsafe extern "C" fn hcreate(nel: usize) -> c_int {
13990    hcreate_r_impl(nel, core::ptr::addr_of_mut!(HTAB_DATA))
13991}
13992
13993#[no_mangle]
13994pub unsafe extern "C" fn hdestroy() {
13995    hdestroy_r_impl(core::ptr::addr_of_mut!(HTAB_DATA));
13996}
13997
13998#[no_mangle]
13999pub unsafe extern "C" fn hsearch(item: HSearchEntry, action: c_int) -> *mut HSearchEntry {
14000    let mut e: *mut HSearchEntry = core::ptr::null_mut();
14001    hsearch_r_impl(item, action, &mut e, core::ptr::addr_of_mut!(HTAB_DATA));
14002    e
14003}
14004
14005#[no_mangle]
14006pub unsafe extern "C" fn hcreate_r(nel: usize, htab: *mut HSearchData) -> c_int {
14007    hcreate_r_impl(nel, htab)
14008}
14009
14010#[no_mangle]
14011pub unsafe extern "C" fn hdestroy_r(htab: *mut HSearchData) {
14012    hdestroy_r_impl(htab);
14013}
14014
14015#[no_mangle]
14016pub unsafe extern "C" fn hsearch_r(item: HSearchEntry, action: c_int, retval: *mut *mut HSearchEntry, htab: *mut HSearchData) -> c_int {
14017    hsearch_r_impl(item, action, retval, htab)
14018}
14019
14020// ============================================================
14021// Search: insque / remque
14022// ============================================================
14023
14024#[repr(C)]
14025struct QueNode {
14026    next: *mut QueNode,
14027    prev: *mut QueNode,
14028}
14029
14030#[no_mangle]
14031pub unsafe extern "C" fn insque(element: *mut c_void, pred: *mut c_void) {
14032    let e = element as *mut QueNode;
14033    let p = pred as *mut QueNode;
14034    if p.is_null() {
14035        (*e).next = core::ptr::null_mut();
14036        (*e).prev = core::ptr::null_mut();
14037        return;
14038    }
14039    (*e).next = (*p).next;
14040    (*e).prev = p;
14041    (*p).next = e;
14042    if !(*e).next.is_null() {
14043        (*(*e).next).prev = e;
14044    }
14045}
14046
14047#[no_mangle]
14048pub unsafe extern "C" fn remque(element: *mut c_void) {
14049    let e = element as *mut QueNode;
14050    if !(*e).next.is_null() {
14051        (*(*e).next).prev = (*e).prev;
14052    }
14053    if !(*e).prev.is_null() {
14054        (*(*e).prev).next = (*e).next;
14055    }
14056}
14057
14058// ============================================================
14059// Search: lsearch / lfind
14060// ============================================================
14061
14062#[no_mangle]
14063pub unsafe extern "C" fn lsearch(
14064    key: *const c_void,
14065    base: *mut c_void,
14066    nelp: *mut usize,
14067    width: usize,
14068    compar: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
14069) -> *mut c_void {
14070    let n = *nelp;
14071    let p = base as *mut u8;
14072    for i in 0..n {
14073        let elem = p.add(i * width);
14074        if compar.unwrap()(key, elem as *const c_void) == 0 {
14075            return elem as *mut c_void;
14076        }
14077    }
14078    let dest = p.add(n * width);
14079    memcpy(dest as *mut c_void, key as *const c_void, width);
14080    *nelp = n + 1;
14081    dest as *mut c_void
14082}
14083
14084#[no_mangle]
14085pub unsafe extern "C" fn lfind(
14086    key: *const c_void,
14087    base: *const c_void,
14088    nelp: *mut usize,
14089    width: usize,
14090    compar: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
14091) -> *mut c_void {
14092    let n = *nelp;
14093    let p = base as *const u8;
14094    for i in 0..n {
14095        let elem = p.add(i * width);
14096        if compar.unwrap()(key, elem as *const c_void) == 0 {
14097            return elem as *mut c_void;
14098        }
14099    }
14100    core::ptr::null_mut()
14101}
14102
14103// ============================================================
14104// Search: tsearch / tfind / tdelete / twalk / tdestroy (BST, no balancing)
14105// ============================================================
14106
14107// Unbalanced binary tree, unlike musl's AVL tree: O(n) worst case.
14108#[repr(C)]
14109pub struct TreeNode {
14110    key: *const c_void,
14111    left: *mut TreeNode,
14112    right: *mut TreeNode,
14113}
14114
14115type ComparFn = Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>;
14116
14117unsafe fn bst_new(key: *const c_void) -> *mut TreeNode {
14118    let n = calloc(1, core::mem::size_of::<TreeNode>()) as *mut TreeNode;
14119    if !n.is_null() {
14120        (*n).key = key;
14121        (*n).left = core::ptr::null_mut();
14122        (*n).right = core::ptr::null_mut();
14123    }
14124    n
14125}
14126
14127#[no_mangle]
14128pub unsafe extern "C" fn tsearch(
14129    key: *const c_void,
14130    rootp: *mut *mut TreeNode,
14131    compar: ComparFn,
14132) -> *mut c_void {
14133    if rootp.is_null() {
14134        return core::ptr::null_mut();
14135    }
14136    let mut pp = rootp;
14137    loop {
14138        let n = *pp;
14139        if n.is_null() {
14140            let r = bst_new(key);
14141            if r.is_null() {
14142                return core::ptr::null_mut();
14143            }
14144            *pp = r;
14145            return r as *mut c_void;
14146        }
14147        let c = compar.unwrap()(key, (*n).key);
14148        if c == 0 {
14149            return n as *mut c_void;
14150        }
14151        if c < 0 {
14152            pp = &mut (*n).left;
14153        } else {
14154            pp = &mut (*n).right;
14155        }
14156    }
14157}
14158
14159#[no_mangle]
14160pub unsafe extern "C" fn tfind(
14161    key: *const c_void,
14162    rootp: *const *mut TreeNode,
14163    compar: ComparFn,
14164) -> *mut c_void {
14165    if rootp.is_null() {
14166        return core::ptr::null_mut();
14167    }
14168    let mut n = *rootp;
14169    loop {
14170        if n.is_null() {
14171            return core::ptr::null_mut();
14172        }
14173        let c = compar.unwrap()(key, (*n).key);
14174        if c == 0 {
14175            return n as *mut c_void;
14176        }
14177        if c < 0 {
14178            n = (*n).left;
14179        } else {
14180            n = (*n).right;
14181        }
14182    }
14183}
14184
14185#[no_mangle]
14186pub unsafe extern "C" fn tdelete(
14187    key: *const c_void,
14188    rootp: *mut *mut TreeNode,
14189    compar: ComparFn,
14190) -> *mut c_void {
14191    if rootp.is_null() {
14192        return core::ptr::null_mut();
14193    }
14194    let mut pp = rootp;
14195    let mut parent: *mut c_void = core::ptr::null_mut();
14196    loop {
14197        let n = *pp;
14198        if n.is_null() {
14199            return core::ptr::null_mut();
14200        }
14201        let c = compar.unwrap()(key, (*n).key);
14202        if c == 0 {
14203            break;
14204        }
14205        parent = n as *mut c_void;
14206        if c < 0 {
14207            pp = &mut (*n).left;
14208        } else {
14209            pp = &mut (*n).right;
14210        }
14211    }
14212    let n = *pp;
14213    // musl returns the node above the deleted one; deleting the root has no
14214    // parent, so it returns the (now-freed) root pointer as a non-null token.
14215    let result = if parent.is_null() { n as *mut c_void } else { parent };
14216    if !(*n).left.is_null() {
14217        // replace with in-order predecessor
14218        let mut q = &mut (*n).left;
14219        while !(*(*q)).right.is_null() {
14220            q = &mut (*(*q)).right;
14221        }
14222        let pred = *q;
14223        // swap keys
14224        (*n).key = (*pred).key;
14225        // remove predecessor
14226        *q = (*pred).left;
14227        free(pred as *mut c_void);
14228    } else {
14229        // replace with right child (may be null)
14230        *pp = (*n).right;
14231        free(n as *mut c_void);
14232    }
14233    result
14234}
14235
14236#[no_mangle]
14237pub unsafe extern "C" fn twalk(
14238    root: *const TreeNode,
14239    action: Option<unsafe extern "C" fn(*const c_void, c_int, c_int)>,
14240) {
14241    unsafe fn walk(
14242        node: *const TreeNode,
14243        action: Option<unsafe extern "C" fn(*const c_void, c_int, c_int)>,
14244        depth: c_int,
14245    ) {
14246        if node.is_null() {
14247            return;
14248        }
14249        let is_leaf = (*node).left.is_null() && (*node).right.is_null();
14250        if is_leaf {
14251            action.unwrap()(node as *const c_void, 3, depth); // leaf
14252        } else {
14253            action.unwrap()(node as *const c_void, 0, depth); // preorder
14254            walk((*node).left, action, depth + 1);
14255            action.unwrap()(node as *const c_void, 1, depth); // postorder (left done)
14256            walk((*node).right, action, depth + 1);
14257            action.unwrap()(node as *const c_void, 2, depth); // endorder
14258        }
14259    }
14260    walk(root, action, 0);
14261}
14262
14263#[no_mangle]
14264pub unsafe extern "C" fn tdestroy(root: *mut TreeNode, freekey: Option<unsafe extern "C" fn(*mut c_void)>) {
14265    if root.is_null() {
14266        return;
14267    }
14268    tdestroy((*root).left, freekey);
14269    tdestroy((*root).right, freekey);
14270    if let Some(f) = freekey {
14271        f((*root).key as *mut c_void);
14272    }
14273    free(root as *mut c_void);
14274}
14275
14276// ============================================================
14277// fnmatch: full POSIX pattern matching
14278
14279const FNMATCH_COMPONENT_MAX: usize = 1024;
14280const FNMATCH_PREFIX_MAX: usize = 4096;
14281// ============================================================
14282
14283const FNM_PATHNAME: c_int = 0x1;
14284const FNM_NOESCAPE: c_int = 0x2;
14285const FNM_PERIOD: c_int = 0x4;
14286const FNM_LEADING_DIR: c_int = 0x8;
14287const FNM_CASEFOLD: c_int = 0x10;
14288const FNM_NOMATCH: c_int = 1;
14289
14290const FNM_END: c_int = 0;
14291const FNM_STAR: c_int = -5;
14292const FNM_QUESTION: c_int = -4;
14293const FNM_BRACKET: c_int = -3;
14294const FNM_UNMATCHABLE: c_int = -2;
14295
14296fn ascii_tolower(c: u8) -> u8 {
14297    if c >= b'A' && c <= b'Z' { c + 32 } else { c }
14298}
14299
14300fn ascii_toupper(c: u8) -> u8 {
14301    if c >= b'a' && c <= b'z' { c - 32 } else { c }
14302}
14303
14304fn ascii_casefold(k: u8) -> u8 {
14305    let upper = ascii_toupper(k);
14306    if upper != k { upper } else { ascii_tolower(k) }
14307}
14308
14309/// Get next byte from pattern, classifying it.
14310/// Returns (token_type, bytes_consumed).
14311unsafe fn pat_next(pat: *const u8, m: usize, flags: c_int) -> (c_int, usize) {
14312    if m == 0 || *pat == 0 {
14313        return (FNM_END, 0);
14314    }
14315    let mut p = pat;
14316    let mut step = 1usize;
14317    let mut esc = false;
14318    if *p == b'\\' && !(flags & FNM_NOESCAPE != 0) && *p.add(1) != 0 {
14319        p = p.add(1);
14320        step = 2;
14321        esc = true;
14322    }
14323    if *p == b'[' && !esc {
14324        // scan for matching ]
14325        let mut k = 1usize;
14326        if k < m && (*pat.add(k) == b'^' || *pat.add(k) == b'!') { k += 1; }
14327        if k < m && *pat.add(k) == b']' { k += 1; }
14328        while k < m && *pat.add(k) != 0 && *pat.add(k) != b']' {
14329            if k + 1 < m && *pat.add(k) == b'[' &&
14330               (*pat.add(k+1) == b':' || *pat.add(k+1) == b'.' || *pat.add(k+1) == b'=') {
14331                let z = *pat.add(k+1);
14332                k += 2;
14333                if k < m { k += 1; }
14334                while k < m && *pat.add(k) != 0 && (*pat.add(k-1) != z || *pat.add(k) != b']') { k += 1; }
14335                if k == m || *pat.add(k) == 0 { break; }
14336            }
14337            k += 1;
14338        }
14339        if k == m || *pat.add(k) == 0 {
14340            // unmatched [ is literal
14341            return (b'[' as c_int, 1);
14342        }
14343        return (FNM_BRACKET, k + 1);
14344    }
14345    if *p == b'*' && !esc {
14346        return (FNM_STAR, 1);
14347    }
14348    if *p == b'?' && !esc {
14349        return (FNM_QUESTION, 1);
14350    }
14351    (*p as c_int, step)
14352}
14353
14354unsafe fn match_class(name: &[u8], k: u8, kfold: u8) -> bool {
14355    let eq = |c: u8| k == c || kfold == c;
14356    let in_range = |lo: u8, hi: u8| (k >= lo && k <= hi) || (kfold >= lo && kfold <= hi);
14357    match name {
14358        b"alnum" => in_range(b'0', b'9') || in_range(b'A', b'Z') || in_range(b'a', b'z'),
14359        b"alpha" => in_range(b'A', b'Z') || in_range(b'a', b'z'),
14360        b"blank" => eq(b' ') || eq(b'\t'),
14361        b"cntrl" => k < 0x20 || k == 0x7f,
14362        b"digit" => in_range(b'0', b'9'),
14363        b"graph" => k >= 0x21 && k <= 0x7e,
14364        b"lower" => in_range(b'a', b'z'),
14365        b"print" => k >= 0x20 && k <= 0x7e,
14366        b"punct" =>
14367            (k >= 0x21 && k <= 0x2f) ||
14368            (k >= 0x3a && k <= 0x40) ||
14369            (k >= 0x5b && k <= 0x60) ||
14370            (k >= 0x7b && k <= 0x7e),
14371        b"space" => eq(b' ') || eq(b'\t') || eq(b'\n') || eq(b'\r') || eq(0x0c) || eq(0x0b),
14372        b"upper" => in_range(b'A', b'Z'),
14373        b"xdigit" => in_range(b'0', b'9') || in_range(b'A', b'F') || in_range(b'a', b'f'),
14374        _ => false,
14375    }
14376}
14377
14378/// Match a bracket expression [class] against char k.
14379unsafe fn match_bracket(mut p: *const u8, k: u8, kfold: u8) -> bool {
14380    let mut inv = false;
14381    p = p.add(1); // skip [
14382    if *p == b'^' || *p == b'!' {
14383        inv = true;
14384        p = p.add(1);
14385    }
14386    // handle ] as first char
14387    if *p == b']' {
14388        if k == b']' { return !inv; }
14389        p = p.add(1);
14390    } else if *p == b'-' {
14391        if k == b'-' { return !inv; }
14392        p = p.add(1);
14393    }
14394    while *p != b']' && *p != 0 {
14395        if *p == b'-' && *p.add(1) != b']' && *p.add(1) != 0 {
14396            // range: previous char to next char
14397            let lo = *p.sub(1);
14398            let hi = *p.add(1);
14399            if lo <= hi && (k >= lo && k <= hi || kfold >= lo && kfold <= hi) {
14400                return !inv;
14401            }
14402            p = p.add(2);
14403        } else if *p == b'[' && (*p.add(1) == b':' || *p.add(1) == b'.' || *p.add(1) == b'=') {
14404            let z = *p.add(1);
14405            let start = p.add(2);
14406            let mut q = start;
14407            while *q != 0 && (*q != z || *q.add(1) != b']') { q = q.add(1); }
14408            if *q != 0 {
14409                let len = (q as usize) - (start as usize);
14410                if len > 0 {
14411                    let inner = core::slice::from_raw_parts(start, len);
14412                    let matched =
14413                        if z == b':' { match_class(inner, k, kfold) }
14414                        else { len == 1 && (inner[0] == k || inner[0] == kfold) };
14415                    if matched { return !inv; }
14416                }
14417                p = q.add(2);
14418                continue;
14419            }
14420        } else {
14421            if *p == k || *p == kfold {
14422                return !inv;
14423            }
14424            p = p.add(1);
14425        }
14426    }
14427    inv
14428}
14429
14430/// Core fnmatch for a single path component (no FNM_PATHNAME splitting).
14431/// Match one non-star, non-end pattern token against one input byte.
14432unsafe fn fnmatch_token(
14433    tok: c_int,
14434    pat: *const u8,
14435    s: *const u8,
14436    flags: c_int,
14437) -> bool {
14438    if *s == 0 {
14439        return false;
14440    }
14441    let k = *s;
14442    let kfold = if flags & FNM_CASEFOLD != 0 { ascii_casefold(k) } else { k };
14443    match tok {
14444        FNM_QUESTION => true,
14445        FNM_BRACKET => match_bracket(pat, k, kfold),
14446        c => k as c_int == c || kfold as c_int == c,
14447    }
14448}
14449
14450unsafe fn fnmatch_internal(pat: *const u8, str: *const u8, flags: c_int) -> c_int {
14451    // Handle leading .
14452    if flags & FNM_PERIOD != 0 && *str == b'.' && *pat != b'.' {
14453        return FNM_NOMATCH;
14454    }
14455
14456    let mut p = pat;
14457    let mut s = str;
14458
14459    // Consume pattern up to first *
14460    loop {
14461        let (tok, step) = pat_next(p, usize::MAX, flags);
14462        match tok {
14463            FNM_END => {
14464                return if *s == 0 { 0 } else { FNM_NOMATCH };
14465            }
14466            FNM_STAR => {
14467                p = p.add(1);
14468                break;
14469            }
14470            _ => {
14471                if !fnmatch_token(tok, p, s, flags) { return FNM_NOMATCH; }
14472                p = p.add(step);
14473                s = s.add(1);
14474            }
14475        }
14476    }
14477
14478    // Now p points after first *, rest of pattern is variable
14479    // Factor: find tail after last * and count fixed chars needed
14480    let mut ptail = p;
14481    let mut tailcnt: usize = 0;
14482    let mut pp = p;
14483    loop {
14484        let (tok, step) = pat_next(pp, usize::MAX, flags);
14485        if tok == FNM_END { break; }
14486        if tok == FNM_STAR {
14487            tailcnt = 0;
14488            ptail = pp.add(1);
14489        } else {
14490            tailcnt += 1;
14491        }
14492        pp = pp.add(step);
14493    }
14494
14495    // str must have at least tailcnt chars
14496    let slen = strlen(s as *const c_char);
14497    if slen < tailcnt { return FNM_NOMATCH; }
14498
14499    // Match tail: ptail..end against str[tailcnt from end]
14500    let stail = s.add(slen - tailcnt);
14501    let mut tp = ptail;
14502    let mut ts = stail;
14503    loop {
14504        let (tok, step) = pat_next(tp, usize::MAX, flags);
14505        if tok == FNM_END {
14506            break;
14507        }
14508        if !fnmatch_token(tok, tp, ts, flags) { return FNM_NOMATCH; }
14509        tp = tp.add(step);
14510        ts = ts.add(1);
14511    }
14512
14513    let endstr = stail;
14514    let endpat = ptail;
14515
14516    let mut cp = p;
14517    let mut cs = s;
14518    while cp < endpat {
14519        let (tok, step) = pat_next(cp, usize::MAX, flags);
14520        if tok == FNM_STAR {
14521            cp = cp.add(step);
14522            cs = s;
14523            continue;
14524        }
14525        let comp_start = cp;
14526        let mut ok = false;
14527        let mut try_s = cs;
14528        while try_s < endstr {
14529            let mut tmp_p = comp_start;
14530            let mut tmp_s = try_s;
14531            let mut matched = true;
14532            loop {
14533                let (t, st) = pat_next(tmp_p, usize::MAX, flags);
14534                if t == FNM_STAR || t == FNM_END {
14535                    cp = tmp_p;
14536                    cs = tmp_s;
14537                    ok = true;
14538                    break;
14539                }
14540                if !fnmatch_token(t, tmp_p, tmp_s, flags) {
14541                    matched = false;
14542                    break;
14543                }
14544                tmp_s = tmp_s.add(1);
14545                tmp_p = tmp_p.add(st);
14546            }
14547            if ok { break; }
14548            if !matched {
14549                try_s = try_s.add(1);
14550            }
14551        }
14552        if !ok {
14553            return FNM_NOMATCH;
14554        }
14555    }
14556    0
14557}
14558
14559#[no_mangle]
14560pub unsafe extern "C" fn fnmatch(pat: *const c_char, str: *const c_char, flags: c_int) -> c_int {
14561    let pat = pat as *const u8;
14562    let str = str as *const u8;
14563
14564    if flags & FNM_PATHNAME != 0 {
14565        // Split on /
14566        let mut s = str;
14567        let mut p = pat;
14568        loop {
14569            // find next / in str
14570            let mut send = s;
14571            while *send != 0 && *send != b'/' { send = send.add(1); }
14572            // find next / in pat
14573            let mut pend = p;
14574            loop {
14575                let (tok, step) = pat_next(pend, usize::MAX, flags);
14576                if tok == FNM_END || (tok >= 0 && tok as u8 == b'/') {
14577                    break;
14578                }
14579                pend = pend.add(step);
14580            }
14581            let (ptok, pstep) = pat_next(pend, usize::MAX, flags);
14582            let pat_is_slash = ptok >= 0 && ptok as u8 == b'/';
14583            let str_is_slash = *send == b'/';
14584            if pat_is_slash != str_is_slash && (*send != 0 || !(flags & FNM_LEADING_DIR != 0)) {
14585                return FNM_NOMATCH;
14586            }
14587            // match component
14588            // We need a null-terminated copy of the component
14589            let plen = (pend as usize) - (p as usize);
14590            let slen = (send as usize) - (s as usize);
14591            // Components longer than 1024 bytes are rejected rather than
14592            // matched with a heap buffer.
14593            if plen > FNMATCH_COMPONENT_MAX || slen > FNMATCH_COMPONENT_MAX {
14594                return FNM_NOMATCH;
14595            }
14596            let mut pbuf = [0u8; FNMATCH_COMPONENT_MAX + 1];
14597            let mut sbuf = [0u8; FNMATCH_COMPONENT_MAX + 1];
14598            core::ptr::copy_nonoverlapping(p, pbuf.as_mut_ptr(), plen);
14599            pbuf[plen] = 0;
14600            core::ptr::copy_nonoverlapping(s, sbuf.as_mut_ptr(), slen);
14601            sbuf[slen] = 0;
14602            if fnmatch_internal(pbuf.as_ptr(), sbuf.as_ptr(), flags & !FNM_LEADING_DIR) != 0 {
14603                return FNM_NOMATCH;
14604            }
14605            if !pat_is_slash {
14606                return 0;
14607            }
14608            s = send.add(1);
14609            p = pend.add(pstep);
14610        }
14611    }
14612
14613    if flags & FNM_LEADING_DIR != 0 {
14614        // Try matching at each /
14615        let mut s = str;
14616        while *s != 0 {
14617            if *s == b'/' {
14618                // temporarily null-terminate
14619                // The prefix must be NUL-terminated for fnmatch_internal().
14620                let len = (s as usize) - (str as usize);
14621                // Just call fnmatch_internal with a temp buffer
14622                if len < FNMATCH_PREFIX_MAX {
14623                    let mut buf = [0u8; FNMATCH_PREFIX_MAX];
14624                    core::ptr::copy_nonoverlapping(str, buf.as_mut_ptr(), len);
14625                    buf[len] = 0;
14626                    if fnmatch_internal(pat, buf.as_ptr(), flags) == 0 {
14627                        return 0;
14628                    }
14629                }
14630            }
14631            s = s.add(1);
14632        }
14633    }
14634
14635    fnmatch_internal(pat, str, flags)
14636}
14637
14638// ============================================================
14639// mntent: setmntent/endmntent/getmntent/getmntent_r/addmntent/hasmntopt
14640// ============================================================
14641
14642#[no_mangle]
14643pub unsafe extern "C" fn setmntent(name: *const c_char, mode: *const c_char) -> *mut FILE {
14644    fopen(name, mode)
14645}
14646
14647#[no_mangle]
14648pub unsafe extern "C" fn endmntent(f: *mut FILE) -> c_int {
14649    if !f.is_null() {
14650        fclose(f);
14651    }
14652    1
14653}
14654
14655// static buffers for getmntent (non-_r variant)
14656static mut MNTENT_MNT: MntEnt = MntEnt {
14657    mnt_fsname: core::ptr::null_mut(),
14658    mnt_dir: core::ptr::null_mut(),
14659    mnt_type: core::ptr::null_mut(),
14660    mnt_opts: core::ptr::null_mut(),
14661    mnt_freq: 0,
14662    mnt_passno: 0,
14663};
14664
14665#[repr(C)]
14666pub struct MntEnt {
14667    mnt_fsname: *mut c_char,
14668    mnt_dir: *mut c_char,
14669    mnt_type: *mut c_char,
14670    mnt_opts: *mut c_char,
14671    mnt_freq: c_int,
14672    mnt_passno: c_int,
14673}
14674
14675unsafe fn unescape_ent(beg: *mut c_char) -> *mut c_char {
14676    let mut dest = beg;
14677    let mut src = beg;
14678    while *src != 0 {
14679        if *src != b'\\' as c_char {
14680            *dest = *src;
14681            dest = dest.add(1);
14682            src = src.add(1);
14683            continue;
14684        }
14685        // backslash
14686        if *src.add(1) == b'\\' as c_char {
14687            src = src.add(1);
14688            *dest = *src;
14689            dest = dest.add(1);
14690            src = src.add(1);
14691            continue;
14692        }
14693        // octal escape
14694        let mut val: u8 = 0;
14695        let mut cnt = 0;
14696        let mut sp = src.add(1);
14697        while cnt < 3 && *sp >= b'0' as c_char && *sp <= b'7' as c_char {
14698            val = val * 8 + (*sp as u8 - b'0');
14699            sp = sp.add(1);
14700            cnt += 1;
14701        }
14702        if cnt > 0 {
14703            *dest = val as c_char;
14704            dest = dest.add(1);
14705            src = sp;
14706        } else {
14707            *dest = *src;
14708            dest = dest.add(1);
14709            src = src.add(1);
14710        }
14711    }
14712    *dest = 0;
14713    beg
14714}
14715
14716unsafe fn parse_mntent_line(
14717    linebuf: *mut c_char,
14718    mnt: *mut MntEnt,
14719) -> *mut MntEnt {
14720    let _len = strlen(linebuf as *const c_char);
14721    // skip comments and empty lines
14722    // parse: fsname dir type opts freq passno
14723    let mut p = linebuf;
14724    // skip leading whitespace
14725    while *p == b' ' as c_char || *p == b'\t' as c_char || *p == b'\n' as c_char || *p == b'\r' as c_char {
14726        p = p.add(1);
14727    }
14728    if *p == 0 || *p == b'#' as c_char {
14729        return core::ptr::null_mut();
14730    }
14731
14732    // fsname
14733    (*mnt).mnt_fsname = p;
14734    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14735        p = p.add(1);
14736    }
14737    if *p == 0 { return core::ptr::null_mut(); }
14738    *p = 0;
14739    p = p.add(1);
14740    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14741
14742    // dir
14743    (*mnt).mnt_dir = p;
14744    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14745        p = p.add(1);
14746    }
14747    if *p == 0 { return core::ptr::null_mut(); }
14748    *p = 0;
14749    p = p.add(1);
14750    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14751
14752    // type
14753    (*mnt).mnt_type = p;
14754    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14755        p = p.add(1);
14756    }
14757    if *p == 0 { return core::ptr::null_mut(); }
14758    *p = 0;
14759    p = p.add(1);
14760    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14761
14762    // opts
14763    (*mnt).mnt_opts = p;
14764    while *p != 0 && *p != b' ' as c_char && *p != b'\t' as c_char && *p != b'\n' as c_char {
14765        p = p.add(1);
14766    }
14767    if *p != 0 {
14768        *p = 0;
14769        p = p.add(1);
14770    }
14771    if *(*mnt).mnt_opts == 0 {
14772        (*mnt).mnt_opts = b"defaults\0".as_ptr() as *mut c_char;
14773    }
14774
14775    // freq and passno
14776    (*mnt).mnt_freq = 0;
14777    (*mnt).mnt_passno = 0;
14778    // skip whitespace
14779    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14780    if *p >= b'0' as c_char && *p <= b'9' as c_char {
14781        (*mnt).mnt_freq = (*p - b'0' as c_char) as c_int;
14782        p = p.add(1);
14783        while *p >= b'0' as c_char && *p <= b'9' as c_char {
14784            (*mnt).mnt_freq = (*mnt).mnt_freq * 10 + (*p - b'0' as c_char) as c_int;
14785            p = p.add(1);
14786        }
14787    }
14788    while *p == b' ' as c_char || *p == b'\t' as c_char { p = p.add(1); }
14789    if *p >= b'0' as c_char && *p <= b'9' as c_char {
14790        (*mnt).mnt_passno = (*p - b'0' as c_char) as c_int;
14791        p = p.add(1);
14792        while *p >= b'0' as c_char && *p <= b'9' as c_char {
14793            (*mnt).mnt_passno = (*mnt).mnt_passno * 10 + (*p - b'0' as c_char) as c_int;
14794            p = p.add(1);
14795        }
14796    }
14797
14798    // unescape
14799    unescape_ent((*mnt).mnt_fsname);
14800    unescape_ent((*mnt).mnt_dir);
14801    unescape_ent((*mnt).mnt_type);
14802    unescape_ent((*mnt).mnt_opts);
14803
14804    mnt
14805}
14806
14807// Use a sentinel pointer to detect internal buffer usage
14808// cast integer to pointer for sentinel
14809static SENTINEL_PTR: usize = 1;
14810
14811// Read one char from FILE buffer directly (avoids musl's static fgets ABI mismatch)
14812unsafe fn mntent_fgetc(f: *mut FILE) -> c_int {
14813    fgetc(f)
14814}
14815
14816unsafe fn mntent_fgets(buf: *mut c_char, n: usize, f: *mut FILE) -> *mut c_char {
14817    if n == 0 { return core::ptr::null_mut(); }
14818    let max = n - 1;
14819    let mut i = 0usize;
14820    while i < max {
14821        let c = mntent_fgetc(f);
14822        if c == -1 { if i == 0 { return core::ptr::null_mut(); } break; }
14823        *buf.add(i) = c as c_char;
14824        i += 1;
14825        if c == b'\n' as c_int { break; }
14826    }
14827    *buf.add(i) = 0;
14828    buf
14829}
14830
14831#[no_mangle]
14832pub unsafe extern "C" fn getmntent_r(
14833    f: *mut FILE,
14834    mnt: *mut MntEnt,
14835    mut linebuf: *mut c_char,
14836    buflen: c_int,
14837) -> *mut MntEnt {
14838    let use_internal = linebuf as usize == SENTINEL_PTR;
14839
14840    (*mnt).mnt_freq = 0;
14841    (*mnt).mnt_passno = 0;
14842
14843    static mut MNT_LINE: *mut c_char = core::ptr::null_mut();
14844    static mut MNT_LINE_CAP: usize = 0;
14845
14846    loop {
14847        let res = if use_internal {
14848            let n = getline(&raw mut MNT_LINE, &raw mut MNT_LINE_CAP, f);
14849            if n < 0 {
14850                return core::ptr::null_mut();
14851            }
14852            linebuf = MNT_LINE;
14853            MNT_LINE
14854        } else {
14855            if buflen <= 0 {
14856                ERRNO!() = EINVAL;
14857                return core::ptr::null_mut();
14858            }
14859            mntent_fgets(linebuf, buflen as usize, f)
14860        };
14861        if res.is_null() {
14862            return core::ptr::null_mut();
14863        }
14864        let mut has_newline = false;
14865        let mut p = linebuf;
14866        while *p != 0 { if *p == b'\n' as c_char { has_newline = true; break; } p = p.add(1); }
14867        if !has_newline {
14868            ERRNO!() = ERANGE;
14869            return core::ptr::null_mut();
14870        }
14871        let result = parse_mntent_line(linebuf, mnt);
14872        if !result.is_null() {
14873            return result;
14874        }
14875    }
14876}
14877
14878#[no_mangle]
14879pub unsafe extern "C" fn getmntent(f: *mut FILE) -> *mut MntEnt {
14880    getmntent_r(f, core::ptr::addr_of_mut!(MNTENT_MNT), SENTINEL_PTR as *mut c_char, 0)
14881}
14882
14883#[no_mangle]
14884pub unsafe extern "C" fn addmntent(f: *mut FILE, mnt: *const MntEnt) -> c_int {
14885    fseek(f, 0, 2); // SEEK_END
14886    let written = fprintf(
14887        f,
14888        b"%s\t%s\t%s\t%s\t%d\t%d\n\0".as_ptr() as *const c_char,
14889        (*mnt).mnt_fsname,
14890        (*mnt).mnt_dir,
14891        (*mnt).mnt_type,
14892        (*mnt).mnt_opts,
14893        (*mnt).mnt_freq,
14894        (*mnt).mnt_passno,
14895    );
14896    if written < 0 { 1 } else { 0 }
14897}
14898
14899#[no_mangle]
14900pub unsafe extern "C" fn hasmntopt(mnt: *const MntEnt, opt: *const c_char) -> *mut c_char {
14901    let l = strlen(opt as *const c_char);
14902    let mut p = (*mnt).mnt_opts;
14903    loop {
14904        if strncmp(p as *const u8, opt as *const u8, l) == 0 {
14905            let after = *p.add(l);
14906            if after == 0 || after == b',' as c_char || after == b'=' as c_char {
14907                return p;
14908            }
14909        }
14910        let comma = strchr(p as *const u8, b',' as c_int);
14911        if comma.is_null() {
14912            return core::ptr::null_mut();
14913        }
14914        p = comma.add(1) as *mut c_char;
14915    }
14916}
14917
14918// ============================================================
14919// SysV IPC: ftok, msg*, sem*, shm*
14920// x86_64 direct syscalls: msgget=68, msgsnd=69, msgrcv=70, msgctl=71
14921//   semget=64, semop=65, semctl=66, semtimedop=220
14922//   shmget=29, shmat=30, shmctl=31, shmdt=67
14923// ============================================================
14924
14925
14926#[inline]
14927unsafe fn sys_msgget(key: c_int, msgflg: c_int) -> i64 {
14928    <Arch as Syscalls>::syscall2(SYS_MSGGET, key as i64, msgflg as i64)
14929}
14930
14931#[inline]
14932unsafe fn sys_msgsnd(msqid: c_int, msgp: *const c_void, msgsz: usize, msgflg: c_int) -> i64 {
14933    <Arch as Syscalls>::syscall4(SYS_MSGSND, msqid as i64, msgp as i64, msgsz as i64, msgflg as i64)
14934}
14935
14936#[inline]
14937unsafe fn sys_msgrcv(msqid: c_int, msgp: *mut c_void, msgsz: usize, msgtyp: c_long, msgflg: c_int) -> i64 {
14938    <Arch as Syscalls>::syscall5(SYS_MSGRCV, msqid as i64, msgp as i64, msgsz as i64, msgtyp as i64, msgflg as i64)
14939}
14940
14941#[inline]
14942unsafe fn sys_msgctl(msqid: c_int, cmd: c_int, buf: *mut c_void) -> i64 {
14943    <Arch as Syscalls>::syscall3(SYS_MSGCTL, msqid as i64, cmd as i64, buf as i64)
14944}
14945
14946#[inline]
14947unsafe fn sys_semget(key: c_int, nsems: c_int, semflg: c_int) -> i64 {
14948    <Arch as Syscalls>::syscall3(SYS_SEMGET, key as i64, nsems as i64, semflg as i64)
14949}
14950
14951#[inline]
14952unsafe fn sys_semop(semid: c_int, sops: *const c_void, nsops: usize) -> i64 {
14953    <Arch as Syscalls>::syscall3(SYS_SEMOP, semid as i64, sops as i64, nsops as i64)
14954}
14955
14956#[inline]
14957unsafe fn sys_semctl(semid: c_int, semnum: c_int, cmd: c_int, arg: *mut c_void) -> i64 {
14958    <Arch as Syscalls>::syscall4(SYS_SEMCTL, semid as i64, semnum as i64, cmd as i64, arg as i64)
14959}
14960
14961#[inline]
14962unsafe fn sys_shmget(key: c_int, size: usize, shmflg: c_int) -> i64 {
14963    <Arch as Syscalls>::syscall3(SYS_SHMGET, key as i64, size as i64, shmflg as i64)
14964}
14965
14966#[inline]
14967unsafe fn sys_shmat(shmid: c_int, shmaddr: *const c_void, shmflg: c_int) -> i64 {
14968    <Arch as Syscalls>::syscall3(SYS_SHMAT, shmid as i64, shmaddr as i64, shmflg as i64)
14969}
14970
14971#[inline]
14972unsafe fn sys_shmdt(shmaddr: *const c_void) -> i64 {
14973    <Arch as Syscalls>::syscall1(SYS_SHMDT, shmaddr as i64)
14974}
14975
14976#[inline]
14977unsafe fn sys_shmctl(shmid: c_int, cmd: c_int, buf: *mut c_void) -> i64 {
14978    <Arch as Syscalls>::syscall3(SYS_SHMCTL, shmid as i64, cmd as i64, buf as i64)
14979}
14980
14981// ftok
14982#[no_mangle]
14983pub unsafe extern "C" fn ftok(path: *const c_char, id: c_int) -> c_int {
14984    let mut st: kernel_stat64 = core::mem::zeroed();
14985    let r = sys_stat(path as *const u8, &mut st);
14986    if r < 0 {
14987        ERRNO!() = (-r) as c_int;
14988        return -1;
14989    }
14990    ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16) | (((id as u32 & 0xff) << 24)) as u64) as c_int
14991}
14992
14993// msgget
14994#[no_mangle]
14995pub unsafe extern "C" fn msgget(key: c_int, msgflg: c_int) -> c_int {
14996    let r = sys_msgget(key, msgflg);
14997    syscall_ret(r) as c_int
14998}
14999
15000// msgsnd
15001#[no_mangle]
15002pub unsafe extern "C" fn msgsnd(msqid: c_int, msgp: *const c_void, msgsz: usize, msgflg: c_int) -> c_int {
15003    let r = sys_msgsnd(msqid, msgp, msgsz, msgflg);
15004    syscall_ret(r) as c_int
15005}
15006
15007// msgrcv
15008#[no_mangle]
15009pub unsafe extern "C" fn msgrcv(msqid: c_int, msgp: *mut c_void, msgsz: usize, msgtyp: c_long, msgflg: c_int) -> isize {
15010    let r = sys_msgrcv(msqid, msgp, msgsz, msgtyp, msgflg);
15011    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
15012}
15013
15014// msgctl
15015#[no_mangle]
15016pub unsafe extern "C" fn msgctl(msqid: c_int, cmd: c_int, buf: *mut c_void) -> c_int {
15017    let r = sys_msgctl(msqid, cmd, buf);
15018    syscall_ret(r) as c_int
15019}
15020
15021// semget
15022const SEM_MAX_NSEMS: c_int = 65535;
15023
15024#[no_mangle]
15025pub unsafe extern "C" fn semget(key: c_int, nsems: c_int, semflg: c_int) -> c_int {
15026    if nsems > SEM_MAX_NSEMS { ERRNO!() = EINVAL; return -1; }
15027    let r = sys_semget(key, nsems, semflg);
15028    syscall_ret(r) as c_int
15029}
15030
15031// semop
15032#[no_mangle]
15033pub unsafe extern "C" fn semop(semid: c_int, sops: *const c_void, nsops: usize) -> c_int {
15034    let r = sys_semop(semid, sops, nsops);
15035    syscall_ret(r) as c_int
15036}
15037
15038// semctl - C variadic
15039#[no_mangle]
15040pub unsafe extern "C" fn semctl(semid: c_int, semnum: c_int, cmd: c_int, mut args: ...) -> c_int {
15041    let mut arg: *mut c_void = core::ptr::null_mut();
15042    // Commands that take the union semun argument
15043    match cmd {
15044        // SETVAL/SETALL/GETALL, IPC_SET/IPC_STAT/IPC_INFO, SEM_STAT,
15045        // SEM_INFO, SEM_STAT_ANY and the 32-bit compat variants all carry
15046        // the `union semun` argument.
15047        16 | 13 | 17 | 1 | 2 | 3 | 18 | 19 | 20 | 0x102 | 0x104 | 0x106 => {
15048            arg = args.next_arg::<*mut c_void>();
15049        }
15050        _ => {}
15051    }
15052    let r = sys_semctl(semid, semnum, cmd, arg);
15053    syscall_ret(r) as c_int
15054}
15055
15056// shmget
15057#[no_mangle]
15058pub unsafe extern "C" fn shmget(key: c_int, size: usize, shmflg: c_int) -> c_int {
15059    let r = sys_shmget(key, size, shmflg);
15060    syscall_ret(r) as c_int
15061}
15062
15063// shmat
15064#[no_mangle]
15065pub unsafe extern "C" fn shmat(shmid: c_int, shmaddr: *const c_void, shmflg: c_int) -> *mut c_void {
15066    let r = sys_shmat(shmid, shmaddr, shmflg);
15067    if (r as usize) > (-(crate::SYSCALL_ERR_MAX as isize)) as usize {
15068        ERRNO!() = (-r) as c_int;
15069        return -1isize as *mut c_void;
15070    }
15071    r as *mut c_void
15072}
15073
15074// shmdt
15075#[no_mangle]
15076pub unsafe extern "C" fn shmdt(shmaddr: *const c_void) -> c_int {
15077    let r = sys_shmdt(shmaddr);
15078    syscall_ret(r) as c_int
15079}
15080
15081// shmctl
15082#[no_mangle]
15083pub unsafe extern "C" fn shmctl(shmid: c_int, cmd: c_int, buf: *mut c_void) -> c_int {
15084    let r = sys_shmctl(shmid, cmd, buf);
15085    syscall_ret(r) as c_int
15086}
15087
15088// ============================================================
15089// Startup: __libc_start_main
15090//
15091// musl crt1.o _start_c calls:
15092//   __libc_start_main(main, argc, argv, _init, _fini, rtld_fini, stack_end)
15093// ============================================================
15094
15095// Auxiliary vector pointer, populated by the dynamic linker before
15096// constructors run so getauxval() works during early startup.
15097#[no_mangle]
15098pub static mut __auxv: *const usize = core::ptr::null();
15099#[no_mangle]
15100pub static mut __keel_static_base: usize = 0;
15101static mut RC_STATIC_EXEC: bool = false;
15102
15103#[no_mangle]
15104pub static mut __progname: *mut c_char = core::ptr::null_mut();
15105#[no_mangle]
15106pub static mut __progname_full: *mut c_char = core::ptr::null_mut();
15107#[no_mangle]
15108pub static mut program_invocation_name: *mut c_char = core::ptr::null_mut();
15109#[no_mangle]
15110pub static mut program_invocation_short_name: *mut c_char = core::ptr::null_mut();
15111
15112#[no_mangle]
15113pub static in6addr_any: [u32; 4] = [0; 4];
15114#[no_mangle]
15115pub static in6addr_loopback: [u32; 4] = [0, 0, 0, 0x0100_0000];
15116
15117#[no_mangle]
15118pub static mut __daylight: c_int = 0;
15119#[no_mangle]
15120pub static mut __timezone: c_long = 0;
15121#[no_mangle]
15122pub static mut __tzname: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
15123
15124#[no_mangle]
15125pub unsafe extern "C" fn getauxval(type_: c_ulong) -> c_ulong {
15126    let mut p = __auxv;
15127    if p.is_null() {
15128        return 0;
15129    }
15130    loop {
15131        let tag = *p;
15132        if tag == 0 {
15133            return 0;
15134        }
15135        if tag == type_ as usize {
15136            return *p.add(1) as c_ulong;
15137        }
15138        p = p.add(2);
15139    }
15140}
15141
15142
15143unsafe fn run_static_init() {
15144    if !RC_STATIC_EXEC {
15145        return;
15146    }
15147    extern "C" {
15148        static __preinit_array_start: usize;
15149        static __preinit_array_end: usize;
15150        static __init_array_start: usize;
15151        static __init_array_end: usize;
15152    }
15153    let mut p = core::ptr::addr_of!(__preinit_array_start) as usize;
15154    let end = core::ptr::addr_of!(__preinit_array_end) as usize;
15155    while p < end {
15156        let f = core::ptr::read_unaligned(p as *const usize);
15157        if f != 0 {
15158            let f: unsafe extern "C" fn() = core::mem::transmute(f);
15159            f();
15160        }
15161        p += core::mem::size_of::<usize>();
15162    }
15163    p = core::ptr::addr_of!(__init_array_start) as usize;
15164    let end = core::ptr::addr_of!(__init_array_end) as usize;
15165    while p < end {
15166        let f = core::ptr::read_unaligned(p as *const usize);
15167        if f != 0 {
15168            let f: unsafe extern "C" fn() = core::mem::transmute(f);
15169            f();
15170        }
15171        p += core::mem::size_of::<usize>();
15172    }
15173}
15174
15175type MainFn = unsafe extern "C" fn(c_int, *const *const c_char, *const *const c_char) -> c_int;
15176type InitFn = unsafe extern "C" fn();
15177
15178#[cfg(target_arch = "x86_64")]
15179unsafe fn static_tls_tp() -> usize {
15180    let mut fs: u64 = 0;
15181    if arch_prctl(0x1003, &mut fs as *mut u64 as u64) != 0 {
15182        0
15183    } else {
15184        fs as usize
15185    }
15186}
15187
15188#[cfg(target_arch = "x86_64")]
15189unsafe fn set_static_tls_tp(tp: usize) {
15190    let _ = arch_prctl(0x1002, tp as u64);
15191}
15192
15193#[cfg(target_arch = "aarch64")]
15194unsafe fn static_tls_tp() -> usize {
15195    let tp: usize;
15196    core::arch::asm!("mrs {}, tpidr_el0", out(reg) tp, options(nostack));
15197    tp
15198}
15199
15200#[cfg(target_arch = "aarch64")]
15201unsafe fn set_static_tls_tp(tp: usize) {
15202    core::arch::asm!("msr tpidr_el0, {}", in(reg) tp, options(nostack));
15203}
15204
15205#[cfg(target_arch = "riscv64")]
15206unsafe fn static_tls_tp() -> usize {
15207    let tp: usize;
15208    core::arch::asm!("mv {}, tp", out(reg) tp, options(nostack));
15209    tp
15210}
15211
15212#[cfg(target_arch = "riscv64")]
15213unsafe fn set_static_tls_tp(tp: usize) {
15214    core::arch::asm!("mv tp, {}", in(reg) tp, options(nostack));
15215}
15216
15217static mut STATIC_TLS_BLOCK_SIZE: usize = 0;
15218static mut STATIC_TLS_TP_OFFSET: usize = 0;
15219static mut STATIC_TLS_VAR_OFFSET: usize = 0;
15220static mut STATIC_TLS_TLS_SIZE: usize = 0;
15221static mut STATIC_TLS_IMAGE: *const u8 = core::ptr::null();
15222static mut STATIC_TLS_FILESZ: usize = 0;
15223static mut STATIC_TLS_CANARY: u64 = 0;
15224
15225// Word indices in the 256-byte TCB. Keep in sync with libc/src/ldso/mod.rs.
15226const TCB_GENERATION: usize = 1;
15227const TCB_TLS_SIZE: usize = 2;
15228const TCB_MODULE_COUNT: usize = 3;
15229const TCB_TLSDESC: usize = 4;
15230const TCB_CANARY: usize = 5;
15231const TCB_ERRNO: usize = 6;
15232const TCB_GETRANDOM: usize = 7;
15233const TCB_THREAD: usize = 8;
15234
15235unsafe fn static_tls_init_block(block: *mut u8) -> *mut u8 {
15236    if block.is_null() || STATIC_TLS_BLOCK_SIZE == 0 {
15237        return core::ptr::null_mut();
15238    }
15239    let var_base = block.add(STATIC_TLS_VAR_OFFSET);
15240    if STATIC_TLS_TLS_SIZE > 0 {
15241        core::ptr::write_bytes(var_base, 0, STATIC_TLS_TLS_SIZE);
15242    }
15243    if STATIC_TLS_FILESZ > 0 && !STATIC_TLS_IMAGE.is_null() {
15244        core::ptr::copy_nonoverlapping(STATIC_TLS_IMAGE, var_base, STATIC_TLS_FILESZ);
15245    }
15246    let tp = block.add(STATIC_TLS_TP_OFFSET);
15247    let tcb = if cfg!(target_arch = "x86_64") {
15248        tp as usize
15249    } else {
15250        block as usize
15251    };
15252    core::ptr::write_unaligned(tcb as *mut u64, tcb as u64);
15253    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_GENERATION), 1);
15254    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_TLS_SIZE), STATIC_TLS_TLS_SIZE as u64);
15255    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_MODULE_COUNT), 1);
15256    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_TLSDESC), 0);
15257    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_CANARY), STATIC_TLS_CANARY);
15258    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_ERRNO), 0);
15259    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_GETRANDOM), 0);
15260    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_THREAD), 0);
15261    tp
15262}
15263
15264unsafe fn static_tls_create_block() -> *mut u8 {
15265    if STATIC_TLS_BLOCK_SIZE == 0 {
15266        return core::ptr::null_mut();
15267    }
15268    let block = sys_mmap(
15269        core::ptr::null_mut(),
15270        STATIC_TLS_BLOCK_SIZE,
15271        PROT_READ | PROT_WRITE,
15272        MAP_PRIVATE | MAP_ANONYMOUS,
15273        -1,
15274        0,
15275    );
15276    if block.is_null() || block == MMAP_FAILED {
15277        return core::ptr::null_mut();
15278    }
15279    static_tls_init_block(block)
15280}
15281
15282#[repr(C)]
15283pub struct TlsIndex {
15284    pub ti_module: usize,
15285    pub ti_offset: usize,
15286}
15287
15288/// Global-dynamic TLS access.  The dynamic loader intercepts this symbol for
15289/// dynamically linked programs and uses its own multi-module implementation.
15290/// A static executable has only module 0, so resolve directly against the
15291/// static TLS block created by `init_static_tls()`.
15292static mut TLS_GET_ADDR_IMPL: usize = 0;
15293
15294/// The dynamic loader installs its multi-module TLS resolver here before
15295/// running constructors.  Keeping a dispatch pointer means a program that
15296/// obtains `__tls_get_addr` through `dlsym` still reaches the loader's
15297/// implementation rather than the static fallback below.
15298#[no_mangle]
15299pub unsafe extern "C" fn __keel_set_tls_get_addr(f: usize) {
15300    TLS_GET_ADDR_IMPL = f;
15301}
15302
15303#[no_mangle]
15304pub unsafe extern "C" fn __tls_get_addr(ti: *const TlsIndex) -> *mut u8 {
15305    if TLS_GET_ADDR_IMPL != 0 {
15306        let f: unsafe extern "C" fn(*const TlsIndex) -> *mut u8 =
15307            core::mem::transmute(TLS_GET_ADDR_IMPL);
15308        return f(ti);
15309    }
15310    if ti.is_null() || (*ti).ti_module != 0 || !RC_STATIC_EXEC {
15311        return core::ptr::null_mut();
15312    }
15313    let tp = static_tls_tp();
15314    if tp == 0 {
15315        return core::ptr::null_mut();
15316    }
15317    (tp - STATIC_TLS_TP_OFFSET + STATIC_TLS_VAR_OFFSET + (*ti).ti_offset) as *mut u8
15318}
15319
15320/// Static executables have no dynamic loader to build a TCB.  Allocate one
15321/// from PT_TLS so that `%fs`/TP-relative TLS accesses and errno work.
15322unsafe fn init_static_tls() {
15323    if static_tls_tp() != 0 {
15324        return;
15325    }
15326    let phdr = getauxval(3) as usize; // AT_PHDR
15327    let phnum = getauxval(5) as usize; // AT_PHNUM
15328    let phent = getauxval(4) as usize; // AT_PHENT
15329    if phdr == 0 || phnum == 0 || phent < 56 {
15330        return;
15331    }
15332
15333    let mut tls_vaddr = 0usize;
15334    let mut tls_filesz = 0usize;
15335    let mut tls_memsz = 0usize;
15336    let mut tls_align = 1usize;
15337    let mut exec_base = __keel_static_base;
15338    let mut i = 0usize;
15339    while i < phnum {
15340        let ph = phdr + i * phent;
15341        let p_type = core::ptr::read_unaligned(ph as *const u32);
15342        if p_type == 3 {
15343            // PT_INTERP means the dynamic loader already owns TLS.
15344            return;
15345        }
15346        if p_type == 6 {
15347            // PT_PHDR
15348            if exec_base == 0 {
15349                let p_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
15350                exec_base = phdr.wrapping_sub(p_vaddr);
15351            }
15352        } else if p_type == 7 {
15353            // PT_TLS
15354            tls_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
15355            tls_filesz = core::ptr::read_unaligned((ph + 32) as *const u64) as usize;
15356            tls_memsz = core::ptr::read_unaligned((ph + 40) as *const u64) as usize;
15357            let align = core::ptr::read_unaligned((ph + 48) as *const u64) as usize;
15358            if align > 1 {
15359                tls_align = align;
15360            }
15361        }
15362        i += 1;
15363    }
15364
15365    let tcb_size = 256usize;
15366    #[cfg(target_arch = "x86_64")]
15367    let gap = 0usize;
15368    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
15369    let gap = if cfg!(target_arch = "aarch64") { 16usize } else { 0usize };
15370
15371    let tls_size = if tls_align > 1 {
15372        (tls_memsz + tls_align - 1) & !(tls_align - 1)
15373    } else {
15374        tls_memsz
15375    };
15376    let total = tcb_size + gap + tls_size + tls_align;
15377    STATIC_TLS_BLOCK_SIZE = total;
15378    STATIC_TLS_TP_OFFSET = if cfg!(target_arch = "x86_64") {
15379        tls_size
15380    } else {
15381        tcb_size
15382    };
15383    STATIC_TLS_VAR_OFFSET = if cfg!(target_arch = "x86_64") {
15384        0
15385    } else {
15386        tcb_size + gap
15387    };
15388    STATIC_TLS_TLS_SIZE = tls_size;
15389    STATIC_TLS_IMAGE = (exec_base + tls_vaddr) as *const u8;
15390    STATIC_TLS_FILESZ = tls_filesz;
15391    let random = getauxval(25) as *const u8; // AT_RANDOM
15392    STATIC_TLS_CANARY = if random.is_null() {
15393        0xdefaced_cafebeefu64
15394    } else {
15395        core::ptr::read_unaligned(random as *const u64)
15396            ^ core::ptr::read_unaligned(random.add(8) as *const u64)
15397    };
15398
15399    let block = sys_mmap(
15400        core::ptr::null_mut(),
15401        total,
15402        PROT_READ | PROT_WRITE,
15403        MAP_PRIVATE | MAP_ANONYMOUS,
15404        -1,
15405        0,
15406    );
15407    if block.is_null() || block == MMAP_FAILED {
15408        return;
15409    }
15410    let tp = static_tls_init_block(block);
15411    if tp.is_null() {
15412        return;
15413    }
15414    set_static_tls_tp(tp as usize);
15415    RC_STATIC_EXEC = true;
15416}
15417
15418
15419#[no_mangle]
15420pub unsafe extern "C" fn __libc_start_main(
15421    main: MainFn,
15422    argc: c_int,
15423    argv: *const *const c_char,
15424    _init: *const c_void,
15425    _fini: *const c_void,
15426    _rtld_fini: *const c_void,
15427    _stack_end: *const c_void,
15428) -> ! {
15429    let envp = argv.add((argc + 1) as usize);
15430    let mut aux = envp;
15431    while !(*aux).is_null() {
15432        aux = aux.add(1);
15433    }
15434    __auxv = aux.add(1) as *const usize;
15435    init_static_tls();
15436    errno_init();
15437    // Register the main thread during startup.  pthread_exit() uses the
15438    // thread table to decide whether it is the last thread; if the main
15439    // thread only registered lazily, a worker exiting first could call
15440    // exit() while the main thread was still alive.  Register slot 0
15441    // directly: pthread_self() would otherwise scan the whole static thread
15442    // table and fault in roughly 1 MiB on every process start.
15443    register_main_thread();
15444
15445    __environ = envp as *mut *mut c_char;
15446    environ = __environ; // sync environ alias
15447    ___environ = __environ;
15448    _environ = __environ;
15449
15450    // glibc-compatible program name globals.
15451    if !argv.is_null() && argc > 0 {
15452        let argv0 = *argv;
15453        __progname_full = argv0 as *mut c_char;
15454        program_invocation_name = argv0 as *mut c_char;
15455        let mut base = argv0;
15456        let mut p = argv0;
15457        while *p != 0 {
15458            if *p == b'/' as c_char { base = p.add(1); }
15459            p = p.add(1);
15460        }
15461        __progname = base as *mut c_char;
15462        program_invocation_short_name = base as *mut c_char;
15463    }
15464
15465    __stdio_init();
15466    run_static_init();
15467
15468    let mut set: SigSetT = 0;
15469    sigemptyset(&mut set);
15470    sigaddset(&mut set, SIGCANCEL);
15471    sigprocmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
15472
15473    if !_init.is_null() {
15474        let init_fn: InitFn = core::mem::transmute(_init);
15475        init_fn();
15476    }
15477
15478    // aarch64/riscv64 GCC reads __stack_chk_guard as a global (GOT-based for PIE),
15479    // so we must initialize it from AT_RANDOM before calling main.
15480    // x86_64 uses %fs:0x28 which the kernel already set up.
15481    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
15482    {
15483        let random_ptr = getauxval(25) as *const u8; // AT_RANDOM = 25
15484        if !random_ptr.is_null() {
15485            let a = core::ptr::read_unaligned(random_ptr as *const u64);
15486            let b = core::ptr::read_unaligned(random_ptr.add(8) as *const u64);
15487            __stack_chk_guard = (a ^ b) as usize;
15488        } else {
15489            // Linux always supplies AT_RANDOM; keep a nonzero fallback for
15490            // the unlikely case where the auxiliary vector is absent.
15491            __stack_chk_guard = 0xdefaced_cafebeef;
15492        }
15493    }
15494
15495    let result = main(argc, argv, envp);
15496
15497    if !_fini.is_null() {
15498        let fini_fn: InitFn = core::mem::transmute(_fini);
15499        fini_fn();
15500    }
15501
15502    exit(result);
15503}
15504
15505type LdsoDlopenFn = unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void;
15506type LdsoDlsymFn = unsafe extern "C" fn(*mut c_void, *const c_char, *mut c_void) -> *mut c_void;
15507type LdsoDlcloseFn = unsafe extern "C" fn(*mut c_void) -> c_int;
15508type LdsoDlerrorFn = unsafe extern "C" fn() -> *const c_char;
15509
15510static mut LDSO_DLOPEN: Option<LdsoDlopenFn> = None;
15511static mut LDSO_DLSYM: Option<LdsoDlsymFn> = None;
15512static mut LDSO_DLCLOSE: Option<LdsoDlcloseFn> = None;
15513static mut LDSO_DLERROR: Option<LdsoDlerrorFn> = None;
15514
15515#[no_mangle]
15516pub unsafe extern "C" fn __ldso_register_dlopen(f: LdsoDlopenFn) {
15517    LDSO_DLOPEN = Some(f);
15518}
15519
15520#[no_mangle]
15521pub unsafe extern "C" fn __ldso_register_dlsym(f: LdsoDlsymFn) {
15522    LDSO_DLSYM = Some(f);
15523}
15524
15525#[no_mangle]
15526pub unsafe extern "C" fn __ldso_register_dlclose(f: LdsoDlcloseFn) {
15527    LDSO_DLCLOSE = Some(f);
15528}
15529
15530#[no_mangle]
15531pub unsafe extern "C" fn __ldso_register_dlerror(f: LdsoDlerrorFn) {
15532    LDSO_DLERROR = Some(f);
15533}
15534
15535#[no_mangle]
15536pub unsafe extern "C" fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void {
15537    if let Some(f) = LDSO_DLOPEN {
15538        f(filename, flags)
15539    } else {
15540        null_mut()
15541    }
15542}
15543
15544#[no_mangle]
15545pub unsafe extern "C" fn dlsym_impl(
15546    handle: *mut c_void,
15547    symbol: *const c_char,
15548    ra: *mut c_void,
15549) -> *mut c_void {
15550    if let Some(f) = LDSO_DLSYM {
15551        f(handle, symbol, ra)
15552    } else {
15553        null_mut()
15554    }
15555}
15556
15557// dlsym() must pass its own return address to the loader so that
15558// RTLD_NEXT can identify the calling object.  Keep the public entry
15559// point in assembly and tail-jump into the Rust implementation.
15560#[no_mangle]
15561#[unsafe(naked)]
15562#[cfg(target_arch = "x86_64")]
15563pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15564    core::arch::naked_asm!("mov rdx, [rsp]", "jmp dlsym_impl");
15565}
15566
15567#[no_mangle]
15568#[unsafe(naked)]
15569#[cfg(target_arch = "aarch64")]
15570pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15571    core::arch::naked_asm!("mov x2, x30", "b dlsym_impl");
15572}
15573
15574#[no_mangle]
15575#[unsafe(naked)]
15576#[cfg(target_arch = "riscv64")]
15577pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
15578    core::arch::naked_asm!("mv a2, ra", "la t0, dlsym_impl", "jr t0");
15579}
15580
15581#[no_mangle]
15582pub unsafe extern "C" fn dlclose(handle: *mut c_void) -> c_int {
15583    if let Some(f) = LDSO_DLCLOSE {
15584        f(handle)
15585    } else {
15586        0
15587    }
15588}
15589
15590#[no_mangle]
15591pub unsafe extern "C" fn dlerror() -> *const c_char {
15592    if let Some(f) = LDSO_DLERROR {
15593        f()
15594    } else {
15595        core::ptr::null()
15596    }
15597}
15598
15599include!("crypt_impl.rs");
15600include!("statvfs.rs");
15601include!("daemon.rs");
15602include!("safety.rs");
15603include!("dn_expand.rs");
15604include!("lrand48.rs");
15605include!("strverscmp.rs");
15606include!("syscall.rs");
15607include!("pthread_atfork.rs");
15608include!("fenv.rs");
15609include!("locale_ctype.rs");
15610include!("regression_stubs.rs");
15611include!("ctype_tables.rs");
15612include!("wctype_tables.rs");
15613include!("netdb_extra.rs");
15614include!("compat_extra.rs");
15615include!("stdio_extra.rs");
15616include!("ns_parse.rs");
15617include!("fts.rs");
15618include!("ifaddrs.rs");
15619include!("dl_extra.rs");
15620include!("des.rs");
15621include!("path_extra.rs");
15622include!("wordexp.rs");
15623include!("getopt_impl.rs");
15624
15625// ============================================================
15626// regex.h
15627// ============================================================
15628
15629// musl defines regoff_t as _Addr (long on every Linux target), not int.
15630type regoff_t = c_long;
15631
15632#[repr(C)]
15633pub struct regex_t {
15634    pub re_nsub: usize,
15635    pub __opaque: *mut c_void,
15636    pub __padding: [*mut c_void; 4],
15637    pub __nsub2: usize,
15638    pub __padding2: c_char,
15639}
15640
15641#[repr(C)]
15642pub struct regmatch_t {
15643    pub rm_so: regoff_t,
15644    pub rm_eo: regoff_t,
15645}
15646
15647include!("regex.rs");
15648include!("tz.rs");
15649
15650// The dynamic loader is part of libc, mirroring musl's single-file design.
15651// It is compiled as a module so its private syscall/string helpers do not
15652// collide with the libc namespace; its exported entry points remain global.
15653#[allow(dead_code, deref_nullptr)]
15654mod ldso;
15655
15656// ============================================================
15657// fmax/fmin and related helpers
15658// ============================================================
15659
15660#[inline]
15661pub(crate) fn fmax_impl(x: f64, y: f64) -> f64 {
15662    if x.is_nan() { return y; }
15663    if y.is_nan() { return x; }
15664    if x == 0.0 && y == 0.0 {
15665        return if x.is_sign_negative() && y.is_sign_negative() { -0.0 } else { 0.0 };
15666    }
15667    if x > y { x } else { y }
15668}
15669
15670#[inline]
15671pub(crate) fn fmin_impl(x: f64, y: f64) -> f64 {
15672    if x.is_nan() { return y; }
15673    if y.is_nan() { return x; }
15674    if x == 0.0 && y == 0.0 {
15675        return if x.is_sign_negative() || y.is_sign_negative() { -0.0 } else { 0.0 };
15676    }
15677    if x < y { x } else { y }
15678}
15679
15680#[inline]
15681pub(crate) fn fmaxf_impl(x: f32, y: f32) -> f32 {
15682    if x.is_nan() { return y; }
15683    if y.is_nan() { return x; }
15684    if x == 0.0 && y == 0.0 {
15685        return if x.is_sign_negative() && y.is_sign_negative() { -0.0 } else { 0.0 };
15686    }
15687    if x > y { x } else { y }
15688}
15689
15690#[inline]
15691pub(crate) fn fminf_impl(x: f32, y: f32) -> f32 {
15692    if x.is_nan() { return y; }
15693    if y.is_nan() { return x; }
15694    if x == 0.0 && y == 0.0 {
15695        return if x.is_sign_negative() || y.is_sign_negative() { -0.0 } else { 0.0 };
15696    }
15697    if x < y { x } else { y }
15698}
15699
15700#[inline(never)]
15701#[no_mangle]
15702pub unsafe extern "C" fn fmax(x: f64, y: f64) -> f64 {
15703    fmax_impl(x, y)
15704}
15705
15706#[inline(never)]
15707#[no_mangle]
15708pub unsafe extern "C" fn fmin(x: f64, y: f64) -> f64 {
15709    fmin_impl(x, y)
15710}
15711
15712#[no_mangle]
15713pub unsafe extern "C" fn fminf(x: f32, y: f32) -> f32 {
15714    fminf_impl(x, y)
15715}
15716
15717#[no_mangle]
15718pub unsafe extern "C" fn fdim(x: f64, y: f64) -> f64 {
15719    if x.is_nan() || y.is_nan() {
15720        return f64::NAN;
15721    }
15722    if x > y { x - y } else { 0.0 }
15723}
15724
15725#[no_mangle]
15726pub unsafe extern "C" fn fma(x: f64, y: f64, z: f64) -> f64 {
15727    if (x.is_infinite() && y == 0.0) || (y.is_infinite() && x == 0.0) {
15728        feraiseexcept(FE_INVALID);
15729        return f64::NAN;
15730    }
15731    if x.is_nan() || y.is_nan() || z.is_nan() {
15732        return f64::NAN;
15733    }
15734    let r = libm::fma(x, y, z);
15735    // inf-inf is invalid; libm may return NaN without raising.
15736    if r.is_nan() {
15737        feraiseexcept(FE_INVALID);
15738    }
15739    r
15740}
15741
15742#[no_mangle]
15743pub unsafe extern "C" fn ilogb(x: f64) -> i32 {
15744    if x.is_nan() {
15745        feraiseexcept(FE_INVALID);
15746        return -0x7fffffff - 1; // FP_ILOGBNAN
15747    }
15748    if x == 0.0 || x.is_infinite() {
15749        feraiseexcept(FE_INVALID);
15750        return if x == 0.0 { -0x7fffffff - 1 } else { 0x7fffffff };
15751    }
15752    let bits = x.to_bits();
15753    let exp = ((bits >> 52) & 0x7ff) as i32;
15754    if exp == 0 {
15755        // subnormal
15756        let mut v = bits & 0xfffffffffffff;
15757        let mut e = -1022;
15758        while v < (1u64 << 52) { v <<= 1; e -= 1; }
15759        e
15760    } else {
15761        exp - 1023
15762    }
15763}
15764
15765#[no_mangle]
15766pub unsafe extern "C" fn logb(x: f64) -> f64 {
15767    if x.is_nan() { return x; }
15768    if x == 0.0 { return __math_divzero(1); }
15769    let bits = x.to_bits();
15770    let exp = ((bits >> 52) & 0x7ff) as i32;
15771    if exp == 0 {
15772        // subnormal
15773        let mut v = bits & 0xfffffffffffff;
15774        let mut e = -1022i32;
15775        while v < (1u64 << 52) { v <<= 1; e -= 1; }
15776        e as f64
15777    } else if exp == 0x7ff {
15778        x * x // infinity * infinity = infinity (preserves sign)
15779    } else {
15780        (exp - 1023) as f64
15781    }
15782}
15783
15784#[no_mangle]
15785pub unsafe extern "C" fn nearbyint(x: f64) -> f64 {
15786    let had_inexact = fetestexcept(FE_INEXACT) & FE_INEXACT != 0;
15787    let r = libm::rint(x);
15788    if !had_inexact {
15789        feclearexcept(FE_INEXACT);
15790    }
15791    r
15792}
15793
15794#[no_mangle]
15795pub unsafe extern "C" fn nextafter(x: f64, y: f64) -> f64 {
15796    if x.is_nan() || y.is_nan() { return x + y; }
15797    if x == 0.0 && y == 0.0 { return y; }
15798    if x == y { return x; }
15799    let r = libm::nextafter(x, y);
15800    if r.is_infinite() && x.is_finite() {
15801        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
15802    } else if r != x {
15803        let bits = r.to_bits();
15804        let is_subnormal = (bits & 0x7ff0000000000000) == 0 && (bits & 0xfffffffffffff) != 0;
15805        if r == 0.0 || is_subnormal {
15806            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
15807        }
15808    }
15809    r
15810}
15811
15812#[no_mangle]
15813pub unsafe extern "C" fn nexttoward(x: f64, y: f64) -> f64 {
15814    // On x86_64, long double = f64, so nexttoward = nextafter
15815    if x == 0.0 && y == 0.0 {
15816        return if y.is_sign_negative() { -0.0 } else { 0.0 };
15817    }
15818    nextafter(x, y)
15819}
15820
15821#[no_mangle]
15822pub unsafe extern "C" fn remainder(x: f64, y: f64) -> f64 {
15823    if x.is_nan() || y.is_nan() { return x + y; }
15824    if y == 0.0 || x.is_infinite() { return __math_invalid(x); }
15825    libm::remainder(x, y)
15826}
15827
15828#[no_mangle]
15829pub unsafe extern "C" fn remquo(x: f64, y: f64, quo: *mut i32) -> f64 {
15830    if x.is_nan() || y.is_nan() {
15831        if !quo.is_null() { *quo = 0; }
15832        return x + y;
15833    }
15834    if y == 0.0 || x.is_infinite() {
15835        if !quo.is_null() { *quo = 0; }
15836        return __math_invalid(x);
15837    }
15838    let (r, q) = libm::remquo(x, y);
15839    if !quo.is_null() { *quo = q; }
15840    r
15841}
15842
15843#[no_mangle]
15844pub unsafe extern "C" fn exp2(x: f64) -> f64 {
15845    exp2_impl(x)
15846}
15847
15848#[no_mangle]
15849pub unsafe extern "C" fn expm1(x: f64) -> f64 {
15850    let r = libm::expm1(x);
15851    // Raise UNDERFLOW for very small results that underflow
15852    if r != 0.0 && x != 0.0 && libm::fabs(x) < 1e-307 {
15853        feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
15854    }
15855    r
15856}
15857
15858#[no_mangle]
15859pub unsafe extern "C" fn log1p(x: f64) -> f64 {
15860    if x == -1.0 {
15861        feraiseexcept(FE_DIVBYZERO);
15862        return f64::NEG_INFINITY;
15863    }
15864    libm::log1p(x)
15865}
15866
15867#[no_mangle]
15868pub unsafe extern "C" fn acosh(x: f64) -> f64 {
15869    if x < 1.0 {
15870        feraiseexcept(FE_INVALID);
15871        return f64::NAN;
15872    }
15873    libm::acosh(x)
15874}
15875
15876#[no_mangle]
15877pub unsafe extern "C" fn asinh(x: f64) -> f64 {
15878    if x == 0.0 { return x; }
15879    libm::asinh(x)
15880}
15881
15882#[no_mangle]
15883pub unsafe extern "C" fn atanh(x: f64) -> f64 {
15884    if x == 0.0 { return x; }
15885    let e = ((x.to_bits() >> 52) & 0x7ff) as i32;
15886    if e < 0x3ff - 32 {
15887        feraiseexcept(FE_INEXACT);
15888        if e == 0 { feraiseexcept(FE_UNDERFLOW); }
15889        return x;
15890    }
15891    if x == 1.0 {
15892        feraiseexcept(FE_DIVBYZERO);
15893        return f64::INFINITY;
15894    }
15895    if x == -1.0 {
15896        feraiseexcept(FE_DIVBYZERO);
15897        return f64::NEG_INFINITY;
15898    }
15899    if x.is_nan() { return x; }
15900    let ax = libm::fabs(x);
15901    if ax > 1.0 {
15902        feraiseexcept(FE_INVALID);
15903        return f64::NAN;
15904    }
15905    if ax < 0.5 {
15906        // For small x: use log1p formula with |x| and negate
15907        let r = libm::log1p(2.0 * (ax + ax * ax / (1.0 - ax))) / 2.0;
15908        if x < 0.0 { -r } else { r }
15909    } else {
15910        // For larger x: use log formula with |x| and negate
15911        let r = 0.5 * libm::log((1.0 + ax) / (1.0 - ax));
15912        if x < 0.0 { -r } else { r }
15913    }
15914}
15915
15916#[no_mangle]
15917pub unsafe extern "C" fn cbrt(x: f64) -> f64 {
15918    libm::cbrt(x)
15919}
15920
15921#[no_mangle]
15922pub unsafe extern "C" fn erf(x: f64) -> f64 {
15923    libm::erf(x)
15924}
15925
15926#[no_mangle]
15927pub unsafe extern "C" fn erfc(x: f64) -> f64 {
15928    libm::erfc(x)
15929}
15930
15931#[no_mangle]
15932pub unsafe extern "C" fn lgamma(x: f64) -> f64 {
15933    lgamma_impl(x)
15934}
15935
15936#[no_mangle]
15937pub unsafe extern "C" fn tgamma(x: f64) -> f64 {
15938    tgamma_impl(x)
15939}
15940
15941#[no_mangle]
15942pub unsafe extern "C" fn lround(x: f64) -> core::ffi::c_long {
15943    libm::round(x) as core::ffi::c_long
15944}
15945
15946#[no_mangle]
15947pub unsafe extern "C" fn llround(x: f64) -> i64 {
15948    libm::round(x) as i64
15949}
15950
15951// ============================================================
15952// Complex math functions - using (f64, f64) pairs
15953// ============================================================
15954
15955// Helper: complex number as (real, imag) pair
15956// cabs: magnitude = sqrt(re^2 + im^2)
15957#[no_mangle]
15958pub unsafe extern "C" fn cabs(z: (f64, f64)) -> f64 {
15959    libm::sqrt(z.0 * z.0 + z.1 * z.1)
15960}
15961
15962#[no_mangle]
15963pub unsafe extern "C" fn cabsf(z: (f32, f32)) -> f32 {
15964    libm::sqrtf(z.0 * z.0 + z.1 * z.1)
15965}
15966
15967#[no_mangle]
15968pub unsafe extern "C" fn cabsl(z: (f64, f64)) -> f64 {
15969    cabs(z)
15970}
15971
15972#[no_mangle]
15973pub unsafe extern "C" fn carg(z: (f64, f64)) -> f64 {
15974    libm::atan2(z.1, z.0)
15975}
15976
15977#[no_mangle]
15978pub unsafe extern "C" fn cargf(z: (f32, f32)) -> f32 {
15979    libm::atan2f(z.1, z.0)
15980}
15981
15982#[no_mangle]
15983pub unsafe extern "C" fn cargl(z: (f64, f64)) -> f64 {
15984    carg(z)
15985}
15986
15987#[no_mangle]
15988pub unsafe extern "C" fn cimag(z: (f64, f64)) -> f64 {
15989    z.1
15990}
15991
15992#[no_mangle]
15993pub unsafe extern "C" fn cimagf(z: (f32, f32)) -> f32 {
15994    z.1
15995}
15996
15997#[no_mangle]
15998pub unsafe extern "C" fn cimagl(z: (f64, f64)) -> f64 {
15999    z.1
16000}
16001
16002#[no_mangle]
16003pub unsafe extern "C" fn creal(z: (f64, f64)) -> f64 {
16004    z.0
16005}
16006
16007#[no_mangle]
16008pub unsafe extern "C" fn crealf(z: (f32, f32)) -> f32 {
16009    z.0
16010}
16011
16012#[no_mangle]
16013pub unsafe extern "C" fn creall(z: (f64, f64)) -> f64 {
16014    z.0
16015}
16016
16017#[no_mangle]
16018pub unsafe extern "C" fn conj(z: (f64, f64)) -> (f64, f64) {
16019    (z.0, -z.1)
16020}
16021
16022#[no_mangle]
16023pub unsafe extern "C" fn conjf(z: (f32, f32)) -> (f32, f32) {
16024    (z.0, -z.1)
16025}
16026
16027#[no_mangle]
16028pub unsafe extern "C" fn conjl(z: (f64, f64)) -> (f64, f64) {
16029    conj(z)
16030}
16031
16032#[no_mangle]
16033pub unsafe extern "C" fn cproj(z: (f64, f64)) -> (f64, f64) {
16034    if z.0.is_infinite() || z.1.is_infinite() {
16035        (f64::INFINITY, if z.1.is_sign_positive() { 0.0 } else { -0.0 })
16036    } else {
16037        z
16038    }
16039}
16040
16041#[no_mangle]
16042pub unsafe extern "C" fn cprojf(z: (f32, f32)) -> (f32, f32) {
16043    if z.0.is_infinite() || z.1.is_infinite() {
16044        (f32::INFINITY, if z.1.is_sign_positive() { 0.0 } else { -0.0 })
16045    } else {
16046        z
16047    }
16048}
16049
16050#[no_mangle]
16051pub unsafe extern "C" fn cprojl(z: (f64, f64)) -> (f64, f64) {
16052    cproj(z)
16053}
16054
16055// cexp: e^z = e^(re + i*im) = e^re * (cos(im) + i*sin(im))
16056#[no_mangle]
16057pub unsafe extern "C" fn cexp(z: (f64, f64)) -> (f64, f64) {
16058    let r = libm::exp(z.0);
16059    (r * libm::cos(z.1), r * libm::sin(z.1))
16060}
16061
16062#[no_mangle]
16063pub unsafe extern "C" fn cexpf(z: (f32, f32)) -> (f32, f32) {
16064    let r = libm::expf(z.0);
16065    (r * libm::cosf(z.1), r * libm::sinf(z.1))
16066}
16067
16068#[no_mangle]
16069pub unsafe extern "C" fn cexpl(z: (f64, f64)) -> (f64, f64) {
16070    cexp(z)
16071}
16072
16073// clog: ln(z) = ln|z| + i*arg(z)
16074#[no_mangle]
16075pub unsafe extern "C" fn clog(z: (f64, f64)) -> (f64, f64) {
16076    (libm::log(cabs(z)), carg(z))
16077}
16078
16079#[no_mangle]
16080pub unsafe extern "C" fn clogf(z: (f32, f32)) -> (f32, f32) {
16081    (libm::logf(cabsf(z)), cargf(z))
16082}
16083
16084#[no_mangle]
16085pub unsafe extern "C" fn clogl(z: (f64, f64)) -> (f64, f64) {
16086    clog(z)
16087}
16088
16089// csqrt: sqrt(z) = sqrt((|z|+re)/2) + i*sign(im)*sqrt((|z|-re)/2)
16090#[no_mangle]
16091pub unsafe extern "C" fn csqrt(z: (f64, f64)) -> (f64, f64) {
16092    let r = cabs(z);
16093    let sign = if z.1 < 0.0 { -1.0 } else { 1.0 };
16094    (libm::sqrt((r + z.0) / 2.0), sign * libm::sqrt((r - z.0) / 2.0))
16095}
16096
16097#[no_mangle]
16098pub unsafe extern "C" fn csqrtf(z: (f32, f32)) -> (f32, f32) {
16099    let r = cabsf(z);
16100    let sign = if z.1 < 0.0 { -1.0f32 } else { 1.0f32 };
16101    (libm::sqrtf((r + z.0) / 2.0), sign * libm::sqrtf((r - z.0) / 2.0))
16102}
16103
16104#[no_mangle]
16105pub unsafe extern "C" fn csqrtl(z: (f64, f64)) -> (f64, f64) {
16106    csqrt(z)
16107}
16108
16109// cpow: z^w = e^(w * log(z))
16110#[no_mangle]
16111pub unsafe extern "C" fn cpow(z: (f64, f64), w: (f64, f64)) -> (f64, f64) {
16112    let log_z = clog(z);
16113    let exp_arg = (w.0 * log_z.0 - w.1 * log_z.1, w.0 * log_z.1 + w.1 * log_z.0);
16114    cexp(exp_arg)
16115}
16116
16117#[no_mangle]
16118pub unsafe extern "C" fn cpowf(z: (f32, f32), w: (f32, f32)) -> (f32, f32) {
16119    let log_z = clogf(z);
16120    let exp_arg = (w.0 * log_z.0 - w.1 * log_z.1, w.0 * log_z.1 + w.1 * log_z.0);
16121    cexpf(exp_arg)
16122}
16123
16124#[no_mangle]
16125pub unsafe extern "C" fn cpowl(z: (f64, f64), w: (f64, f64)) -> (f64, f64) {
16126    cpow(z, w)
16127}
16128
16129// ccos: cos(z) = cos(re)*cosh(im) - i*sin(re)*sinh(im)
16130#[no_mangle]
16131pub unsafe extern "C" fn ccos(z: (f64, f64)) -> (f64, f64) {
16132    (libm::cos(z.0) * libm::cosh(z.1), -libm::sin(z.0) * libm::sinh(z.1))
16133}
16134
16135#[no_mangle]
16136pub unsafe extern "C" fn ccosf(z: (f32, f32)) -> (f32, f32) {
16137    (libm::cosf(z.0) * libm::coshf(z.1), -libm::sinf(z.0) * libm::sinhf(z.1))
16138}
16139
16140#[no_mangle]
16141pub unsafe extern "C" fn ccosl(z: (f64, f64)) -> (f64, f64) {
16142    ccos(z)
16143}
16144
16145// csin: sin(z) = sin(re)*cosh(im) + i*cos(re)*sinh(im)
16146#[no_mangle]
16147pub unsafe extern "C" fn csin(z: (f64, f64)) -> (f64, f64) {
16148    (libm::sin(z.0) * libm::cosh(z.1), libm::cos(z.0) * libm::sinh(z.1))
16149}
16150
16151#[no_mangle]
16152pub unsafe extern "C" fn csinf(z: (f32, f32)) -> (f32, f32) {
16153    (libm::sinf(z.0) * libm::coshf(z.1), libm::cosf(z.0) * libm::sinhf(z.1))
16154}
16155
16156#[no_mangle]
16157pub unsafe extern "C" fn csinl(z: (f64, f64)) -> (f64, f64) {
16158    csin(z)
16159}
16160
16161// ctan: tan(z) = sin(2re)/(cos(2re)+cosh(2im)) + i*sinh(2im)/(cos(2re)+cosh(2im))
16162#[no_mangle]
16163pub unsafe extern "C" fn ctan(z: (f64, f64)) -> (f64, f64) {
16164    let d = libm::cos(2.0 * z.0) + libm::cosh(2.0 * z.1);
16165    (libm::sin(2.0 * z.0) / d, libm::sinh(2.0 * z.1) / d)
16166}
16167
16168#[no_mangle]
16169pub unsafe extern "C" fn ctanf(z: (f32, f32)) -> (f32, f32) {
16170    let d = libm::cosf(2.0 * z.0) + libm::coshf(2.0 * z.1);
16171    (libm::sinf(2.0 * z.0) / d, libm::sinhf(2.0 * z.1) / d)
16172}
16173
16174#[no_mangle]
16175pub unsafe extern "C" fn ctanl(z: (f64, f64)) -> (f64, f64) {
16176    ctan(z)
16177}
16178
16179// ccosh: cosh(z) = cosh(re)*cos(im) + i*sinh(re)*sin(im)
16180#[no_mangle]
16181pub unsafe extern "C" fn ccosh(z: (f64, f64)) -> (f64, f64) {
16182    (libm::cosh(z.0) * libm::cos(z.1), libm::sinh(z.0) * libm::sin(z.1))
16183}
16184
16185#[no_mangle]
16186pub unsafe extern "C" fn ccoshf(z: (f32, f32)) -> (f32, f32) {
16187    (libm::coshf(z.0) * libm::cosf(z.1), libm::sinhf(z.0) * libm::sinf(z.1))
16188}
16189
16190#[no_mangle]
16191pub unsafe extern "C" fn ccoshl(z: (f64, f64)) -> (f64, f64) {
16192    ccosh(z)
16193}
16194
16195// csinh: sinh(z) = sinh(re)*cos(im) + i*cosh(re)*sin(im)
16196#[no_mangle]
16197pub unsafe extern "C" fn csinh(z: (f64, f64)) -> (f64, f64) {
16198    (libm::sinh(z.0) * libm::cos(z.1), libm::cosh(z.0) * libm::sin(z.1))
16199}
16200
16201#[no_mangle]
16202pub unsafe extern "C" fn csinhf(z: (f32, f32)) -> (f32, f32) {
16203    (libm::sinhf(z.0) * libm::cosf(z.1), libm::coshf(z.0) * libm::sinf(z.1))
16204}
16205
16206#[no_mangle]
16207pub unsafe extern "C" fn csinhl(z: (f64, f64)) -> (f64, f64) {
16208    csinh(z)
16209}
16210
16211// ctanh: tanh(z) = sinh(2re)/(cosh(2re)+cos(2im)) + i*sin(2im)/(cosh(2re)+cos(2im))
16212#[no_mangle]
16213pub unsafe extern "C" fn ctanh(z: (f64, f64)) -> (f64, f64) {
16214    let d = libm::cosh(2.0 * z.0) + libm::cos(2.0 * z.1);
16215    (libm::sinh(2.0 * z.0) / d, libm::sin(2.0 * z.1) / d)
16216}
16217
16218#[no_mangle]
16219pub unsafe extern "C" fn ctanhf(z: (f32, f32)) -> (f32, f32) {
16220    let d = libm::coshf(2.0 * z.0) + libm::cosf(2.0 * z.1);
16221    (libm::sinhf(2.0 * z.0) / d, libm::sinf(2.0 * z.1) / d)
16222}
16223
16224#[no_mangle]
16225pub unsafe extern "C" fn ctanhl(z: (f64, f64)) -> (f64, f64) {
16226    ctanh(z)
16227}
16228
16229// cacos: acos(z) = pi/2 - asin(z)
16230// asin(z) = -i * log(i*z + sqrt(1 - z^2))
16231#[no_mangle]
16232pub unsafe extern "C" fn cacos(z: (f64, f64)) -> (f64, f64) {
16233    let asin_z = casin(z);
16234    (3.14159265358979323846264338327950288419716939937510582097494459230781640 / 2.0 - asin_z.0, -asin_z.1)
16235}
16236
16237#[no_mangle]
16238pub unsafe extern "C" fn cacosf(z: (f32, f32)) -> (f32, f32) {
16239    let asin_z = casinf(z);
16240    (3.14159265358979323846264338327950288419716939937510582097494459230781640f32 / 2.0 - asin_z.0, -asin_z.1)
16241}
16242
16243#[no_mangle]
16244pub unsafe extern "C" fn cacosl(z: (f64, f64)) -> (f64, f64) {
16245    cacos(z)
16246}
16247
16248// casin: asin(z) = -i * log(i*z + sqrt(1 - z^2))
16249#[no_mangle]
16250pub unsafe extern "C" fn casin(z: (f64, f64)) -> (f64, f64) {
16251    // i*z = (-z.1, z.0)
16252    let iz = (-z.1, z.0);
16253    // 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)
16254    let one_minus_z2 = (1.0 - z.0 * z.0 + z.1 * z.1, -2.0 * z.0 * z.1);
16255    let sqrt_val = csqrt(one_minus_z2);
16256    let arg = clog((iz.0 + sqrt_val.0, iz.1 + sqrt_val.1));
16257    // -i * log(...) = (arg.1, -arg.0)
16258    (arg.1, -arg.0)
16259}
16260
16261#[no_mangle]
16262pub unsafe extern "C" fn casinf(z: (f32, f32)) -> (f32, f32) {
16263    let iz = (-z.1, z.0);
16264    let one_minus_z2 = (1.0 - z.0 * z.0 + z.1 * z.1, -2.0 * z.0 * z.1);
16265    let sqrt_val = csqrtf(one_minus_z2);
16266    let arg = clogf((iz.0 + sqrt_val.0, iz.1 + sqrt_val.1));
16267    (arg.1, -arg.0)
16268}
16269
16270#[no_mangle]
16271pub unsafe extern "C" fn casinl(z: (f64, f64)) -> (f64, f64) {
16272    casin(z)
16273}
16274
16275// catan: atan(z) = (i/2) * log((1 - i*z)/(1 + i*z))
16276#[no_mangle]
16277pub unsafe extern "C" fn catan(z: (f64, f64)) -> (f64, f64) {
16278    // i*z = (-z.1, z.0)
16279    // 1 - i*z = (1 + z.1, -z.0)
16280    // 1 + i*z = (1 - z.1, z.0)
16281    let num = (1.0 + z.1, -z.0);
16282    let den = (1.0 - z.1, z.0);
16283    let ratio = cdiv(num, den);
16284    let log_ratio = clog(ratio);
16285    // (i/2) * log = (-log.1/2, log.0/2)
16286    (-log_ratio.1 / 2.0, log_ratio.0 / 2.0)
16287}
16288
16289#[no_mangle]
16290pub unsafe extern "C" fn catanf(z: (f32, f32)) -> (f32, f32) {
16291    let num = (1.0 + z.1, -z.0);
16292    let den = (1.0 - z.1, z.0);
16293    let ratio = cdivf(num, den);
16294    let log_ratio = clogf(ratio);
16295    (-log_ratio.1 / 2.0, log_ratio.0 / 2.0)
16296}
16297
16298#[no_mangle]
16299pub unsafe extern "C" fn catanl(z: (f64, f64)) -> (f64, f64) {
16300    catan(z)
16301}
16302
16303// Helper: complex division
16304fn cdiv(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
16305    let d = b.0 * b.0 + b.1 * b.1;
16306    ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
16307}
16308
16309fn cdivf(a: (f32, f32), b: (f32, f32)) -> (f32, f32) {
16310    let d = b.0 * b.0 + b.1 * b.1;
16311    ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
16312}
16313
16314// cacosh: acosh(z) = log(z + sqrt(z^2 - 1))
16315#[no_mangle]
16316pub unsafe extern "C" fn cacosh(z: (f64, f64)) -> (f64, f64) {
16317    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16318    let z2_minus_1 = (z2.0 - 1.0, z2.1);
16319    let sqrt_val = csqrt(z2_minus_1);
16320    clog((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16321}
16322
16323#[no_mangle]
16324pub unsafe extern "C" fn cacoshf(z: (f32, f32)) -> (f32, f32) {
16325    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16326    let z2_minus_1 = (z2.0 - 1.0, z2.1);
16327    let sqrt_val = csqrtf(z2_minus_1);
16328    clogf((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16329}
16330
16331#[no_mangle]
16332pub unsafe extern "C" fn cacoshl(z: (f64, f64)) -> (f64, f64) {
16333    cacosh(z)
16334}
16335
16336// casinh: asinh(z) = log(z + sqrt(z^2 + 1))
16337#[no_mangle]
16338pub unsafe extern "C" fn casinh(z: (f64, f64)) -> (f64, f64) {
16339    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16340    let z2_plus_1 = (z2.0 + 1.0, z2.1);
16341    let sqrt_val = csqrt(z2_plus_1);
16342    clog((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16343}
16344
16345#[no_mangle]
16346pub unsafe extern "C" fn casinhf(z: (f32, f32)) -> (f32, f32) {
16347    let z2 = (z.0 * z.0 - z.1 * z.1, 2.0 * z.0 * z.1);
16348    let z2_plus_1 = (z2.0 + 1.0, z2.1);
16349    let sqrt_val = csqrtf(z2_plus_1);
16350    clogf((z.0 + sqrt_val.0, z.1 + sqrt_val.1))
16351}
16352
16353#[no_mangle]
16354pub unsafe extern "C" fn casinhl(z: (f64, f64)) -> (f64, f64) {
16355    casinh(z)
16356}
16357
16358// catanh: atanh(z) = (1/2) * log((1+z)/(1-z))
16359#[no_mangle]
16360pub unsafe extern "C" fn catanh(z: (f64, f64)) -> (f64, f64) {
16361    let num = (1.0 + z.0, z.1);
16362    let den = (1.0 - z.0, -z.1);
16363    let ratio = cdiv(num, den);
16364    let log_ratio = clog(ratio);
16365    (log_ratio.0 / 2.0, log_ratio.1 / 2.0)
16366}
16367
16368#[no_mangle]
16369pub unsafe extern "C" fn catanhf(z: (f32, f32)) -> (f32, f32) {
16370    let num = (1.0 + z.0, z.1);
16371    let den = (1.0 - z.0, -z.1);
16372    let ratio = cdivf(num, den);
16373    let log_ratio = clogf(ratio);
16374    (log_ratio.0 / 2.0, log_ratio.1 / 2.0)
16375}
16376
16377#[no_mangle]
16378pub unsafe extern "C" fn catanhl(z: (f64, f64)) -> (f64, f64) {
16379    catanh(z)
16380}
16381
16382// ============================================================
16383// Float math functions (f32 versions)
16384// ============================================================
16385
16386#[inline(never)]
16387#[no_mangle]
16388pub unsafe extern "C" fn fmaxf(x: f32, y: f32) -> f32 {
16389    fmaxf_impl(x, y)
16390}
16391
16392#[no_mangle]
16393pub unsafe extern "C" fn fdimf(x: f32, y: f32) -> f32 {
16394    if x.is_nan() || y.is_nan() {
16395        return f32::NAN;
16396    }
16397    if x > y { x - y } else { 0.0 }
16398}
16399
16400#[no_mangle]
16401pub unsafe extern "C" fn fmaf(x: f32, y: f32, z: f32) -> f32 {
16402    if (x.is_infinite() && y == 0.0) || (y.is_infinite() && x == 0.0) {
16403        feraiseexcept(FE_INVALID);
16404        return f32::NAN;
16405    }
16406    if x.is_nan() || y.is_nan() || z.is_nan() {
16407        return f32::NAN;
16408    }
16409    let r = libm::fmaf(x, y, z);
16410    if r.is_nan() {
16411        feraiseexcept(FE_INVALID);
16412    }
16413    r
16414}
16415
16416#[no_mangle]
16417pub unsafe extern "C" fn ilogbf(x: f32) -> i32 {
16418    if x.is_nan() {
16419        feraiseexcept(FE_INVALID);
16420        return -0x7fffffff - 1;
16421    }
16422    if x == 0.0 || x.is_infinite() {
16423        feraiseexcept(FE_INVALID);
16424        return if x == 0.0 { -0x7fffffff - 1 } else { 0x7fffffff };
16425    }
16426    let bits = x.to_bits();
16427    let exp = ((bits >> 23) & 0xff) as i32;
16428    if exp == 0 {
16429        let mut v = bits & 0x7fffff;
16430        let mut e = -126;
16431        while v < (1u32 << 23) { v <<= 1; e -= 1; }
16432        e
16433    } else {
16434        exp - 127
16435    }
16436}
16437
16438#[no_mangle]
16439pub unsafe extern "C" fn logbf(x: f32) -> f32 {
16440    if x.is_nan() { return x; }
16441    if x == 0.0 { return __math_divzerof(1); }
16442    let bits = x.to_bits();
16443    let exp = ((bits >> 23) & 0xff) as i32;
16444    if exp == 0 {
16445        let mut v = bits & 0x7fffff;
16446        let mut e = -126i32;
16447        while v < (1u32 << 23) { v <<= 1; e -= 1; }
16448        e as f32
16449    } else if exp == 0xff {
16450        x * x
16451    } else {
16452        (exp - 127) as f32
16453    }
16454}
16455
16456#[no_mangle]
16457pub unsafe extern "C" fn nearbyintf(x: f32) -> f32 {
16458    let had_inexact = fetestexcept(FE_INEXACT) & FE_INEXACT != 0;
16459    let r = libm::rintf(x);
16460    if !had_inexact {
16461        feclearexcept(FE_INEXACT);
16462    }
16463    r
16464}
16465
16466#[no_mangle]
16467pub unsafe extern "C" fn nextafterf(x: f32, y: f32) -> f32 {
16468    if x.is_nan() || y.is_nan() { return x + y; }
16469    if x == 0.0 && y == 0.0 { return y; }
16470    if x == y { return x; }
16471    let r = libm::nextafterf(x, y);
16472    if r.is_infinite() && x.is_finite() {
16473        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
16474    } else if r != x {
16475        let bits = r.to_bits();
16476        let is_subnormal = (bits & 0x7f800000) == 0 && (bits & 0x7fffff) != 0;
16477        if r == 0.0 || is_subnormal {
16478            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16479        }
16480    }
16481    r
16482}
16483
16484#[no_mangle]
16485#[cfg(target_arch = "x86_64")]
16486pub unsafe extern "C" fn nexttowardf(x: f32, y: f64) -> f32 {
16487    if y.is_nan() { return (x as f64 + y) as f32; }
16488    if x == 0.0 && y == 0.0 {
16489        return if y.is_sign_negative() { -0.0 } else { 0.0 };
16490    }
16491    if (x as f64) == y { return x; }
16492    nextafterf(x, if y > x as f64 { f32::INFINITY } else { f32::NEG_INFINITY })
16493}
16494
16495#[no_mangle]
16496#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
16497pub unsafe extern "C" fn nexttowardf(x: f32, y: f128) -> f32 {
16498    if f128_is_nan(y) { return f32::NAN; }
16499    let yf = f128_to_f64(y);
16500    if x as f64 == yf { return x; }
16501    nextafterf(x, if yf > x as f64 { f32::INFINITY } else { f32::NEG_INFINITY })
16502}
16503
16504#[no_mangle]
16505pub unsafe extern "C" fn remainderf(x: f32, y: f32) -> f32 {
16506    if x.is_nan() || y.is_nan() { return x + y; }
16507    if y == 0.0 || x.is_infinite() { return __math_invalidf(x); }
16508    libm::remainderf(x, y)
16509}
16510
16511#[no_mangle]
16512pub unsafe extern "C" fn remquof(x: f32, y: f32, quo: *mut i32) -> f32 {
16513    if x.is_nan() || y.is_nan() {
16514        if !quo.is_null() { *quo = 0; }
16515        return x + y;
16516    }
16517    if y == 0.0 || x.is_infinite() {
16518        if !quo.is_null() { *quo = 0; }
16519        return __math_invalidf(x);
16520    }
16521    let (r, q) = libm::remquof(x, y);
16522    if !quo.is_null() { *quo = q; }
16523    r
16524}
16525
16526#[no_mangle]
16527pub unsafe extern "C" fn exp2f(x: f32) -> f32 {
16528    if x == f32::INFINITY { return f32::INFINITY; }
16529    if x == f32::NEG_INFINITY { return 0.0; }
16530    if x.is_nan() { return f32::NAN; }
16531    let r = libm::exp2f(x);
16532    if r.is_infinite() && x.is_finite() {
16533        feraiseexcept(FE_OVERFLOW | FE_INEXACT);
16534    } else if r == 0.0 && x < -149.0 {
16535        feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16536    } else if r != 0.0 && x != libm::truncf(x) {
16537        let bits = r.to_bits();
16538        if (bits & 0x7f800000) == 0 {
16539            feraiseexcept(FE_UNDERFLOW | FE_INEXACT);
16540        }
16541    }
16542    r
16543}
16544
16545#[no_mangle]
16546pub unsafe extern "C" fn expm1f(x: f32) -> f32 {
16547    libm::expm1f(x)
16548}
16549
16550#[no_mangle]
16551pub unsafe extern "C" fn log1pf(x: f32) -> f32 {
16552    if x == -1.0 {
16553        feraiseexcept(FE_DIVBYZERO);
16554        return f32::NEG_INFINITY;
16555    }
16556    libm::log1pf(x)
16557}
16558
16559#[no_mangle]
16560pub unsafe extern "C" fn acoshf(x: f32) -> f32 {
16561    if x < 1.0 {
16562        feraiseexcept(FE_INVALID);
16563        return f32::NAN;
16564    }
16565    libm::acoshf(x)
16566}
16567
16568#[no_mangle]
16569pub unsafe extern "C" fn asinhf(x: f32) -> f32 {
16570    if x == 0.0 { return x; }
16571    libm::asinhf(x)
16572}
16573
16574#[no_mangle]
16575pub unsafe extern "C" fn atanhf(x: f32) -> f32 {
16576    if x == 0.0 { return x; }
16577    let e = ((x.to_bits() >> 23) & 0xff) as i32;
16578    if e < 0x7f - 32 {
16579        feraiseexcept(FE_INEXACT);
16580        if e == 0 { feraiseexcept(FE_UNDERFLOW); }
16581        return x;
16582    }
16583    if x == 1.0 {
16584        feraiseexcept(FE_DIVBYZERO);
16585        return f32::INFINITY;
16586    }
16587    if x == -1.0 {
16588        feraiseexcept(FE_DIVBYZERO);
16589        return f32::NEG_INFINITY;
16590    }
16591    if x.is_nan() { return x; }
16592    let ax = libm::fabsf(x);
16593    if ax > 1.0 {
16594        feraiseexcept(FE_INVALID);
16595        return f32::NAN;
16596    }
16597    if ax < 0.5 {
16598        let r = libm::log1pf(2.0 * (ax + ax * ax / (1.0 - ax))) / 2.0;
16599        if x < 0.0 { -r } else { r }
16600    } else {
16601        let r = 0.5 * libm::logf((1.0 + ax) / (1.0 - ax));
16602        if x < 0.0 { -r } else { r }
16603    }
16604}
16605
16606#[no_mangle]
16607pub unsafe extern "C" fn cbrtf(x: f32) -> f32 {
16608    libm::cbrtf(x)
16609}
16610
16611#[no_mangle]
16612pub unsafe extern "C" fn erff(x: f32) -> f32 {
16613    libm::erff(x)
16614}
16615
16616#[no_mangle]
16617pub unsafe extern "C" fn erfcf(x: f32) -> f32 {
16618    libm::erfcf(x)
16619}
16620
16621#[no_mangle]
16622pub unsafe extern "C" fn lgammaf(x: f32) -> f32 {
16623    if x.is_nan() {
16624        crate::set_signgam(1);
16625        return x;
16626    }
16627    if x == 0.0 {
16628        crate::set_signgam(if x.is_sign_negative() { -1 } else { 1 });
16629        feraiseexcept(FE_DIVBYZERO);
16630        return f32::INFINITY;
16631    }
16632    let (r, sign) = libm::lgammaf_r(x);
16633    crate::set_signgam(sign);
16634    r
16635}
16636
16637#[no_mangle]
16638pub unsafe extern "C" fn tgammaf(x: f32) -> f32 {
16639    if x.is_nan() { return x; }
16640    if x == 0.0 {
16641        feraiseexcept(FE_DIVBYZERO);
16642        return if x.is_sign_negative() { f32::NEG_INFINITY } else { f32::INFINITY };
16643    }
16644    if x.is_infinite() {
16645        return if x.is_sign_negative() { __math_invalidf(x) } else { f32::INFINITY };
16646    }
16647    if x < 0.0 && x == libm::floorf(x) {
16648        feraiseexcept(FE_INVALID);
16649        return f32::NAN;
16650    }
16651    libm::tgammaf(x)
16652}
16653
16654#[no_mangle]
16655pub unsafe extern "C" fn lroundf(x: f32) -> core::ffi::c_long {
16656    libm::roundf(x) as core::ffi::c_long
16657}
16658
16659#[no_mangle]
16660pub unsafe extern "C" fn llroundf(x: f32) -> i64 {
16661    libm::roundf(x) as i64
16662}
16663
16664// ============================================================
16665// Wide char functions
16666// ============================================================
16667
16668#[no_mangle]
16669pub unsafe extern "C" fn wcscasecmp(s1: *const u32, s2: *const u32) -> i32 {
16670    let mut i = 0;
16671    loop {
16672        let c1 = *s1.add(i);
16673        let c2 = *s2.add(i);
16674        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16675        let l1 = if c1 >= 'A' as u32 && c1 <= 'Z' as u32 { c1 + 32 } else { c1 };
16676        let l2 = if c2 >= 'A' as u32 && c2 <= 'Z' as u32 { c2 + 32 } else { c2 };
16677        if l1 != l2 { return (l1 as i32) - (l2 as i32); }
16678        i += 1;
16679    }
16680}
16681
16682#[no_mangle]
16683pub unsafe extern "C" fn wcscasecmp_l(s1: *const u32, s2: *const u32, _loc: *mut core::ffi::c_void) -> i32 {
16684    wcscasecmp(s1, s2)
16685}
16686
16687#[no_mangle]
16688pub unsafe extern "C" fn wcsncasecmp(s1: *const u32, s2: *const u32, n: usize) -> i32 {
16689    let mut i = 0;
16690    while i < n {
16691        let c1 = *s1.add(i);
16692        let c2 = *s2.add(i);
16693        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16694        let l1 = if c1 >= 'A' as u32 && c1 <= 'Z' as u32 { c1 + 32 } else { c1 };
16695        let l2 = if c2 >= 'A' as u32 && c2 <= 'Z' as u32 { c2 + 32 } else { c2 };
16696        if l1 != l2 { return (l1 as i32) - (l2 as i32); }
16697        i += 1;
16698    }
16699    0
16700}
16701
16702#[no_mangle]
16703pub unsafe extern "C" fn wcsncasecmp_l(s1: *const u32, s2: *const u32, n: usize, _loc: *mut core::ffi::c_void) -> i32 {
16704    wcsncasecmp(s1, s2, n)
16705}
16706
16707#[no_mangle]
16708pub unsafe extern "C" fn wcscoll(s1: *const u32, s2: *const u32) -> i32 {
16709    // musl's C locale compares wide characters by codepoint.
16710    let mut i = 0;
16711    loop {
16712        let c1 = *s1.add(i);
16713        let c2 = *s2.add(i);
16714        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
16715        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
16716        i += 1;
16717    }
16718}
16719
16720unsafe fn wc_in_set(c: u32, set: *const u32) -> bool {
16721    let mut i = 0usize;
16722    while *set.add(i) != 0 {
16723        if *set.add(i) == c { return true; }
16724        i += 1;
16725    }
16726    false
16727}
16728
16729#[no_mangle]
16730pub unsafe extern "C" fn wcstok(s: *mut u32, sep: *const u32, p: *mut *mut u32) -> *mut u32 {
16731    if sep.is_null() || p.is_null() { return core::ptr::null_mut(); }
16732    let mut src = if s.is_null() {
16733        if (*p).is_null() { return core::ptr::null_mut(); }
16734        *p
16735    } else { s };
16736    while *src != 0 && wc_in_set(*src, sep) { src = src.add(1); }
16737    if *src == 0 { return core::ptr::null_mut(); }
16738    let start = src;
16739    while *src != 0 && !wc_in_set(*src, sep) { src = src.add(1); }
16740    if *src != 0 {
16741        *src = 0;
16742        *p = src.add(1);
16743    } else {
16744        *p = src;
16745    }
16746    start
16747}
16748
16749#[no_mangle]
16750pub unsafe extern "C" fn wcswcs(haystack: *const u32, needle: *const u32) -> *mut u32 {
16751    if *needle == 0 { return haystack as *mut u32; }
16752    let mut i = 0;
16753    while *haystack.add(i) != 0 {
16754        let mut j = 0;
16755        while *needle.add(j) != 0 && *haystack.add(i + j) == *needle.add(j) {
16756            j += 1;
16757        }
16758        if *needle.add(j) == 0 { return haystack.add(i) as *mut u32; }
16759        i += 1;
16760    }
16761    core::ptr::null_mut()
16762}
16763
16764#[no_mangle]
16765pub unsafe extern "C" fn wcswidth(s: *const u32, n: usize) -> i32 {
16766    let mut width = 0i32;
16767    let mut i = 0usize;
16768    while i < n {
16769        let c = *s.add(i);
16770        if c == 0 { break; }
16771        let w = wcwidth(c);
16772        if w < 0 { return w; }
16773        width += w;
16774        i += 1;
16775    }
16776    width
16777}
16778
16779#[no_mangle]
16780pub unsafe extern "C" fn wcsftime(s: *mut u32, maxsize: usize, fmt: *const u32, tm: *const c_void) -> usize {
16781    if s.is_null() || fmt.is_null() || maxsize == 0 { return 0; }
16782    // Convert the wide format string to multibyte, let strftime do the work,
16783    // then convert the result back. Both buffers scale with the inputs.
16784    let wlen = wcslen(fmt as *const wchar_t);
16785    let cfmt_cap = match wlen.checked_mul(4).and_then(|v| v.checked_add(1)) {
16786        Some(v) => v,
16787        None => return 0,
16788    };
16789    let cfmt = crate::malloc(cfmt_cap) as *mut u8;
16790    if cfmt.is_null() { ERRNO!() = ENOMEM; return 0; }
16791    let mut o = 0usize;
16792    let mut i = 0usize;
16793    let mut st: c_uint = 0;
16794    while *fmt.add(i) != 0 {
16795        let n = wcrtomb(
16796            cfmt.add(o) as *mut c_char,
16797            *fmt.add(i) as c_int,
16798            &mut st as *mut c_uint,
16799        );
16800        if n == !0usize || o + n >= cfmt_cap {
16801            crate::free(cfmt as *mut c_void);
16802            return 0;
16803        }
16804        o += n;
16805        i += 1;
16806    }
16807    *cfmt.add(o) = 0;
16808    let out_cap = match maxsize.checked_mul(4).and_then(|v| v.checked_add(1)) {
16809        Some(v) => v,
16810        None => { crate::free(cfmt as *mut c_void); return 0; }
16811    };
16812    let out = crate::malloc(out_cap) as *mut u8;
16813    if out.is_null() {
16814        crate::free(cfmt as *mut c_void);
16815        ERRNO!() = ENOMEM;
16816        return 0;
16817    }
16818    let n = strftime(out as *mut c_char, out_cap, cfmt as *const c_char, tm as *const tm);
16819    crate::free(cfmt as *mut c_void);
16820    if n == 0 {
16821        crate::free(out as *mut c_void);
16822        return 0;
16823    }
16824    let mut ws = 0usize;
16825    let mut p = 0usize;
16826    while p < n && ws + 1 < maxsize {
16827        let mut wc: c_int = 0;
16828        let mut st2: c_uint = 0;
16829        let r = mbrtowc(&mut wc, out.add(p) as *const c_char, n - p, &mut st2);
16830        if r == !0usize {
16831            crate::free(out as *mut c_void);
16832            return 0;
16833        }
16834        if r == 0 || r == !1usize { break; }
16835        *s.add(ws) = wc as u32;
16836        ws += 1;
16837        p += r;
16838    }
16839    *s.add(ws) = 0;
16840    crate::free(out as *mut c_void);
16841    ws
16842}
16843
16844#[no_mangle]
16845pub unsafe extern "C" fn mbsnrtowcs(
16846    dst: *mut u32,
16847    src: *mut *const u8,
16848    nms: usize,
16849    len: usize,
16850    st: *mut core::ffi::c_void,
16851) -> usize {
16852    if src.is_null() { return 0; }
16853    let mut s = *src;
16854    if s.is_null() { return 0; }
16855    let state = st as *mut c_uint;
16856    let limit = if dst.is_null() { usize::MAX } else { len };
16857    let mut count = 0usize;
16858    let mut n = nms;
16859    while count < limit && n > 0 {
16860        let c = *s;
16861        if c == 0 {
16862            if !dst.is_null() {
16863                if count < len { *dst.add(count) = 0; }
16864                *src = core::ptr::null();
16865            }
16866            return count;
16867        }
16868        let mut wc: c_int = 0;
16869        let r = mbrtowc(&mut wc, s as *const c_char, n, state);
16870        if r == !0usize {
16871            *src = s;
16872            return !0usize;
16873        }
16874        if r == !1usize { break; }
16875        if !dst.is_null() { *dst.add(count) = wc as u32; }
16876        count += 1;
16877        s = s.add(r);
16878        n -= r;
16879    }
16880    *src = s;
16881    count
16882}
16883
16884#[no_mangle]
16885pub unsafe extern "C" fn wcsnrtombs(dst: *mut u8, src: *mut *const u32, nwc: usize, len: usize, _st: *mut core::ffi::c_void) -> usize {
16886    // Port of musl's wcsnrtombs: nwc counts wide characters, len counts
16887    // output bytes, and a converted NUL terminates the source pointer.
16888    let mut ws = *src;
16889    let mut wn = nwc;
16890    let mut cnt = 0usize;
16891    let mut n = len;
16892    let mut d = dst;
16893    while !ws.is_null() && wn > 0 {
16894        let c = *ws;
16895        let mut tmp = [0u8; 8];
16896        let mut state: c_uint = 0;
16897        let l = wcrtomb(tmp.as_mut_ptr() as *mut c_char, c as c_int, &mut state);
16898        if l == !0usize {
16899            return !0usize;
16900        }
16901        if !d.is_null() {
16902            if l > n {
16903                break;
16904            }
16905            core::ptr::copy_nonoverlapping(tmp.as_ptr(), d, l);
16906            d = d.add(l);
16907            n -= l;
16908        }
16909        if c == 0 {
16910            ws = core::ptr::null();
16911            break;
16912        }
16913        ws = ws.add(1);
16914        wn -= 1;
16915        cnt += l;
16916    }
16917    if !dst.is_null() {
16918        *src = ws;
16919    }
16920    cnt
16921}
16922
16923// ============================================================
16924// Thread sync functions (C11 threads)
16925// ============================================================
16926
16927
16928// C11 thread types
16929pub type thrd_start_t = Option<unsafe extern "C" fn(arg: *mut core::ffi::c_void) -> i32>;
16930
16931// C11 threads: thin wrappers around the pthread implementation.
16932#[no_mangle]
16933pub unsafe extern "C" fn thrd_create(thr: *mut usize, func: thrd_start_t, arg: *mut core::ffi::c_void) -> i32 {
16934    let mut thread: u64 = 0;
16935    let r = pthread_create(&mut thread, core::ptr::null(), core::mem::transmute(func), arg);
16936    if r == 0 {
16937        *thr = thread as usize;
16938        0 // thrd_success
16939    } else {
16940        -1 // thrd_nomem
16941    }
16942}
16943
16944#[no_mangle]
16945pub unsafe extern "C" fn thrd_join(thr: usize, res: *mut i32) -> i32 {
16946    let mut retval: *mut core::ffi::c_void = core::ptr::null_mut();
16947    let r = pthread_join(thr as u64, &mut retval);
16948    if r == 0 {
16949        if !res.is_null() { *res = retval as i32; }
16950        0
16951    } else {
16952        -1
16953    }
16954}
16955
16956#[no_mangle]
16957pub unsafe extern "C" fn thrd_exit(res: i32) {
16958    pthread_exit(res as *mut core::ffi::c_void);
16959}
16960
16961#[no_mangle]
16962pub unsafe extern "C" fn thrd_detach(thr: usize) -> i32 {
16963    let r = pthread_detach(thr as u64);
16964    if r == 0 { 0 } else { -1 }
16965}
16966
16967#[no_mangle]
16968pub unsafe extern "C" fn thrd_current() -> usize {
16969    pthread_self() as usize
16970}
16971
16972#[no_mangle]
16973pub unsafe extern "C" fn thrd_equal(thr1: usize, thr2: usize) -> i32 {
16974    (thr1 == thr2) as i32
16975}
16976
16977#[no_mangle]
16978pub unsafe extern "C" fn thrd_sleep(duration: *const core::ffi::c_void, remaining: *mut core::ffi::c_void) -> i32 {
16979    nanosleep(duration as *const timespec, remaining as *mut timespec)
16980}
16981
16982#[no_mangle]
16983pub unsafe extern "C" fn thrd_yield() {
16984    sched_yield();
16985}
16986
16987// Mutex
16988#[no_mangle]
16989pub unsafe extern "C" fn mtx_init(mtx: *mut usize, _mtx_type: i32) -> i32 {
16990    let r = pthread_mutex_init(mtx as *mut pthread_mutex_t, core::ptr::null());
16991    if r == 0 { 0 } else { -1 }
16992}
16993
16994#[no_mangle]
16995pub unsafe extern "C" fn mtx_lock(mtx: *mut usize) -> i32 {
16996    let r = pthread_mutex_lock(mtx as *mut pthread_mutex_t);
16997    if r == 0 { 0 } else { -1 }
16998}
16999
17000#[no_mangle]
17001pub unsafe extern "C" fn mtx_trylock(mtx: *mut usize) -> i32 {
17002    let r = pthread_mutex_trylock(mtx as *mut pthread_mutex_t);
17003    if r == 0 { 0 } else { -1 }
17004}
17005
17006#[no_mangle]
17007pub unsafe extern "C" fn mtx_unlock(mtx: *mut usize) -> i32 {
17008    let r = pthread_mutex_unlock(mtx as *mut pthread_mutex_t);
17009    if r == 0 { 0 } else { -1 }
17010}
17011
17012#[no_mangle]
17013pub unsafe extern "C" fn mtx_destroy(mtx: *mut usize) {
17014    pthread_mutex_destroy(mtx as *mut pthread_mutex_t);
17015}
17016
17017#[no_mangle]
17018pub unsafe extern "C" fn mtx_timedlock(mtx: *mut usize, ts: *const core::ffi::c_void) -> i32 {
17019    let r = pthread_mutex_timedlock(mtx as *mut pthread_mutex_t, ts as *const timespec);
17020    if r == 0 { 0 } else { -1 }
17021}
17022
17023// Condition variable
17024#[no_mangle]
17025pub unsafe extern "C" fn cnd_init(cnd: *mut usize) -> i32 {
17026    let r = pthread_cond_init(cnd as *mut pthread_cond_t, core::ptr::null());
17027    if r == 0 { 0 } else { -1 }
17028}
17029
17030#[no_mangle]
17031pub unsafe extern "C" fn cnd_signal(cnd: *mut usize) -> i32 {
17032    let r = pthread_cond_signal(cnd as *mut pthread_cond_t);
17033    if r == 0 { 0 } else { -1 }
17034}
17035
17036#[no_mangle]
17037pub unsafe extern "C" fn cnd_broadcast(cnd: *mut usize) -> i32 {
17038    let r = pthread_cond_broadcast(cnd as *mut pthread_cond_t);
17039    if r == 0 { 0 } else { -1 }
17040}
17041
17042#[no_mangle]
17043pub unsafe extern "C" fn cnd_wait(cnd: *mut usize, mtx: *mut usize) -> i32 {
17044    let r = pthread_cond_wait(cnd as *mut pthread_cond_t, mtx as *mut pthread_mutex_t);
17045    if r == 0 { 0 } else { -1 }
17046}
17047
17048#[no_mangle]
17049pub unsafe extern "C" fn cnd_timedwait(cnd: *mut usize, mtx: *mut usize, ts: *const core::ffi::c_void) -> i32 {
17050    let r = pthread_cond_timedwait(cnd as *mut pthread_cond_t, mtx as *mut pthread_mutex_t, ts as *const timespec);
17051    if r == 0 { 0 } else { -1 }
17052}
17053
17054#[no_mangle]
17055pub unsafe extern "C" fn cnd_destroy(cnd: *mut usize) {
17056    pthread_cond_destroy(cnd as *mut pthread_cond_t);
17057}
17058
17059// Thread-specific storage
17060#[no_mangle]
17061pub unsafe extern "C" fn tss_create(key: *mut u32, dtor: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>) -> i32 {
17062    let r = pthread_key_create(key, dtor);
17063    if r == 0 { 0 } else { -1 }
17064}
17065
17066#[no_mangle]
17067pub unsafe extern "C" fn tss_delete(key: u32) {
17068    pthread_key_delete(key);
17069}
17070
17071#[no_mangle]
17072pub unsafe extern "C" fn tss_set(key: u32, val: *mut core::ffi::c_void) -> i32 {
17073    let r = pthread_setspecific(key, val);
17074    if r == 0 { 0 } else { -1 }
17075}
17076
17077#[no_mangle]
17078pub unsafe extern "C" fn tss_get(key: u32) -> *mut core::ffi::c_void {
17079    pthread_getspecific(key)
17080}
17081
17082// call_once
17083#[no_mangle]
17084pub unsafe extern "C" fn call_once(flag: *mut u32, func: Option<unsafe extern "C" fn()>) {
17085    if flag.is_null() { return; }
17086    let state = &*(flag as *const AtomicU32);
17087    if state.load(Ordering::Acquire) == 2 { return; }
17088    if state.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).is_ok() {
17089        if let Some(f) = func { f(); }
17090        state.store(2, Ordering::Release);
17091    } else {
17092        while state.load(Ordering::Acquire) != 2 {
17093            core::hint::spin_loop();
17094        }
17095    }
17096}
17097
17098// ============================================================
17099// Network functions
17100// ============================================================
17101
17102// accept4 - Linux-specific extension
17103#[no_mangle]
17104pub unsafe extern "C" fn accept4(fd: i32, addr: *mut core::ffi::c_void, addrlen: *mut u32, flags: i32) -> i32 {
17105    syscall_ret(<Arch as Syscalls>::syscall4(SYS_ACCEPT4, fd as i64, addr as i64, addrlen as i64, flags as i64)) as i32
17106}
17107
17108// getifaddrs / freeifaddrs
17109// ============================================================
17110// epoll/eventfd/signalfd/timerfd
17111// ============================================================
17112
17113#[no_mangle]
17114pub unsafe extern "C" fn epoll_create(size: i32) -> i32 {
17115    #[cfg(target_arch = "x86_64")]
17116    { syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE, size as i64)) as i32 }
17117    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
17118    {
17119        if size < 1 {
17120            ERRNO!() = EINVAL;
17121            return -1;
17122        }
17123        syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE1, 0)) as i32
17124    }
17125}
17126
17127#[no_mangle]
17128pub unsafe extern "C" fn epoll_create1(flags: i32) -> i32 {
17129    syscall_ret(<Arch as Syscalls>::syscall1(SYS_EPOLL_CREATE1, flags as i64)) as i32
17130}
17131
17132#[no_mangle]
17133pub unsafe extern "C" fn epoll_ctl(epfd: i32, op: i32, fd: i32, event: *mut core::ffi::c_void) -> i32 {
17134    syscall_ret(<Arch as Syscalls>::syscall4(SYS_EPOLL_CTL, epfd as i64, op as i64, fd as i64, event as i64)) as i32
17135}
17136
17137#[no_mangle]
17138pub unsafe extern "C" fn epoll_wait(epfd: i32, events: *mut core::ffi::c_void, maxevents: i32, timeout: i32) -> i32 {
17139    #[cfg(target_arch = "x86_64")]
17140    {
17141        syscall_ret(<Arch as Syscalls>::syscall4(
17142            SYS_EPOLL_WAIT,
17143            epfd as i64,
17144            events as i64,
17145            maxevents as i64,
17146            timeout as i64,
17147        )) as i32
17148    }
17149    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
17150    {
17151        epoll_pwait(epfd, events, maxevents, timeout, core::ptr::null())
17152    }
17153}
17154
17155#[no_mangle]
17156pub unsafe extern "C" fn epoll_pwait(
17157    epfd: i32,
17158    events: *mut core::ffi::c_void,
17159    maxevents: i32,
17160    timeout: i32,
17161    sigmask: *const u64,
17162) -> i32 {
17163    syscall_ret(<Arch as Syscalls>::syscall6(
17164        SYS_EPOLL_PWAIT,
17165        epfd as i64,
17166        events as i64,
17167        maxevents as i64,
17168        timeout as i64,
17169        sigmask as i64,
17170        8,
17171    )) as i32
17172}
17173
17174#[no_mangle]
17175pub unsafe extern "C" fn eventfd(initval: u32, flags: i32) -> i32 {
17176    syscall_ret(<Arch as Syscalls>::syscall2(SYS_EVENTFD2, initval as i64, flags as i64)) as i32
17177}
17178
17179#[no_mangle]
17180pub unsafe extern "C" fn eventfd_read(fd: i32, value: *mut u64) -> i32 {
17181    let n = crate::read(fd, value as *mut core::ffi::c_void, 8);
17182    if n == 8 { 0 } else { -1 }
17183}
17184
17185#[no_mangle]
17186pub unsafe extern "C" fn eventfd_write(fd: i32, value: u64) -> i32 {
17187    let n = crate::write(fd, &value as *const u64 as *const core::ffi::c_void, 8);
17188    if n == 8 { 0 } else { -1 }
17189}
17190
17191#[no_mangle]
17192pub unsafe extern "C" fn signalfd(fd: i32, mask: *const u64, flags: i32) -> i32 {
17193    syscall_ret(<Arch as Syscalls>::syscall4(SYS_SIGNALFD4, fd as i64, mask as i64, 8, flags as i64)) as i32
17194}
17195
17196#[no_mangle]
17197pub unsafe extern "C" fn timerfd_create(clockid: i32, flags: i32) -> i32 {
17198    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMERFD_CREATE, clockid as i64, flags as i64)) as i32
17199}
17200
17201#[no_mangle]
17202pub 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 {
17203    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
17204}
17205
17206#[no_mangle]
17207pub unsafe extern "C" fn timerfd_gettime(fd: i32, curr_value: *mut core::ffi::c_void) -> i32 {
17208    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMERFD_GETTIME, fd as i64, curr_value as i64)) as i32
17209}
17210
17211// ============================================================
17212// System functions
17213// ============================================================
17214
17215#[no_mangle]
17216pub unsafe extern "C" fn prctl(option: i32, mut args: ...) -> i32 {
17217    let a1 = args.next_arg::<i64>();
17218    let a2 = args.next_arg::<i64>();
17219    let a3 = args.next_arg::<i64>();
17220    let a4 = args.next_arg::<i64>();
17221    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PRCTL, option as i64, a1, a2, a3, a4)) as i32
17222}
17223
17224#[no_mangle]
17225pub unsafe extern "C" fn quotactl(cmd: i32, special: *const core::ffi::c_char, id: i32, addr: *mut core::ffi::c_char) -> i32 {
17226    syscall_ret(<Arch as Syscalls>::syscall4(SYS_QUOTACTL, cmd as i64, special as i64, id as i64, addr as i64)) as i32
17227}
17228
17229#[no_mangle]
17230pub unsafe extern "C" fn klogctl(type_: i32, bufp: *mut core::ffi::c_char, len: i32) -> i32 {
17231    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SYSLOG, type_ as i64, bufp as i64, len as i64)) as i32
17232}
17233
17234static mut SYSLOG_IDENT: [core::ffi::c_char; 64] = [0; 64];
17235static mut SYSLOG_OPTIONS: i32 = 0;
17236static mut SYSLOG_FACILITY: i32 = 1;
17237const SYSLOG_FACILITY_MASK: i32 = 0x3f8;
17238
17239#[no_mangle]
17240pub unsafe extern "C" fn openlog(ident: *const core::ffi::c_char, option: i32, facility: i32) {
17241    SYSLOG_OPTIONS = option;
17242    SYSLOG_FACILITY = facility & SYSLOG_FACILITY_MASK;
17243    SYSLOG_IDENT[0] = 0;
17244    if !ident.is_null() {
17245        let mut i = 0;
17246        while i < 63 && *ident.add(i) != 0 {
17247            SYSLOG_IDENT[i] = *ident.add(i);
17248            i += 1;
17249        }
17250        SYSLOG_IDENT[i] = 0;
17251    }
17252}
17253
17254#[repr(C)]
17255struct SockAddrUn {
17256    sun_family: u16,
17257    sun_path: [core::ffi::c_char; 108],
17258}
17259
17260unsafe fn syslog_emit(priority: i32, msg: *const core::ffi::c_char, len: usize) {
17261    let mut out = [0u8; 1200];
17262    let mut o = 0usize;
17263    let pri = (SYSLOG_FACILITY | (priority & 7)) as u32;
17264    out[o] = b'<'; o += 1;
17265    if pri >= 100 { out[o] = b'0' + (pri / 100) as u8; o += 1; }
17266    if pri >= 10 { out[o] = b'0' + ((pri / 10) % 10) as u8; o += 1; }
17267    out[o] = b'0' + (pri % 10) as u8; o += 1;
17268    out[o] = b'>'; o += 1;
17269    let mut i = 0;
17270    while i < 63 && SYSLOG_IDENT[i] != 0 && o + 1 < out.len() {
17271        out[o] = SYSLOG_IDENT[i] as u8; o += 1; i += 1;
17272    }
17273    if SYSLOG_OPTIONS & 1 != 0 {
17274        out[o] = b'['; o += 1;
17275        let mut pid = crate::getpid() as u32;
17276        let mut digits = [0u8; 10];
17277        let mut d = 0;
17278        if pid == 0 { digits[0] = b'0'; d = 1; }
17279        while pid > 0 { digits[d] = b'0' + (pid % 10) as u8; pid /= 10; d += 1; }
17280        while d > 0 { d -= 1; out[o] = digits[d]; o += 1; }
17281        out[o] = b']'; o += 1;
17282    }
17283    out[o] = b':'; o += 1; out[o] = b' '; o += 1;
17284    let copy = core::cmp::min(len, out.len() - o - 1);
17285    core::ptr::copy_nonoverlapping(msg as *const u8, out.as_mut_ptr().add(o), copy);
17286    o += copy;
17287    let fd = crate::socket(AF_UNIX, SOCK_DGRAM, 0);
17288    if fd >= 0 {
17289        let mut sa: SockAddrUn = core::mem::zeroed();
17290        sa.sun_family = AF_UNIX as u16;
17291        let path = b"/dev/log";
17292        for i in 0..path.len() { sa.sun_path[i] = path[i] as core::ffi::c_char; }
17293        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);
17294        crate::close(fd);
17295        if r >= 0 { return; }
17296    }
17297    crate::write(2, out.as_ptr() as *const core::ffi::c_void, o);
17298    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
17299}
17300
17301#[no_mangle]
17302pub unsafe extern "C" fn vsyslog(priority: c_int, fmt: *const c_char, ap: VaList) {
17303    let mut msg = [0 as c_char; 1024];
17304    let n = vsnprintf(msg.as_mut_ptr(), msg.len(), fmt, ap);
17305    if n > 0 { syslog_emit(priority, msg.as_ptr(), core::cmp::min(n as usize, msg.len() - 1)); }
17306}
17307
17308#[no_mangle]
17309pub unsafe extern "C" fn syslog(priority: c_int, fmt: *const c_char, args: ...) {
17310    vsyslog(priority, fmt, args);
17311}
17312
17313#[no_mangle]
17314pub unsafe extern "C" fn closelog() {
17315    // Nothing to do
17316}
17317
17318#[no_mangle]
17319pub unsafe extern "C" fn setlogmask(mask: i32) -> i32 {
17320    static mut LOG_MASK: i32 = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80;
17321    let old = LOG_MASK;
17322    if mask != 0 { LOG_MASK = mask; }
17323    old
17324}
17325
17326#[no_mangle]
17327pub unsafe extern "C" fn acct(filename: *const core::ffi::c_char) -> i32 {
17328    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ACCT, filename as i64)) as i32
17329}
17330
17331#[no_mangle]
17332pub unsafe extern "C" fn swapon(path: *const core::ffi::c_char, flags: i32) -> i32 {
17333    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SWAPON, path as i64, flags as i64)) as i32
17334}
17335
17336#[no_mangle]
17337pub unsafe extern "C" fn swapoff(path: *const core::ffi::c_char) -> i32 {
17338    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SWAPOFF, path as i64)) as i32
17339}
17340
17341#[no_mangle]
17342pub unsafe extern "C" fn syncfs(fd: i32) -> i32 {
17343    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SYNCFS, fd as i64)) as i32
17344}
17345
17346#[no_mangle]
17347pub unsafe extern "C" fn sync_file_range(fd: i32, offset: i64, nbytes: u64, flags: u32) -> i32 {
17348    syscall_ret(<Arch as Syscalls>::syscall4(SYS_SYNC_FILE_RANGE, fd as i64, offset, nbytes as i64, flags as i64)) as i32
17349}
17350
17351#[no_mangle]
17352pub unsafe extern "C" fn posix_fadvise(fd: i32, offset: i64, len: u64, advice: i32) -> i32 {
17353    // POSIX returns the error number directly, not -1/errno.
17354    let r = <Arch as Syscalls>::syscall4(SYS_FADVISE64, fd as i64, offset, len as i64, advice as i64);
17355    if r < 0 { (-r) as i32 } else { 0 }
17356}
17357
17358#[no_mangle]
17359pub unsafe extern "C" fn posix_fallocate(fd: i32, offset: i64, len: u64) -> i32 {
17360    let r = <Arch as Syscalls>::syscall3(SYS_FALLOCATE, fd as i64, offset, len as i64);
17361    if r < 0 { (-r) as i32 } else { 0 }
17362}
17363
17364#[no_mangle]
17365pub unsafe extern "C" fn readahead(fd: i32, offset: i64, count: usize) -> isize {
17366    // musl declares readahead() as ssize_t; returning int leaves the upper
17367    // half of rax undefined for callers that expect a 64-bit result.
17368    syscall_ret(<Arch as Syscalls>::syscall3(SYS_READAHEAD, fd as i64, offset, count as i64)) as isize
17369}
17370
17371#[no_mangle]
17372pub unsafe extern "C" fn fallocate(fd: i32, mode: i32, offset: i64, len: u64) -> i32 {
17373    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FALLOCATE, fd as i64, mode as i64, offset, len as i64)) as i32
17374}
17375
17376// ============================================================
17377// Terminal functions
17378// ============================================================
17379
17380#[no_mangle]
17381pub unsafe extern "C" fn tcgetattr(fd: i32, termios_p: *mut core::ffi::c_void) -> i32 {
17382    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5401, termios_p as i64)) as i32
17383}
17384
17385#[no_mangle]
17386pub unsafe extern "C" fn tcsetattr(fd: i32, optional_actions: i32, termios_p: *const core::ffi::c_void) -> i32 {
17387    let cmd = match optional_actions {
17388        0 => 0x5402,
17389        1 => 0x5403,
17390        2 => 0x5404,
17391        _ => 0x5402,
17392    };
17393    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, cmd, termios_p as i64)) as i32
17394}
17395
17396#[no_mangle]
17397pub unsafe extern "C" fn tcdrain(fd: i32) -> i32 {
17398    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5409, 1)) as i32
17399}
17400
17401#[no_mangle]
17402pub unsafe extern "C" fn tcflush(fd: i32, queue_selector: i32) -> i32 {
17403    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540B, queue_selector as i64)) as i32
17404}
17405
17406#[no_mangle]
17407pub unsafe extern "C" fn tcflow(fd: i32, action: i32) -> i32 {
17408    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540A, action as i64)) as i32
17409}
17410
17411#[no_mangle]
17412pub unsafe extern "C" fn tcsendbreak(fd: i32, duration: i32) -> i32 {
17413    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5425, duration as i64)) as i32
17414}
17415
17416#[no_mangle]
17417pub unsafe extern "C" fn tcgetsid(fd: i32) -> i32 {
17418    let mut sid: i32 = 0;
17419    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5429, &mut sid as *mut i32 as i64);
17420    if r < 0 { -1 } else { sid }
17421}
17422
17423#[no_mangle]
17424pub unsafe extern "C" fn tcgetpgrp(fd: i32) -> i32 {
17425    let mut pgrp: i32 = 0;
17426    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x540F, &mut pgrp as *mut i32 as i64);
17427    if r < 0 { -1 } else { pgrp }
17428}
17429
17430#[no_mangle]
17431pub unsafe extern "C" fn tcsetpgrp(fd: i32, pgrp: i32) -> i32 {
17432    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5410, &pgrp as *const i32 as i64)) as i32
17433}
17434
17435// ============================================================
17436// Memory locking functions
17437// ============================================================
17438
17439// ============================================================
17440
17441// ============================================================
17442// POSIX message queue functions
17443// ============================================================
17444
17445#[no_mangle]
17446pub unsafe extern "C" fn mq_open(name: *const core::ffi::c_char, oflag: i32, mut args: ...) -> i32 {
17447    if name.is_null() { ERRNO!() = EINVAL; return -1; }
17448    let mut p = name as *const u8;
17449    if *p == b'/' { p = p.add(1); }
17450    let mut mode: u32 = 0;
17451    let mut attr: *const core::ffi::c_void = core::ptr::null();
17452    if oflag & 0o100 != 0 {
17453        mode = args.next_arg::<u32>();
17454        attr = args.next_arg::<*const core::ffi::c_void>();
17455    }
17456    syscall_ret(<Arch as Syscalls>::syscall4(
17457        SYS_MQ_OPEN,
17458        p as i64,
17459        oflag as i64,
17460        mode as i64,
17461        attr as i64,
17462    )) as i32
17463}
17464
17465#[no_mangle]
17466pub unsafe extern "C" fn mq_close(mqdes: i32) -> i32 {
17467    crate::close(mqdes as i32)
17468}
17469
17470#[no_mangle]
17471pub unsafe extern "C" fn mq_unlink(name: *const core::ffi::c_char) -> i32 {
17472    if name.is_null() { ERRNO!() = EINVAL; return -1; }
17473    let mut p = name as *const u8;
17474    if *p == b'/' { p = p.add(1); }
17475    let r = <Arch as Syscalls>::syscall1(SYS_MQ_UNLINK, p as i64);
17476    if r < 0 {
17477        // The kernel reports EPERM for an unlink while the queue is open.
17478        let e = if (-r) as c_int == 1 { 13 } else { (-r) as c_int };
17479        ERRNO!() = e;
17480        -1
17481    } else {
17482        0
17483    }
17484}
17485
17486#[no_mangle]
17487pub unsafe extern "C" fn mq_send(mqdes: i32, msg_ptr: *const core::ffi::c_char, msg_len: usize, msg_prio: u32) -> i32 {
17488    mq_timedsend(mqdes, msg_ptr, msg_len, msg_prio, core::ptr::null())
17489}
17490
17491#[no_mangle]
17492pub unsafe extern "C" fn mq_receive(mqdes: i32, msg_ptr: *mut core::ffi::c_char, msg_len: usize, msg_prio: *mut u32) -> isize {
17493    mq_timedreceive(mqdes, msg_ptr, msg_len, msg_prio, core::ptr::null())
17494}
17495
17496#[no_mangle]
17497pub unsafe extern "C" fn mq_timedsend(
17498    mqdes: i32,
17499    msg_ptr: *const core::ffi::c_char,
17500    msg_len: usize,
17501    msg_prio: u32,
17502    abs_timeout: *const core::ffi::c_void,
17503) -> i32 {
17504    syscall_ret(<Arch as Syscalls>::syscall5(
17505        SYS_MQ_TIMEDSEND,
17506        mqdes as i64,
17507        msg_ptr as i64,
17508        msg_len as i64,
17509        msg_prio as i64,
17510        abs_timeout as i64,
17511    )) as i32
17512}
17513
17514#[no_mangle]
17515pub unsafe extern "C" fn mq_timedreceive(
17516    mqdes: i32,
17517    msg_ptr: *mut core::ffi::c_char,
17518    msg_len: usize,
17519    msg_prio: *mut u32,
17520    abs_timeout: *const core::ffi::c_void,
17521) -> isize {
17522    syscall_ret(<Arch as Syscalls>::syscall5(
17523        SYS_MQ_TIMEDRECEIVE,
17524        mqdes as i64,
17525        msg_ptr as i64,
17526        msg_len as i64,
17527        msg_prio as i64,
17528        abs_timeout as i64,
17529    )) as isize
17530}
17531
17532#[repr(C)]
17533pub struct SigEventFull {
17534    sigev_value: usize,
17535    sigev_signo: i32,
17536    sigev_notify: i32,
17537    sigev_function: usize,
17538    sigev_attributes: usize,
17539    sigev_pad: [u8; 32],
17540}
17541
17542struct MqNotifyArgs {
17543    sem: sem_t,
17544    sock: i32,
17545    mqd: i32,
17546    err: i32,
17547    func: usize,
17548    value: usize,
17549}
17550
17551unsafe extern "C" fn mq_notify_thread(arg: *mut c_void) -> *mut c_void {
17552    let a = &mut *(arg as *mut MqNotifyArgs);
17553    let sock = a.sock;
17554    let mqd = a.mqd;
17555    let func = a.func;
17556    let value = a.value;
17557    let zeros = [0u8; 32];
17558    let sev2 = SigEventFull {
17559        sigev_value: zeros.as_ptr() as usize,
17560        sigev_signo: sock,
17561        sigev_notify: 2, // SIGEV_THREAD, consumed by the kernel as a netlink fd
17562        sigev_function: 0,
17563        sigev_attributes: 0,
17564        sigev_pad: [0; 32],
17565    };
17566    let r = <Arch as Syscalls>::syscall2(SYS_MQ_NOTIFY, mqd as i64, &sev2 as *const SigEventFull as i64);
17567    a.err = if r < 0 { (-r) as i32 } else { 0 };
17568    sem_post(&mut a.sem);
17569    if a.err != 0 { return core::ptr::null_mut(); }
17570    pthread_detach(pthread_self());
17571    let mut buf = [0u8; 32];
17572    let n = recv(sock, buf.as_mut_ptr() as *mut c_void, buf.len(), 0x4000 | 0x100);
17573    crate::close(sock);
17574    if n as usize == buf.len() && buf[buf.len() - 1] == 1 && func != 0 {
17575        let f: extern "C" fn(usize) = core::mem::transmute(func);
17576        f(value);
17577    }
17578    core::ptr::null_mut()
17579}
17580
17581#[no_mangle]
17582pub unsafe extern "C" fn mq_notify(mqdes: i32, sev: *const core::ffi::c_void) -> i32 {
17583    if sev.is_null() {
17584        return syscall_ret(<Arch as Syscalls>::syscall2(SYS_MQ_NOTIFY, mqdes as i64, 0)) as i32;
17585    }
17586    let ev = &*(sev as *const SigEventFull);
17587    if ev.sigev_notify != 2 {
17588        return syscall_ret(<Arch as Syscalls>::syscall2(SYS_MQ_NOTIFY, mqdes as i64, sev as i64)) as i32;
17589    }
17590
17591    // SIGEV_THREAD is emulated with a netlink socket and a helper thread,
17592    // matching musl. The kernel only deals with the socket.
17593    let sock = socket(16 /* AF_NETLINK */, 3 | 0x80000 /* SOCK_RAW|SOCK_CLOEXEC */, 0);
17594    if sock < 0 { return -1; }
17595    let mut a = MqNotifyArgs {
17596        sem: core::mem::zeroed(),
17597        sock,
17598        mqd: mqdes,
17599        err: 0,
17600        func: ev.sigev_function,
17601        value: ev.sigev_value,
17602    };
17603    sem_init(&mut a.sem, 0, 0);
17604
17605    let mut attr: pthread_attr_t = core::mem::zeroed();
17606    if ev.sigev_attributes != 0 {
17607        attr = core::ptr::read(ev.sigev_attributes as *const pthread_attr_t);
17608    } else {
17609        pthread_attr_init(&mut attr);
17610    }
17611    pthread_attr_setdetachstate(&mut attr, PTHREAD_CREATE_JOINABLE);
17612
17613    let mut all: SigSetT = 0;
17614    sigfillset(&mut all);
17615    let mut orig: SigSetT = 0;
17616    pthread_sigmask(0 /* SIG_BLOCK */, &all, &mut orig);
17617
17618    let mut td: PthreadT = 0;
17619    let r = pthread_create(&mut td, &attr, mq_notify_thread as *const () as usize, &mut a as *mut MqNotifyArgs as *mut c_void);
17620    pthread_sigmask(2 /* SIG_SETMASK */, &orig, core::ptr::null_mut());
17621    if r != 0 {
17622        crate::close(sock);
17623        ERRNO!() = EAGAIN;
17624        return -1;
17625    }
17626    sem_wait(&mut a.sem);
17627    sem_destroy(&mut a.sem);
17628    if a.err != 0 {
17629        crate::close(sock);
17630        pthread_join(td, core::ptr::null_mut());
17631        ERRNO!() = a.err;
17632        return -1;
17633    }
17634    0
17635}
17636
17637#[no_mangle]
17638pub unsafe extern "C" fn mq_getattr(mqdes: i32, attr: *mut core::ffi::c_void) -> i32 {
17639    mq_setattr(mqdes, core::ptr::null(), attr)
17640}
17641
17642#[no_mangle]
17643pub unsafe extern "C" fn mq_setattr(
17644    mqdes: i32,
17645    new: *const core::ffi::c_void,
17646    old: *mut core::ffi::c_void,
17647) -> i32 {
17648    syscall_ret(<Arch as Syscalls>::syscall3(
17649        SYS_MQ_GETSETATTR,
17650        mqdes as i64,
17651        new as i64,
17652        old as i64,
17653    )) as i32
17654}
17655
17656// ============================================================
17657// pthread functions
17658// ============================================================
17659
17660#[no_mangle]
17661pub unsafe extern "C" fn pthread_getaffinity_np(thread: usize, cpusetsize: usize, cpuset: *mut u8) -> i32 {
17662    sched_getaffinity(thread as i32, cpusetsize, cpuset)
17663}
17664
17665#[no_mangle]
17666pub unsafe extern "C" fn pthread_setaffinity_np(thread: usize, cpusetsize: usize, cpuset: *const u8) -> i32 {
17667    sched_setaffinity(thread as i32, cpusetsize, cpuset)
17668}
17669
17670// ============================================================
17671// sched functions
17672// ============================================================
17673
17674#[no_mangle]
17675pub unsafe extern "C" fn sched_yield() -> i32 {
17676    syscall_ret(<Arch as Syscalls>::syscall0(SYS_SCHED_YIELD)) as i32
17677}
17678
17679#[no_mangle]
17680pub unsafe extern "C" fn sched_get_priority_max(policy: i32) -> i32 {
17681    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SCHED_GET_PRIORITY_MAX, policy as i64)) as i32
17682}
17683
17684#[no_mangle]
17685pub unsafe extern "C" fn sched_get_priority_min(policy: i32) -> i32 {
17686    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SCHED_GET_PRIORITY_MIN, policy as i64)) as i32
17687}
17688
17689#[no_mangle]
17690pub unsafe extern "C" fn sched_getparam(pid: i32, param: *mut core::ffi::c_void) -> i32 {
17691    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SCHED_GETPARAM, pid as i64, param as i64)) as i32
17692}
17693
17694#[no_mangle]
17695pub unsafe extern "C" fn sched_setparam(pid: i32, param: *const core::ffi::c_void) -> i32 {
17696    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SCHED_SETPARAM, pid as i64, param as i64)) as i32
17697}
17698
17699#[no_mangle]
17700pub unsafe extern "C" fn sched_getscheduler(pid: i32) -> i32 {
17701    syscall_ret(<Arch as Syscalls>::syscall1(SYS_SCHED_GETSCHEDULER, pid as i64)) as i32
17702}
17703
17704#[no_mangle]
17705pub unsafe extern "C" fn sched_setscheduler(pid: i32, policy: i32, param: *const core::ffi::c_void) -> i32 {
17706    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SCHED_SETSCHEDULER, pid as i64, policy as i64, param as i64)) as i32
17707}
17708
17709#[no_mangle]
17710pub unsafe extern "C" fn sched_setaffinity(pid: i32, cpusetsize: usize, cpuset: *const u8) -> i32 {
17711    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SCHED_SETAFFINITY, pid as i64, cpusetsize as i64, cpuset as i64)) as i32
17712}
17713
17714#[no_mangle]
17715pub unsafe extern "C" fn sched_getaffinity(pid: i32, cpusetsize: usize, cpuset: *mut u8) -> i32 {
17716    let r = <Arch as Syscalls>::syscall3(SYS_SCHED_GETAFFINITY, pid as i64, cpusetsize as i64, cpuset as i64);
17717    if r < 0 {
17718        ERRNO!() = (-r) as c_int;
17719        return -1;
17720    }
17721    // The kernel returns the number of bytes copied, not 0.
17722    0
17723}
17724
17725#[cold]
17726unsafe fn sched_getcpu_syscall(cpu: *mut u32) -> i32 {
17727    let r = <Arch as Syscalls>::syscall3(SYS_GETCPU, cpu as i64, 0, 0);
17728    if r == 0 {
17729        core::ptr::read_unaligned(cpu) as i32
17730    } else {
17731        syscall_ret(r) as i32
17732    }
17733}
17734
17735#[no_mangle]
17736pub unsafe extern "C" fn sched_getcpu() -> i32 {
17737    // Both the vDSO and the syscall fill the slot on success.  A 16-byte
17738    // scratch area keeps the write away from the return address; a 4-byte
17739    // slot overlaps the compiler's push and triggers a store-forwarding
17740    // stall on the vDSO write (measured ~2.5 ns).
17741    let mut cpu = core::mem::MaybeUninit::<[u64; 2]>::uninit();
17742    let cpu_ptr = cpu.as_mut_ptr() as *mut u32;
17743    if vdso_getcpu(cpu_ptr) {
17744        return core::ptr::read_unaligned(cpu_ptr) as i32;
17745    }
17746    sched_getcpu_syscall(cpu_ptr)
17747}
17748
17749#[no_mangle]
17750pub unsafe extern "C" fn sched_rr_get_interval(pid: i32, tp: *mut core::ffi::c_void) -> i32 {
17751    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SCHED_RR_GET_INTERVAL, pid as i64, tp as i64)) as i32
17752}
17753
17754// ============================================================
17755// timer/clock functions
17756// ============================================================
17757
17758#[no_mangle]
17759pub unsafe extern "C" fn timer_create(clockid: i32, sevp: *mut core::ffi::c_void, timerid: *mut i32) -> i32 {
17760    syscall_ret(<Arch as Syscalls>::syscall3(SYS_TIMER_CREATE, clockid as i64, sevp as i64, timerid as i64)) as i32
17761}
17762
17763#[no_mangle]
17764pub unsafe extern "C" fn timer_delete(timerid: i32) -> i32 {
17765    syscall_ret(<Arch as Syscalls>::syscall1(SYS_TIMER_DELETE, timerid as i64)) as i32
17766}
17767
17768#[no_mangle]
17769pub 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 {
17770    syscall_ret(<Arch as Syscalls>::syscall4(SYS_TIMER_SETTIME, timerid as i64, flags as i64, new_value as i64, old_value as i64)) as i32
17771}
17772
17773#[no_mangle]
17774pub unsafe extern "C" fn timer_gettime(timerid: i32, curr_value: *mut core::ffi::c_void) -> i32 {
17775    syscall_ret(<Arch as Syscalls>::syscall2(SYS_TIMER_GETTIME, timerid as i64, curr_value as i64)) as i32
17776}
17777
17778#[no_mangle]
17779pub unsafe extern "C" fn timer_getoverrun(timerid: i32) -> i32 {
17780    syscall_ret(<Arch as Syscalls>::syscall1(SYS_TIMER_GETOVERRUN, timerid as i64)) as i32
17781}
17782
17783#[no_mangle]
17784pub unsafe extern "C" fn clock_adjtime(_clockid: i32, buf: *mut core::ffi::c_void) -> i32 {
17785    syscall_ret(<Arch as Syscalls>::syscall2(SYS_ADJTIMEX, buf as i64, 0)) as i32
17786}
17787
17788#[no_mangle]
17789pub unsafe extern "C" fn clock_getcpuclockid(pid: i32, clockid: *mut i32) -> i32 {
17790    if clockid.is_null() { return EINVAL; }
17791    let id: i32 = ((-(pid as i64) - 1) * 8 + 2) as i32;
17792    let mut ts: timespec = core::mem::zeroed();
17793    let r = <Arch as Syscalls>::syscall2(SYS_CLOCK_GETRES, id as i64, &mut ts as *mut timespec as i64);
17794    if r < 0 {
17795        let e = (-r) as c_int;
17796        return if e == EINVAL { 3 } else { e };
17797    }
17798    *clockid = id;
17799    0
17800}
17801
17802// ============================================================
17803// String functions
17804// ============================================================
17805
17806#[no_mangle]
17807pub unsafe extern "C" fn strcoll(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> i32 {
17808    // musl's C locale compares byte strings directly (strcmp semantics).
17809    let mut i = 0;
17810    loop {
17811        let c1 = *s1.add(i) as u8;
17812        let c2 = *s2.add(i) as u8;
17813        if c1 == 0 || c2 == 0 { return (c1 as i32) - (c2 as i32); }
17814        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
17815        i += 1;
17816    }
17817}
17818
17819#[no_mangle]
17820pub unsafe extern "C" fn strxfrm(dest: *mut core::ffi::c_char, src: *const core::ffi::c_char, n: usize) -> usize {
17821    let mut i = 0;
17822    while i < n {
17823        let c = *src.add(i);
17824        *dest.add(i) = c;
17825        if c == 0 { break; }
17826        i += 1;
17827    }
17828    i
17829}
17830
17831// ============================================================
17832// Directory functions
17833// ============================================================
17834
17835#[no_mangle]
17836pub unsafe extern "C" fn scandir(
17837    dirp: *const core::ffi::c_char,
17838    namelist: *mut *mut *mut core::ffi::c_void,
17839    filter: Option<unsafe extern "C" fn(*const core::ffi::c_void) -> i32>,
17840    compar: Option<unsafe extern "C" fn(*const core::ffi::c_void, *const core::ffi::c_void) -> i32>,
17841) -> c_int {
17842    if dirp.is_null() || namelist.is_null() {
17843        ERRNO!() = EINVAL;
17844        return -1;
17845    }
17846    *namelist = core::ptr::null_mut();
17847    let dir = opendir(dirp);
17848    if dir.is_null() { return -1; }
17849
17850    let mut cap = 16usize;
17851    let mut count = 0usize;
17852    let mut list = crate::malloc(cap * core::mem::size_of::<*mut c_void>()) as *mut *mut c_void;
17853    if list.is_null() { closedir(dir); ERRNO!() = ENOMEM; return -1; }
17854
17855    loop {
17856        let ent = readdir(dir);
17857        if ent.is_null() { break; }
17858        if let Some(filter) = filter {
17859            if filter(ent as *const c_void) == 0 { continue; }
17860        }
17861        if count == cap {
17862            let new_cap = match cap.checked_mul(2) {
17863                Some(n) => n,
17864                None => {
17865                    for i in 0..count { crate::free(*list.add(i)); }
17866                    crate::free(list as *mut c_void);
17867                    closedir(dir);
17868                    ERRNO!() = ENOMEM;
17869                    return -1;
17870                }
17871            };
17872            let p = crate::realloc(
17873                list as *mut c_void,
17874                new_cap * core::mem::size_of::<*mut c_void>(),
17875            ) as *mut *mut c_void;
17876            if p.is_null() {
17877                for i in 0..count { crate::free(*list.add(i)); }
17878                crate::free(list as *mut c_void);
17879                closedir(dir);
17880                ERRNO!() = ENOMEM;
17881                return -1;
17882            }
17883            list = p;
17884            cap = new_cap;
17885        }
17886        let name = (ent as *const u8).add(core::mem::offset_of!(linux_dirent64, d_name))
17887            as *const core::ffi::c_char;
17888        let copy = crate::strdup(name);
17889        if copy.is_null() {
17890            for i in 0..count { crate::free(*list.add(i)); }
17891            crate::free(list as *mut c_void);
17892            closedir(dir);
17893            ERRNO!() = ENOMEM;
17894            return -1;
17895        }
17896        *list.add(count) = copy as *mut c_void;
17897        count += 1;
17898    }
17899    closedir(dir);
17900
17901    if let Some(compar) = compar {
17902        if count > 1 {
17903            qsort(
17904                list as *mut c_void,
17905                count,
17906                core::mem::size_of::<*mut c_void>(),
17907                compar,
17908            );
17909        }
17910    }
17911    *namelist = list;
17912    count as c_int
17913}
17914
17915#[no_mangle]
17916pub unsafe extern "C" fn alphasort(a: *const *const core::ffi::c_void, b: *const *const core::ffi::c_void) -> i32 {
17917    let s1 = *a as *const core::ffi::c_char;
17918    let s2 = *b as *const core::ffi::c_char;
17919    crate::strcmp(s1 as *const u8, s2 as *const u8)
17920}
17921
17922#[no_mangle]
17923pub unsafe extern "C" fn versionsort(a: *const *const core::ffi::c_void, b: *const *const core::ffi::c_void) -> i32 {
17924    let s1 = *a as *const core::ffi::c_char;
17925    let s2 = *b as *const core::ffi::c_char;
17926    crate::strcmp(s1 as *const u8, s2 as *const u8)
17927}
17928
17929// ============================================================
17930
17931
17932// ============================================================
17933// err functions
17934// ============================================================
17935
17936unsafe fn vwarn_impl(fmt: *const c_char, ap: VaList, with_errno: bool) {
17937    let mut buf = [0 as c_char; 1024];
17938    let n = vsnprintf(buf.as_mut_ptr(), buf.len(), fmt, ap);
17939    if n > 0 {
17940        let l = core::cmp::min(n as usize, buf.len() - 1);
17941        crate::write(2, buf.as_ptr() as *const c_void, l);
17942    }
17943    if with_errno {
17944        let e = ERRNO!();
17945        crate::write(2, b": ".as_ptr() as *const c_void, 2);
17946        let msg = strerror(e);
17947        crate::write(2, msg as *const c_void, crate::strlen(msg));
17948    }
17949    crate::write(2, b"\n".as_ptr() as *const c_void, 1);
17950}
17951
17952#[no_mangle]
17953pub unsafe extern "C" fn verr(eval: c_int, fmt: *const c_char, ap: VaList) {
17954    vwarn_impl(fmt, ap, true);
17955    crate::exit(eval);
17956}
17957
17958#[no_mangle]
17959pub unsafe extern "C" fn verrx(eval: c_int, fmt: *const c_char, ap: VaList) {
17960    vwarn_impl(fmt, ap, false);
17961    crate::exit(eval);
17962}
17963
17964#[no_mangle]
17965pub unsafe extern "C" fn vwarn(fmt: *const c_char, ap: VaList) {
17966    vwarn_impl(fmt, ap, true);
17967}
17968
17969#[no_mangle]
17970pub unsafe extern "C" fn vwarnx(fmt: *const c_char, ap: VaList) {
17971    vwarn_impl(fmt, ap, false);
17972}
17973
17974#[no_mangle]
17975pub unsafe extern "C" fn err(eval: c_int, fmt: *const c_char, args: ...) {
17976    verr(eval, fmt, args);
17977}
17978
17979#[no_mangle]
17980pub unsafe extern "C" fn errx(eval: c_int, fmt: *const c_char, args: ...) {
17981    verrx(eval, fmt, args);
17982}
17983
17984#[no_mangle]
17985pub unsafe extern "C" fn warn(fmt: *const c_char, args: ...) {
17986    vwarn(fmt, args);
17987}
17988
17989#[no_mangle]
17990pub unsafe extern "C" fn warnx(fmt: *const c_char, args: ...) {
17991    vwarnx(fmt, args);
17992}
17993
17994// ============================================================
17995// ecvt functions
17996// ============================================================
17997
17998#[no_mangle]
17999pub unsafe extern "C" fn ecvt(value: f64, ndigit: i32, decpt: *mut i32, sign: *mut i32) -> *mut core::ffi::c_char {
18000    static mut BUF: [core::ffi::c_char; 80] = [0; 80];
18001    if value < 0.0 { *sign = 1; } else { *sign = 0; }
18002    let v = if value < 0.0 { -value } else { value };
18003    if v == 0.0 { *decpt = 0; BUF[0] = 0; return BUF.as_mut_ptr(); }
18004    let mut d = 0i32;
18005    let mut tmp = v;
18006    while tmp >= 10.0 { tmp /= 10.0; d += 1; }
18007    while tmp < 1.0 { tmp *= 10.0; d -= 1; }
18008    *decpt = d + 1;
18009    let mut i = 0;
18010    let mut val = tmp;
18011    while i < ndigit as usize && i < 79 {
18012        let digit = val as i32;
18013        BUF[i] = (b'0' + digit as u8) as c_char;
18014        val = (val - digit as f64) * 10.0;
18015        i += 1;
18016    }
18017    BUF[i] = 0;
18018    BUF.as_mut_ptr()
18019}
18020
18021#[no_mangle]
18022pub unsafe extern "C" fn fcvt(value: f64, ndigit: i32, decpt: *mut i32, sign: *mut i32) -> *mut core::ffi::c_char {
18023    static mut BUF: [core::ffi::c_char; 80] = [0; 80];
18024    if value < 0.0 { *sign = 1; } else { *sign = 0; }
18025    let v = if value < 0.0 { -value } else { value };
18026    if v == 0.0 { *decpt = 0; BUF[0] = 0; return BUF.as_mut_ptr(); }
18027    let mut d = 0i32;
18028    let mut tmp = v;
18029    while tmp >= 10.0 { tmp /= 10.0; d += 1; }
18030    while tmp < 1.0 { tmp *= 10.0; d -= 1; }
18031    *decpt = d + 1;
18032    let mut val = tmp;
18033    let mut i = 0;
18034    while i < (*decpt) as usize && i < 79 {
18035        let digit = val as i32;
18036        BUF[i] = (b'0' + digit as u8) as c_char;
18037        val = (val - digit as f64) * 10.0;
18038        i += 1;
18039    }
18040    if ndigit > 0 && i < 79 {
18041        BUF[i] = '.' as c_char;
18042        i += 1;
18043        let mut frac = val;
18044        let mut j = 0;
18045        while j < ndigit as usize && i < 79 {
18046            let digit = frac as i32;
18047            BUF[i] = (b'0' + digit as u8) as c_char;
18048            frac = (frac - digit as f64) * 10.0;
18049            i += 1;
18050            j += 1;
18051        }
18052    }
18053    BUF[i] = 0;
18054    BUF.as_mut_ptr()
18055}
18056
18057#[no_mangle]
18058pub unsafe extern "C" fn gcvt(value: f64, ndigit: i32, buf: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
18059    if buf.is_null() {
18060        return buf;
18061    }
18062    // musl implements gcvt as sprintf("%.*g"); cap the write at a size that
18063    // always covers %g's output for the requested precision.
18064    let cap = if ndigit > 0 {
18065        (ndigit as usize).saturating_mul(2).saturating_add(32).min(4096)
18066    } else {
18067        32
18068    };
18069    crate::snprintf(buf, cap, b"%.*g\0".as_ptr() as *const core::ffi::c_char, ndigit, value);
18070    buf
18071}
18072
18073// ============================================================
18074// usershell functions
18075// ============================================================
18076
18077static mut SHELLS: [*const core::ffi::c_char; 3] = [
18078    b"/bin/sh\0".as_ptr() as *const core::ffi::c_char,
18079    b"/bin/bash\0".as_ptr() as *const core::ffi::c_char,
18080    core::ptr::null(),
18081];
18082static mut SHELL_IDX: usize = 0;
18083
18084#[no_mangle]
18085pub unsafe extern "C" fn getusershell() -> *mut core::ffi::c_char {
18086    let s = SHELLS[SHELL_IDX];
18087    if s.is_null() {
18088        SHELL_IDX = 0;
18089        return core::ptr::null_mut();
18090    }
18091    SHELL_IDX += 1;
18092    s as *mut core::ffi::c_char
18093}
18094
18095#[no_mangle]
18096pub unsafe extern "C" fn setusershell() {
18097    SHELL_IDX = 0;
18098}
18099
18100#[no_mangle]
18101pub unsafe extern "C" fn endusershell() {
18102    SHELL_IDX = 0;
18103}
18104
18105// ============================================================
18106// ether functions
18107// ============================================================
18108
18109#[no_mangle]
18110pub unsafe extern "C" fn ether_aton(s: *const core::ffi::c_char) -> *mut u8 {
18111    static mut EA: [u8; 6] = [0; 6];
18112    if ether_aton_r(s, EA.as_mut_ptr()).is_null() { core::ptr::null_mut() } else { EA.as_mut_ptr() }
18113}
18114
18115#[no_mangle]
18116pub unsafe extern "C" fn ether_aton_r(s: *const core::ffi::c_char, ea: *mut u8) -> *mut u8 {
18117    if ea.is_null() { return core::ptr::null_mut(); }
18118    let mut i = 0;
18119    let mut j = 0;
18120    let mut val: u32 = 0;
18121    let mut digits = 0;
18122    while *s.add(i) != 0 && j < 6 {
18123        let c = *s.add(i);
18124        if c == ':' as c_char {
18125            if digits == 0 { return core::ptr::null_mut(); }
18126            *ea.add(j) = val as u8;
18127            j += 1;
18128            val = 0;
18129            digits = 0;
18130        } 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) {
18131            let d = if c >= '0' as c_char && c <= '9' as c_char { (c - '0' as c_char) as u32 }
18132                   else if c >= 'a' as c_char { (c - 'a' as c_char + 10) as u32 }
18133                   else { (c - 'A' as c_char + 10) as u32 };
18134            val = val * 16 + d;
18135            if val > 255 { return core::ptr::null_mut(); }
18136            digits += 1;
18137            if digits > 2 { return core::ptr::null_mut(); }
18138        } else {
18139            return core::ptr::null_mut();
18140        }
18141        i += 1;
18142    }
18143    if digits == 0 || j != 5 { return core::ptr::null_mut(); }
18144    *ea.add(j) = val as u8;
18145    ea
18146}
18147
18148#[no_mangle]
18149pub unsafe extern "C" fn ether_ntoa(ea: *const u8) -> *mut core::ffi::c_char {
18150    static mut BUF: [core::ffi::c_char; 18] = [0; 18];
18151    ether_ntoa_r(ea, BUF.as_mut_ptr());
18152    BUF.as_mut_ptr()
18153}
18154
18155#[no_mangle]
18156pub unsafe extern "C" fn ether_ntoa_r(ea: *const u8, buf: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
18157    let a = *ea.add(0); let b = *ea.add(1); let c = *ea.add(2);
18158    let d = *ea.add(3); let e = *ea.add(4); let f = *ea.add(5);
18159    let hex = b"0123456789abcdef\0".as_ptr() as *const u8;
18160    let mut i = 0;
18161    *buf.add(i) = *hex.add((a >> 4) as usize) as c_char; i += 1;
18162    *buf.add(i) = *hex.add((a & 0xf) as usize) as c_char; i += 1;
18163    *buf.add(i) = ':' as c_char; i += 1;
18164    *buf.add(i) = *hex.add((b >> 4) as usize) as c_char; i += 1;
18165    *buf.add(i) = *hex.add((b & 0xf) as usize) as c_char; i += 1;
18166    *buf.add(i) = ':' as c_char; i += 1;
18167    *buf.add(i) = *hex.add((c >> 4) as usize) as c_char; i += 1;
18168    *buf.add(i) = *hex.add((c & 0xf) as usize) as c_char; i += 1;
18169    *buf.add(i) = ':' as c_char; i += 1;
18170    *buf.add(i) = *hex.add((d >> 4) as usize) as c_char; i += 1;
18171    *buf.add(i) = *hex.add((d & 0xf) as usize) as c_char; i += 1;
18172    *buf.add(i) = ':' as c_char; i += 1;
18173    *buf.add(i) = *hex.add((e >> 4) as usize) as c_char; i += 1;
18174    *buf.add(i) = *hex.add((e & 0xf) as usize) as c_char; i += 1;
18175    *buf.add(i) = ':' as c_char; i += 1;
18176    *buf.add(i) = *hex.add((f >> 4) as usize) as c_char; i += 1;
18177    *buf.add(i) = *hex.add((f & 0xf) as usize) as c_char; i += 1;
18178    *buf.add(i) = 0;
18179    buf
18180}
18181
18182// ============================================================
18183// utmpx functions
18184// ============================================================
18185
18186#[no_mangle]
18187pub unsafe extern "C" fn getutxent() -> *mut core::ffi::c_void {
18188    getutent()
18189}
18190
18191#[no_mangle]
18192pub unsafe extern "C" fn getutxid(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
18193    getutid(ut)
18194}
18195
18196#[no_mangle]
18197pub unsafe extern "C" fn getutxline(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
18198    getutline(ut)
18199}
18200
18201#[no_mangle]
18202pub unsafe extern "C" fn pututxline(ut: *const core::ffi::c_void) -> *mut core::ffi::c_void {
18203    pututline(ut)
18204}
18205
18206#[no_mangle]
18207pub unsafe extern "C" fn setutxent() {
18208    setutent()
18209}
18210
18211#[no_mangle]
18212pub unsafe extern "C" fn endutxent() {
18213    endutent()
18214}
18215
18216// ============================================================
18217// exec functions
18218// ============================================================
18219
18220#[no_mangle]
18221pub unsafe extern "C" fn execv(path: *const core::ffi::c_char, argv: *const *const core::ffi::c_char) -> i32 {
18222    crate::execve(path, argv, __environ as *const *const core::ffi::c_char)
18223}
18224
18225#[no_mangle]
18226pub unsafe extern "C" fn execlp(file: *const core::ffi::c_char, _args: ...) -> i32 {
18227    let mut cap = 16usize;
18228    let mut argv = malloc(cap * core::mem::size_of::<*const core::ffi::c_char>()) as *mut *const core::ffi::c_char;
18229    if argv.is_null() { ERRNO!() = ENOMEM; return -1; }
18230    let mut i = 0usize;
18231    let mut args = _args;
18232    loop {
18233        let arg = args.next_arg::<*const core::ffi::c_char>();
18234        if arg.is_null() { break; }
18235        if i + 1 >= cap {
18236            cap = match cap.checked_mul(2) { Some(v) => v, None => { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; } };
18237            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;
18238            if grown.is_null() { free(argv as *mut c_void); ERRNO!() = ENOMEM; return -1; }
18239            argv = grown;
18240        }
18241        *argv.add(i) = arg;
18242        i += 1;
18243    }
18244    *argv.add(i) = core::ptr::null();
18245    let r = execvp(file, argv);
18246    free(argv as *mut c_void);
18247    r
18248}
18249
18250#[no_mangle]
18251pub unsafe extern "C" fn execvp(file: *const core::ffi::c_char, argv: *const *const core::ffi::c_char) -> i32 {
18252    execvpe(file, argv, __environ as *const *const core::ffi::c_char)
18253}
18254
18255unsafe fn write_decimal(dst: *mut c_char, mut value: usize) -> usize {
18256    let mut tmp = [0u8; 20];
18257    let mut n = 0usize;
18258    if value == 0 {
18259        tmp[0] = b'0';
18260        n = 1;
18261    } else {
18262        while value > 0 {
18263            tmp[n] = b'0' + (value % 10) as u8;
18264            value /= 10;
18265            n += 1;
18266        }
18267    }
18268    for i in 0..n {
18269        *dst.add(i) = tmp[n - 1 - i] as c_char;
18270    }
18271    n
18272}
18273
18274#[no_mangle]
18275pub unsafe extern "C" fn fexecve(fd: i32, argv: *const *const core::ffi::c_char, envp: *const *const core::ffi::c_char) -> i32 {
18276    // Read /proc/self/fd/N to get the path
18277    let mut path: [core::ffi::c_char; 64] = [0; 64];
18278    let mut i = 0;
18279    let src = b"/proc/self/fd/\0".as_ptr() as *const core::ffi::c_char;
18280    while i < 63 && *src.add(i) != 0 { path[i] = *src.add(i); i += 1; }
18281    if fd < 0 { ERRNO!() = EBADF; return -1; }
18282    i += write_decimal(path.as_mut_ptr().add(i), fd as usize);
18283    path[i] = 0;
18284    crate::execve(path.as_ptr(), argv, envp)
18285}
18286
18287// ============================================================
18288// conf functions
18289// ============================================================
18290
18291#[no_mangle]
18292pub unsafe extern "C" fn confstr(name: i32, buf: *mut core::ffi::c_char, len: usize) -> usize {
18293    // _CS_PATH is the only value with content; the POSIX_V6/V7 option
18294    // strings are empty on Linux. Truncation follows snprintf semantics.
18295    let value: &[u8] = if name == 0 {
18296        b"/bin:/usr/bin"
18297    } else if (1..=37).contains(&name) {
18298        b""
18299    } else {
18300        ERRNO!() = EINVAL;
18301        return 0;
18302    };
18303    let need = value.len() + 1;
18304    if !buf.is_null() && len > 0 {
18305        let n = core::cmp::min(value.len(), len - 1);
18306        core::ptr::copy_nonoverlapping(value.as_ptr(), buf as *mut u8, n);
18307        *buf.add(n) = 0;
18308    }
18309    need
18310}
18311
18312#[no_mangle]
18313pub unsafe extern "C" fn pathconf(_path: *const core::ffi::c_char, name: i32) -> i64 {
18314    fpathconf(-1, name)
18315}
18316
18317#[no_mangle]
18318pub unsafe extern "C" fn fpathconf(_fd: i32, name: i32) -> i64 {
18319    // Same policy as musl's conf/fpathconf.c: the values are filesystem
18320    // independent defaults, so the path/fd argument is not consulted.
18321    match name {
18322        0 => 8,       // _PC_LINK_MAX (_POSIX_LINK_MAX)
18323        1 => 255,     // _PC_MAX_CANON
18324        2 => 255,     // _PC_MAX_INPUT
18325        3 => 255,     // _PC_NAME_MAX
18326        4 => 4096,    // _PC_PATH_MAX
18327        5 => 4096,    // _PC_PIPE_BUF
18328        6 => 1,       // _PC_CHOWN_RESTRICTED
18329        7 => 1,       // _PC_NO_TRUNC
18330        8 => 0,       // _PC_VDISABLE
18331        9 => 1,       // _PC_SYNC_IO
18332        10 => -1,     // _PC_ASYNC_IO
18333        11 => -1,     // _PC_PRIO_IO
18334        12 => -1,     // _PC_SOCK_MAXBUF
18335        13 => 64,     // _PC_FILESIZEBITS
18336        14..=17 => 4096, // _PC_REC_*_XFER_SIZE/_ALIGN
18337        18 => 4096,   // _PC_ALLOC_SIZE_MIN
18338        19 => -1,     // _PC_SYMLINK_MAX
18339        20 => 1,      // _PC_2_SYMLINKS
18340        _ => {
18341            ERRNO!() = EINVAL;
18342            -1
18343        }
18344    }
18345}
18346
18347// ============================================================
18348// exp10 functions
18349// ============================================================
18350
18351#[no_mangle]
18352pub unsafe extern "C" fn exp10(x: f64) -> f64 {
18353    libm::pow(10.0, x)
18354}
18355
18356#[no_mangle]
18357pub unsafe extern "C" fn exp10f(x: f32) -> f32 {
18358    libm::powf(10.0, x)
18359}
18360
18361// ============================================================
18362// memory functions
18363// ============================================================
18364
18365#[no_mangle]
18366pub unsafe extern "C" fn explicit_bzero(s: *mut u8, n: usize) {
18367    core::ptr::write_bytes(s, 0, n);
18368    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
18369}
18370
18371#[no_mangle]
18372pub unsafe extern "C" fn memccpy(dest: *mut u8, src: *const u8, c: i32, n: usize) -> *mut u8 {
18373    let mut i = 0;
18374    while i < n {
18375        let byte = *src.add(i);
18376        *dest.add(i) = byte;
18377        if byte == c as u8 {
18378            return dest.add(i + 1);
18379        }
18380        i += 1;
18381    }
18382    core::ptr::null_mut()
18383}
18384
18385// ============================================================
18386// *at functions
18387// ============================================================
18388
18389#[no_mangle]
18390pub unsafe extern "C" fn faccessat(dirfd: i32, pathname: *const core::ffi::c_char, mode: i32, flags: i32) -> i32 {
18391    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FACCESSAT, dirfd as i64, pathname as i64, mode as i64, flags as i64)) as i32
18392}
18393
18394#[no_mangle]
18395pub unsafe extern "C" fn fchmodat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32, flags: i32) -> i32 {
18396    if flags == 0 {
18397        return syscall_ret(<Arch as Syscalls>::syscall4(SYS_FCHMODAT, dirfd as i64, pathname as i64, mode as i64, 0)) as i32;
18398    }
18399    if flags != AT_SYMLINK_NOFOLLOW {
18400        // Only AT_SYMLINK_NOFOLLOW is defined for fchmodat.
18401        ERRNO!() = EINVAL;
18402        return -1;
18403    }
18404    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FCHMODAT2, dirfd as i64, pathname as i64, mode as i64, flags as i64)) as i32
18405}
18406
18407#[no_mangle]
18408pub unsafe extern "C" fn fchownat(dirfd: i32, pathname: *const core::ffi::c_char, uid: u32, gid: u32, flags: i32) -> i32 {
18409    syscall_ret(<Arch as Syscalls>::syscall5(SYS_FCHOWNAT, dirfd as i64, pathname as i64, uid as i64, gid as i64, flags as i64)) as i32
18410}
18411
18412#[no_mangle]
18413pub unsafe extern "C" fn linkat(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char, flags: i32) -> i32 {
18414    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
18415}
18416
18417#[no_mangle]
18418pub unsafe extern "C" fn mkdirat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18419    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKDIRAT, dirfd as i64, pathname as i64, mode as i64)) as i32
18420}
18421
18422#[no_mangle]
18423pub unsafe extern "C" fn mkfifoat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18424    mknodat(dirfd, pathname, mode | 0o010000, 0)
18425}
18426
18427#[no_mangle]
18428pub unsafe extern "C" fn mknodat(dirfd: i32, pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
18429    syscall_ret(<Arch as Syscalls>::syscall4(SYS_MKNODAT, dirfd as i64, pathname as i64, mode as i64, dev as i64)) as i32
18430}
18431
18432#[no_mangle]
18433pub unsafe extern "C" fn readlinkat(dirfd: i32, pathname: *const core::ffi::c_char, buf: *mut core::ffi::c_char, bufsiz: usize) -> isize {
18434    syscall_ret(<Arch as Syscalls>::syscall4(SYS_READLINKAT, dirfd as i64, pathname as i64, buf as i64, bufsiz as i64)) as isize
18435}
18436
18437#[no_mangle]
18438pub unsafe extern "C" fn renameat(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char) -> i32 {
18439    syscall_ret(<Arch as Syscalls>::syscall5(SYS_RENAMEAT2, olddirfd as i64, oldpath as i64, newdirfd as i64, newpath as i64, 0)) as i32
18440}
18441
18442#[no_mangle]
18443pub unsafe extern "C" fn renameat2(olddirfd: i32, oldpath: *const core::ffi::c_char, newdirfd: i32, newpath: *const core::ffi::c_char, flags: u32) -> i32 {
18444    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
18445}
18446
18447#[no_mangle]
18448pub unsafe extern "C" fn symlinkat(target: *const core::ffi::c_char, newdirfd: i32, linkpath: *const core::ffi::c_char) -> i32 {
18449    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SYMLINKAT, target as i64, newdirfd as i64, linkpath as i64)) as i32
18450}
18451
18452#[no_mangle]
18453pub unsafe extern "C" fn unlinkat(dirfd: i32, pathname: *const core::ffi::c_char, flags: i32) -> i32 {
18454    syscall_ret(<Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, pathname as i64, flags as i64)) as i32
18455}
18456
18457#[no_mangle]
18458pub unsafe extern "C" fn utimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
18459    utimensat(AT_FDCWD, filename, times as *const timespec, 0)
18460}
18461
18462#[no_mangle]
18463pub unsafe extern "C" fn futimes(fd: i32, times: *const core::ffi::c_void) -> i32 {
18464    utimensat(fd, core::ptr::null(), times as *const timespec, 0)
18465}
18466
18467// ============================================================
18468// inotify functions
18469// ============================================================
18470
18471#[no_mangle]
18472pub unsafe extern "C" fn inotify_init() -> i32 {
18473    syscall_ret(<Arch as Syscalls>::syscall1(SYS_INOTIFY_INIT, 0)) as i32
18474}
18475
18476#[no_mangle]
18477pub unsafe extern "C" fn inotify_init1(flags: i32) -> i32 {
18478    syscall_ret(<Arch as Syscalls>::syscall1(SYS_INOTIFY_INIT1, flags as i64)) as i32
18479}
18480
18481#[no_mangle]
18482pub unsafe extern "C" fn inotify_add_watch(fd: i32, pathname: *const core::ffi::c_char, mask: u32) -> i32 {
18483    syscall_ret(<Arch as Syscalls>::syscall3(SYS_INOTIFY_ADD_WATCH, fd as i64, pathname as i64, mask as i64)) as i32
18484}
18485
18486#[no_mangle]
18487pub unsafe extern "C" fn inotify_rm_watch(fd: i32, wd: i32) -> i32 {
18488    syscall_ret(<Arch as Syscalls>::syscall2(SYS_INOTIFY_RM_WATCH, fd as i64, wd as i64)) as i32
18489}
18490
18491#[no_mangle]
18492pub unsafe extern "C" fn fanotify_init(flags: i32, event_f_flags: i32) -> i32 {
18493    syscall_ret(<Arch as Syscalls>::syscall2(SYS_FANOTIFY_INIT, flags as i64, event_f_flags as i64)) as i32
18494}
18495
18496#[no_mangle]
18497pub unsafe extern "C" fn fanotify_mark(fd: i32, flags: i32, mask: u64, dirfd: i32, pathname: *const core::ffi::c_char) -> i32 {
18498    syscall_ret(<Arch as Syscalls>::syscall5(SYS_FANOTIFY_MARK, fd as i64, flags as i64, mask as i64, dirfd as i64, pathname as i64)) as i32
18499}
18500
18501// ============================================================
18502// ffs functions
18503// ============================================================
18504
18505#[no_mangle]
18506pub unsafe extern "C" fn ffs(x: i32) -> i32 {
18507    if x == 0 { return 0; }
18508    x.trailing_zeros() as i32 + 1
18509}
18510
18511#[no_mangle]
18512pub unsafe extern "C" fn ffsl(x: i64) -> i32 {
18513    if x == 0 { return 0; }
18514    x.trailing_zeros() as i32 + 1
18515}
18516
18517#[no_mangle]
18518pub unsafe extern "C" fn ffsll(x: i64) -> i32 {
18519    if x == 0 { return 0; }
18520    x.trailing_zeros() as i32 + 1
18521}
18522
18523// ============================================================
18524// More system functions
18525// ============================================================
18526
18527#[no_mangle]
18528pub unsafe extern "C" fn fchdir(fd: i32) -> i32 {
18529    syscall_ret(<Arch as Syscalls>::syscall1(SYS_FCHDIR, fd as i64)) as i32
18530}
18531
18532#[no_mangle]
18533pub unsafe extern "C" fn fchown(fd: i32, uid: u32, gid: u32) -> i32 {
18534    syscall_ret(<Arch as Syscalls>::syscall3(SYS_FCHOWN, fd as i64, uid as i64, gid as i64)) as i32
18535}
18536
18537#[no_mangle]
18538pub unsafe extern "C" fn fdopendir(fd: i32) -> *mut core::ffi::c_void {
18539    if fd < 0 { ERRNO!() = EBADF; return core::ptr::null_mut(); }
18540    dir_stream_new(fd)
18541}
18542
18543#[no_mangle]
18544pub unsafe extern "C" fn getdtablesize() -> i32 {
18545    let mut rlim: Rlimit = core::mem::zeroed();
18546    if getrlimit(RLIMIT_NOFILE, &mut rlim) == 0 {
18547        rlim.rlim_cur as i32
18548    } else {
18549        1024
18550    }
18551}
18552
18553#[no_mangle]
18554pub unsafe extern "C" fn getentropy(buf: *mut u8, buflen: usize) -> i32 {
18555    if buflen > 256 {
18556        ERRNO!() = EIO;
18557        return -1;
18558    }
18559    let mut pos = buf;
18560    let mut left = buflen;
18561    while left > 0 {
18562        let r = getrandom(pos, left, 0);
18563        if r < 0 {
18564            if ERRNO!() == EINTR {
18565                continue;
18566            }
18567            return -1;
18568        }
18569        pos = pos.add(r as usize);
18570        left -= r as usize;
18571    }
18572    0
18573}
18574
18575#[no_mangle]
18576pub unsafe extern "C" fn getrandom(buf: *mut u8, buflen: usize, flags: u32) -> isize {
18577    if let Some(r) = vgetrandom(buf, buflen, flags) {
18578        return if r < 0 {
18579            ERRNO!() = (-r) as c_int;
18580            -1
18581        } else {
18582            r
18583        };
18584    }
18585    let r = <Arch as Syscalls>::syscall3(SYS_GETRANDOM, buf as i64, buflen as i64, flags as i64);
18586    if r < 0 {
18587        ERRNO!() = (-r) as c_int;
18588        -1
18589    } else {
18590        r as isize
18591    }
18592}
18593
18594#[no_mangle]
18595pub unsafe extern "C" fn killpg(pgrp: i32, sig: i32) -> i32 {
18596    syscall_ret(<Arch as Syscalls>::syscall2(SYS_KILL, -pgrp as i64, sig as i64)) as i32
18597}
18598
18599#[no_mangle]
18600pub unsafe extern "C" fn mkfifo(pathname: *const core::ffi::c_char, mode: u32) -> i32 {
18601    mknod(pathname, 0o010000 | mode, 0)
18602}
18603
18604// ============================================================
18605// Memory allocation functions
18606// ============================================================
18607
18608#[no_mangle]
18609pub unsafe extern "C" fn aligned_alloc(alignment: usize, size: usize) -> *mut core::ffi::c_void {
18610    alloc_aligned_impl(alignment, size) as *mut core::ffi::c_void
18611}
18612
18613#[no_mangle]
18614pub unsafe extern "C" fn memalign(alignment: usize, size: usize) -> *mut core::ffi::c_void {
18615    alloc_aligned_impl(alignment, size) as *mut core::ffi::c_void
18616}
18617
18618#[no_mangle]
18619pub unsafe extern "C" fn posix_memalign(memptr: *mut *mut core::ffi::c_void, alignment: usize, size: usize) -> i32 {
18620    if memptr.is_null() { return EINVAL; }
18621    if alignment < core::mem::size_of::<*mut core::ffi::c_void>() || !alignment.is_power_of_two() {
18622        return EINVAL;
18623    }
18624    let p = alloc_aligned_impl(alignment, size);
18625    if p.is_null() { return ENOMEM; }
18626    *memptr = p as *mut core::ffi::c_void;
18627    0
18628}
18629
18630#[no_mangle]
18631pub unsafe extern "C" fn valloc(size: usize) -> *mut core::ffi::c_void {
18632    alloc_aligned_impl(PAGE, size) as *mut core::ffi::c_void
18633}
18634
18635// ============================================================
18636// glob functions
18637// ============================================================
18638
18639// ============================================================
18640// wordexp functions
18641// ============================================================
18642
18643// ============================================================
18644// gettext functions
18645// ============================================================
18646
18647#[no_mangle]
18648pub unsafe extern "C" fn gettext(msgid: *const core::ffi::c_char) -> *const core::ffi::c_char {
18649    msgid
18650}
18651
18652#[no_mangle]
18653pub unsafe extern "C" fn dgettext(_domainname: *const core::ffi::c_char, msgid: *const core::ffi::c_char) -> *const core::ffi::c_char {
18654    msgid
18655}
18656
18657#[no_mangle]
18658pub unsafe extern "C" fn dcgettext(_domainname: *const core::ffi::c_char, msgid: *const core::ffi::c_char, _category: i32) -> *const core::ffi::c_char {
18659    msgid
18660}
18661
18662#[no_mangle]
18663pub unsafe extern "C" fn ngettext(msgid1: *const core::ffi::c_char, msgid2: *const core::ffi::c_char, n: u64) -> *const core::ffi::c_char {
18664    if n == 1 { msgid1 } else { msgid2 }
18665}
18666
18667#[no_mangle]
18668pub 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 {
18669    if n == 1 { msgid1 } else { msgid2 }
18670}
18671
18672#[no_mangle]
18673pub 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 {
18674    if n == 1 { msgid1 } else { msgid2 }
18675}
18676
18677#[no_mangle]
18678pub unsafe extern "C" fn textdomain(domainname: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18679    static mut DOMAIN: [core::ffi::c_char; 256] = [0; 256];
18680    if domainname.is_null() { return DOMAIN.as_mut_ptr(); }
18681    let mut i = 0;
18682    while i < 255 && *domainname.add(i) != 0 {
18683        DOMAIN[i] = *domainname.add(i);
18684        i += 1;
18685    }
18686    DOMAIN[i] = 0;
18687    DOMAIN.as_mut_ptr()
18688}
18689
18690#[no_mangle]
18691pub unsafe extern "C" fn bindtextdomain(_domainname: *const core::ffi::c_char, dirname: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18692    dirname as *mut core::ffi::c_char
18693}
18694
18695#[no_mangle]
18696pub unsafe extern "C" fn bind_textdomain_codeset(_domainname: *const core::ffi::c_char, codeset: *const core::ffi::c_char) -> *mut core::ffi::c_char {
18697    codeset as *mut core::ffi::c_char
18698}
18699
18700// ============================================================
18701// Wide string functions
18702// ============================================================
18703
18704#[no_mangle]
18705pub unsafe extern "C" fn wmemcpy(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18706    let mut i = 0;
18707    while i < n {
18708        *dest.add(i) = *src.add(i);
18709        i += 1;
18710    }
18711    dest
18712}
18713
18714#[no_mangle]
18715pub unsafe extern "C" fn wmemmove(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18716    if dest as usize <= src as usize {
18717        let mut i = 0;
18718        while i < n {
18719            *dest.add(i) = *src.add(i);
18720            i += 1;
18721        }
18722    } else {
18723        let mut i = n;
18724        while i > 0 {
18725            i -= 1;
18726            *dest.add(i) = *src.add(i);
18727        }
18728    }
18729    dest
18730}
18731
18732#[no_mangle]
18733pub unsafe extern "C" fn wmemset(dest: *mut u32, c: u32, n: usize) -> *mut u32 {
18734    let mut i = 0;
18735    while i < n {
18736        *dest.add(i) = c;
18737        i += 1;
18738    }
18739    dest
18740}
18741
18742#[no_mangle]
18743pub unsafe extern "C" fn wmemcmp(s1: *const u32, s2: *const u32, n: usize) -> i32 {
18744    let mut i = 0;
18745    while i < n {
18746        let c1 = *s1.add(i);
18747        let c2 = *s2.add(i);
18748        if c1 != c2 { return (c1 as i32) - (c2 as i32); }
18749        i += 1;
18750    }
18751    0
18752}
18753
18754#[no_mangle]
18755pub unsafe extern "C" fn wmemchr(s: *const u32, c: u32, n: usize) -> *mut u32 {
18756    let mut i = 0;
18757    while i < n {
18758        if *s.add(i) == c { return s.add(i) as *mut u32; }
18759        i += 1;
18760    }
18761    core::ptr::null_mut()
18762}
18763
18764#[no_mangle]
18765pub unsafe extern "C" fn wcpcpy(dest: *mut u32, src: *const u32) -> *mut u32 {
18766    let mut i = 0;
18767    loop {
18768        let c = *src.add(i);
18769        *dest.add(i) = c;
18770        if c == 0 { return dest.add(i); }
18771        i += 1;
18772    }
18773}
18774
18775#[no_mangle]
18776pub unsafe extern "C" fn wcpncpy(dest: *mut u32, src: *const u32, n: usize) -> *mut u32 {
18777    let mut i = 0;
18778    while i < n {
18779        let c = *src.add(i);
18780        *dest.add(i) = c;
18781        if c == 0 { return dest.add(i); }
18782        i += 1;
18783    }
18784    dest.add(n)
18785}
18786
18787#[no_mangle]
18788pub unsafe extern "C" fn wprintf(fmt: *const wchar_t, args: ...) -> c_int {
18789    vfwprintf(stdout, fmt, args)
18790}
18791
18792#[no_mangle]
18793pub unsafe extern "C" fn vwprintf(fmt: *const wchar_t, ap: core::ffi::VaList) -> c_int {
18794    vfwprintf(stdout, fmt, ap)
18795}
18796
18797// ============================================================
18798// C32 functions
18799// ============================================================
18800
18801#[no_mangle]
18802pub unsafe extern "C" fn c16rtomb(s: *mut u8, c16: u16, ps: *mut core::ffi::c_void) -> usize {
18803    // UTF-16 to UTF-8, with surrogate pairs tracked in the mbstate.
18804    let state = ps as *mut u32;
18805    let saved: u32 = if state.is_null() { 0 } else { *state };
18806    if s.is_null() {
18807        if !state.is_null() { *state = 0; }
18808        return 1;
18809    }
18810    let cp: u32;
18811    if saved != 0 {
18812        if (c16 as u32) < UNICODE_LOW_SURROGATE_START || (c16 as u32) > UNICODE_SURROGATE_END {
18813            if !state.is_null() { *state = 0; }
18814            ERRNO!() = EILSEQ;
18815            return !0usize;
18816        }
18817        cp = UNICODE_SUPPLEMENTARY_BASE
18818            + (((saved - UNICODE_SURROGATE_START) << 10) | ((c16 as u32) - UNICODE_LOW_SURROGATE_START));
18819        if !state.is_null() { *state = 0; }
18820    } else if (c16 as u32) >= UNICODE_SURROGATE_START && (c16 as u32) <= UNICODE_HIGH_SURROGATE_END {
18821        if !state.is_null() { *state = c16 as u32; }
18822        return 0;
18823    } else if c16 >= 0xdc00 && c16 <= 0xdfff {
18824        ERRNO!() = EILSEQ;
18825        return !0usize;
18826    } else {
18827        cp = c16 as u32;
18828    }
18829    if cp < 0x80 {
18830        *s = cp as u8;
18831        1
18832    } else if cp < 0x800 {
18833        *s = (0xc0 | (cp >> 6)) as u8;
18834        *s.add(1) = (0x80 | (cp & 0x3f)) as u8;
18835        2
18836    } else if cp < 0x10000 {
18837        *s = (0xe0 | (cp >> 12)) as u8;
18838        *s.add(1) = (0x80 | ((cp >> 6) & 0x3f)) as u8;
18839        *s.add(2) = (0x80 | (cp & 0x3f)) as u8;
18840        3
18841    } else {
18842        *s = (0xf0 | (cp >> 18)) as u8;
18843        *s.add(1) = (0x80 | ((cp >> 12) & 0x3f)) as u8;
18844        *s.add(2) = (0x80 | ((cp >> 6) & 0x3f)) as u8;
18845        *s.add(3) = (0x80 | (cp & 0x3f)) as u8;
18846        4
18847    }
18848}
18849
18850#[no_mangle]
18851pub unsafe extern "C" fn c32rtomb(s: *mut u8, c32: u32, _ps: *mut core::ffi::c_void) -> usize {
18852    if s.is_null() { return 1; }
18853    if c32 > 0x10ffff || (c32 >= 0xd800 && c32 <= 0xdfff) {
18854        ERRNO!() = EILSEQ;
18855        return !0usize;
18856    }
18857    if c32 < 0x80 {
18858        *s = c32 as u8;
18859        1
18860    } else if c32 < 0x800 {
18861        *s = (0xc0 | (c32 >> 6)) as u8;
18862        *s.add(1) = (0x80 | (c32 & 0x3f)) as u8;
18863        2
18864    } else if c32 < 0x10000 {
18865        *s = (0xe0 | (c32 >> 12)) as u8;
18866        *s.add(1) = (0x80 | ((c32 >> 6) & 0x3f)) as u8;
18867        *s.add(2) = (0x80 | (c32 & 0x3f)) as u8;
18868        3
18869    } else {
18870        *s = (0xf0 | (c32 >> 18)) as u8;
18871        *s.add(1) = (0x80 | ((c32 >> 12) & 0x3f)) as u8;
18872        *s.add(2) = (0x80 | ((c32 >> 6) & 0x3f)) as u8;
18873        *s.add(3) = (0x80 | (c32 & 0x3f)) as u8;
18874        4
18875    }
18876}
18877
18878#[no_mangle]
18879pub unsafe extern "C" fn mbrtoc16(pc16: *mut u16, s: *const u8, n: usize, _ps: *mut core::ffi::c_void) -> usize {
18880    if s.is_null() { return 0; }
18881    if n == 0 { return 1; }
18882    let c = *s;
18883    if c == 0 { return 0; }
18884    if c < 0x80 {
18885        if !pc16.is_null() { *pc16 = c as u16; }
18886        return 1;
18887    }
18888    if c < 0xC2 { return 1; } // Invalid
18889    if c < 0xE0 {
18890        if n < 2 { return 1; }
18891        let c2 = *s.add(1);
18892        if (c2 & 0xC0) != 0x80 { return 1; }
18893        if !pc16.is_null() { *pc16 = ((((c & 0x1F) as u32) << 6) | ((c2 & 0x3F) as u32)) as u16; }
18894        return 2;
18895    }
18896    if c < 0xF0 {
18897        if n < 3 { return 1; }
18898        let c2 = *s.add(1);
18899        let c3 = *s.add(2);
18900        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 { return 1; }
18901        if !pc16.is_null() { *pc16 = ((((c & 0x0F) as u32) << 12) | (((c2 & 0x3F) as u32) << 6) | ((c3 & 0x3F) as u32)) as u16; }
18902        return 3;
18903    }
18904    1
18905}
18906
18907#[no_mangle]
18908pub unsafe extern "C" fn mbrtoc32(pc32: *mut u32, s: *const u8, n: usize, _ps: *mut core::ffi::c_void) -> usize {
18909    if s.is_null() { return 0; }
18910    if n == 0 { return 1; }
18911    let c = *s;
18912    if c == 0 { return 0; }
18913    if c < 0x80 {
18914        if !pc32.is_null() { *pc32 = c as u32; }
18915        return 1;
18916    }
18917    if c < 0xC2 { return 1; } // Invalid
18918    if c < 0xE0 {
18919        if n < 2 { return 1; }
18920        let c2 = *s.add(1);
18921        if (c2 & 0xC0) != 0x80 { return 1; }
18922        if !pc32.is_null() { *pc32 = (((c & 0x1F) as u32) << 6) | ((c2 & 0x3F) as u32); }
18923        return 2;
18924    }
18925    if c < 0xF0 {
18926        if n < 3 { return 1; }
18927        let c2 = *s.add(1);
18928        let c3 = *s.add(2);
18929        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 { return 1; }
18930        if !pc32.is_null() { *pc32 = (((c & 0x0F) as u32) << 12) | (((c2 & 0x3F) as u32) << 6) | ((c3 & 0x3F) as u32); }
18931        return 3;
18932    }
18933    if c < 0xF5 {
18934        if n < 4 { return 1; }
18935        let c2 = *s.add(1);
18936        let c3 = *s.add(2);
18937        let c4 = *s.add(3);
18938        if (c2 & 0xC0) != 0x80 || (c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80 { return 1; }
18939        if !pc32.is_null() { *pc32 = (((c & 0x07) as u32) << 18) | (((c2 & 0x3F) as u32) << 12) | (((c3 & 0x3F) as u32) << 6) | ((c4 & 0x3F) as u32); }
18940        return 4;
18941    }
18942    1
18943}
18944
18945// ============================================================
18946// Shadow functions
18947// ============================================================
18948
18949
18950
18951
18952// ============================================================
18953// chown functions
18954// ============================================================
18955
18956#[no_mangle]
18957pub unsafe extern "C" fn chown(path: *const core::ffi::c_char, uid: u32, gid: u32) -> i32 {
18958    syscall_ret(<Arch as Syscalls>::syscall5(
18959        SYS_FCHOWNAT,
18960        AT_FDCWD as i64,
18961        path as i64,
18962        uid as i64,
18963        gid as i64,
18964        0,
18965    )) as i32
18966}
18967
18968#[no_mangle]
18969pub unsafe extern "C" fn lchown(path: *const core::ffi::c_char, uid: u32, gid: u32) -> i32 {
18970    syscall_ret(<Arch as Syscalls>::syscall5(
18971        SYS_FCHOWNAT,
18972        AT_FDCWD as i64,
18973        path as i64,
18974        uid as i64,
18975        gid as i64,
18976        AT_SYMLINK_NOFOLLOW as i64,
18977    )) as i32
18978}
18979
18980// ============================================================
18981// chroot functions
18982// ============================================================
18983
18984#[no_mangle]
18985pub unsafe extern "C" fn chroot(path: *const core::ffi::c_char) -> i32 {
18986    syscall_ret(<Arch as Syscalls>::syscall1(SYS_CHROOT, path as i64)) as i32
18987}
18988
18989#[no_mangle]
18990pub unsafe extern "C" fn get_current_dir_name() -> *mut core::ffi::c_char {
18991    static mut BUF: [core::ffi::c_char; PATH_MAX_V] = [0; PATH_MAX_V];
18992    let r = getcwd(BUF.as_mut_ptr(), PATH_MAX_V);
18993    if r.is_null() { core::ptr::null_mut() } else { BUF.as_mut_ptr() }
18994}
18995
18996// ============================================================
18997// I/O functions
18998// ============================================================
18999
19000#[no_mangle]
19001pub unsafe extern "C" fn creat(pathname: *const core::ffi::c_char, mode: u32) -> i32 {
19002    // O_WRONLY | O_CREAT | O_TRUNC. The previous flags included O_EXCL.
19003    open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode as i32)
19004}
19005
19006#[no_mangle]
19007pub unsafe extern "C" fn openat(dirfd: i32, pathname: *const core::ffi::c_char, flags: i32, mode: u32) -> i32 {
19008    syscall_ret(<Arch as Syscalls>::syscall4(SYS_OPENAT, dirfd as i64, pathname as i64, flags as i64, mode as i64)) as i32
19009}
19010
19011#[no_mangle]
19012pub unsafe extern "C" fn pwrite(fd: i32, buf: *const u8, count: usize, offset: i64) -> isize {
19013    syscall_ret(<Arch as Syscalls>::syscall4(SYS_PWRITE64, fd as i64, buf as i64, count as i64, offset)) as isize
19014}
19015
19016#[no_mangle]
19017pub unsafe extern "C" fn readv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32) -> isize {
19018    syscall_ret(<Arch as Syscalls>::syscall3(SYS_READV, fd as i64, iov as i64, iovcnt as i64)) as isize
19019}
19020
19021#[no_mangle]
19022pub unsafe extern "C" fn writev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32) -> isize {
19023    syscall_ret(<Arch as Syscalls>::syscall3(SYS_WRITEV, fd as i64, iov as i64, iovcnt as i64)) as isize
19024}
19025
19026// ============================================================
19027// Lock functions
19028// ============================================================
19029
19030#[no_mangle]
19031pub unsafe extern "C" fn flock(fd: i32, operation: i32) -> i32 {
19032    syscall_ret(<Arch as Syscalls>::syscall2(SYS_FLOCK, fd as i64, operation as i64)) as i32
19033}
19034
19035#[repr(C)]
19036struct FlockArg {
19037    l_type: i16,
19038    l_whence: i16,
19039    l_start: i64,
19040    l_len: i64,
19041    l_pid: i32,
19042}
19043
19044#[no_mangle]
19045pub unsafe extern "C" fn lockf(fd: i32, cmd: i32, len: i64) -> i32 {
19046    // POSIX lockf commands map onto fcntl record locks relative to the
19047    // current file offset.
19048    const F_RDLCK: i16 = 0;
19049    const F_WRLCK: i16 = 1;
19050    const F_UNLCK: i16 = 2;
19051    const F_SETLK: i64 = 6;
19052    const F_SETLKW: i64 = 7;
19053    const SEEK_CUR: i16 = 1;
19054    let (l_type, wait) = match cmd {
19055        0 => (F_UNLCK, false), // F_ULOCK
19056        1 => (F_WRLCK, true),  // F_LOCK
19057        2 => (F_WRLCK, false), // F_TLOCK
19058        3 => (F_RDLCK, false), // F_TEST
19059        _ => {
19060            ERRNO!() = EINVAL;
19061            return -1;
19062        }
19063    };
19064    let fl = FlockArg { l_type, l_whence: SEEK_CUR, l_start: 0, l_len: len, l_pid: 0 };
19065    let r = <Arch as Syscalls>::syscall3(
19066        SYS_FCNTL,
19067        fd as i64,
19068        if wait { F_SETLKW } else { F_SETLK },
19069        &fl as *const FlockArg as i64,
19070    );
19071    syscall_ret(r) as c_int
19072}
19073
19074// ============================================================
19075// Hostname/login functions
19076// ============================================================
19077
19078#[no_mangle]
19079pub unsafe extern "C" fn getdomainname(name: *mut core::ffi::c_char, len: usize) -> i32 {
19080    if name.is_null() || len == 0 {
19081        ERRNO!() = EINVAL;
19082        return -1;
19083    }
19084    let mut uts: UtsName = core::mem::zeroed();
19085    let r = <Arch as Syscalls>::syscall1(SYS_UNAME, &mut uts as *mut UtsName as i64);
19086    if r < 0 {
19087        ERRNO!() = (-r) as c_int;
19088        return -1;
19089    }
19090    let mut n = 0usize;
19091    while n < uts.domainname.len() && uts.domainname[n] != 0 { n += 1; }
19092    if n >= len {
19093        ERRNO!() = EINVAL;
19094        return -1;
19095    }
19096    core::ptr::copy_nonoverlapping(uts.domainname.as_ptr(), name as *mut u8, n);
19097    *name.add(n) = 0;
19098    0
19099}
19100
19101#[no_mangle]
19102pub unsafe extern "C" fn setdomainname(name: *const core::ffi::c_char, len: usize) -> i32 {
19103    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETDOMAINNAME, name as i64, len as i64)) as i32
19104}
19105
19106#[no_mangle]
19107pub unsafe extern "C" fn sethostname(name: *const core::ffi::c_char, len: usize) -> i32 {
19108    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETHOSTNAME, name as i64, len as i64)) as i32
19109}
19110
19111#[no_mangle]
19112pub unsafe extern "C" fn getlogin_r(name: *mut core::ffi::c_char, bufsize: usize) -> i32 {
19113    let user = getlogin();
19114    if user.is_null() { return ENXIO; }
19115    let len = crate::strlen(user);
19116    if len >= bufsize { return 34; } // ERANGE
19117    core::ptr::copy_nonoverlapping(user, name, len + 1);
19118    0
19119}
19120
19121#[no_mangle]
19122pub unsafe extern "C" fn cuserid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
19123    let user = crate::getenv(b"USER\0".as_ptr() as *const core::ffi::c_char);
19124    if user.is_null() { return core::ptr::null_mut(); }
19125    if s.is_null() {
19126        static mut BUF: [core::ffi::c_char; 32] = [0; 32];
19127        let mut i = 0;
19128        while i < 31 && *user.add(i) != 0 { BUF[i] = *user.add(i); i += 1; }
19129        BUF[i] = 0;
19130        BUF.as_mut_ptr()
19131    } else {
19132        let mut i = 0;
19133        while i < 31 && *user.add(i) != 0 { *s.add(i) = *user.add(i); i += 1; }
19134        *s.add(i) = 0;
19135        s
19136    }
19137}
19138
19139// ============================================================
19140// Group and passwd functions
19141// ============================================================
19142
19143#[repr(C)]
19144#[derive(Copy, Clone)]
19145pub struct Passwd {
19146    pub pw_name: *mut c_char,
19147    pub pw_passwd: *mut c_char,
19148    pub pw_uid: u32,
19149    pub pw_gid: u32,
19150    pub pw_gecos: *mut c_char,
19151    pub pw_dir: *mut c_char,
19152    pub pw_shell: *mut c_char,
19153}
19154
19155#[repr(C)]
19156#[derive(Copy, Clone)]
19157pub struct Group {
19158    pub gr_name: *mut c_char,
19159    pub gr_passwd: *mut c_char,
19160    pub gr_gid: u32,
19161    pub gr_mem: *mut *mut c_char,
19162}
19163
19164static mut PWD_ENT: Passwd = Passwd {
19165    pw_name: core::ptr::null_mut(), pw_passwd: core::ptr::null_mut(),
19166    pw_uid: 0, pw_gid: 0, pw_gecos: core::ptr::null_mut(),
19167    pw_dir: core::ptr::null_mut(), pw_shell: core::ptr::null_mut(),
19168};
19169static mut PWD_LINE: *mut c_char = core::ptr::null_mut();
19170static mut PWD_LINE_CAP: usize = 0;
19171static mut PWD_BUF: *mut c_char = core::ptr::null_mut();
19172static mut PWD_BUF_CAP: usize = 0;
19173static mut PWD_FILE: *mut FILE = core::ptr::null_mut();
19174
19175unsafe fn ensure_pwd_buf(n: usize) -> bool {
19176    if n <= PWD_BUF_CAP {
19177        return true;
19178    }
19179    let mut cap = if PWD_BUF_CAP == 0 { 1024 } else { PWD_BUF_CAP };
19180    while cap < n {
19181        cap *= 2;
19182    }
19183    let p = realloc(PWD_BUF as *mut c_void, cap) as *mut c_char;
19184    if p.is_null() {
19185        return false;
19186    }
19187    PWD_BUF = p;
19188    PWD_BUF_CAP = cap;
19189    true
19190}
19191
19192static mut GRP_ENT: Group = Group {
19193    gr_name: core::ptr::null_mut(), gr_passwd: core::ptr::null_mut(),
19194    gr_gid: 0, gr_mem: core::ptr::null_mut(),
19195};
19196static mut GRP_LINE: *mut c_char = core::ptr::null_mut();
19197static mut GRP_LINE_CAP: usize = 0;
19198static mut GRP_BUF: *mut c_char = core::ptr::null_mut();
19199static mut GRP_BUF_CAP: usize = 0;
19200static mut GRP_MEM: *mut *mut c_char = core::ptr::null_mut();
19201static mut GRP_MEM_CAP: usize = 0;
19202static mut GRP_FILE: *mut FILE = core::ptr::null_mut();
19203
19204unsafe fn ensure_grp_buf(n: usize) -> bool {
19205    if n <= GRP_BUF_CAP {
19206        return true;
19207    }
19208    let mut cap = if GRP_BUF_CAP == 0 { 2048 } else { GRP_BUF_CAP };
19209    while cap < n {
19210        cap *= 2;
19211    }
19212    let p = realloc(GRP_BUF as *mut c_void, cap) as *mut c_char;
19213    if p.is_null() {
19214        return false;
19215    }
19216    GRP_BUF = p;
19217    GRP_BUF_CAP = cap;
19218    true
19219}
19220
19221unsafe fn ensure_grp_mem(n: usize) -> bool {
19222    if n <= GRP_MEM_CAP {
19223        return true;
19224    }
19225    let mut cap = if GRP_MEM_CAP == 0 { 32 } else { GRP_MEM_CAP };
19226    while cap < n {
19227        cap *= 2;
19228    }
19229    let p = realloc(
19230        GRP_MEM as *mut c_void,
19231        cap * core::mem::size_of::<*mut c_char>(),
19232    ) as *mut *mut c_char;
19233    if p.is_null() {
19234        return false;
19235    }
19236    GRP_MEM = p;
19237    GRP_MEM_CAP = cap;
19238    true
19239}
19240
19241/// Copy colon-separated fields from `line` into `buf`, NUL-terminating each.
19242/// Returns the number of fields found, or None when `buf` is too small.
19243unsafe fn split_colon_fields(
19244    line: *const c_char,
19245    buf: *mut c_char,
19246    buflen: usize,
19247    fields: &mut [*mut c_char],
19248) -> Option<usize> {
19249    let mut src = line;
19250    let mut o = 0usize;
19251    let mut n = 0usize;
19252    while n < fields.len() {
19253        let start = o;
19254        while *src != 0 && *src != b':' as c_char {
19255            if o + 1 >= buflen { return None; }
19256            *buf.add(o) = *src;
19257            o += 1;
19258            src = src.add(1);
19259        }
19260        *buf.add(o) = 0;
19261        o += 1;
19262        fields[n] = buf.add(start);
19263        n += 1;
19264        if *src == 0 { break; }
19265        src = src.add(1);
19266    }
19267    Some(n)
19268}
19269
19270unsafe fn parse_passwd(line: *const c_char, ent: *mut Passwd, buf: *mut c_char, buflen: usize) -> bool {
19271    let mut fields: [*mut c_char; 7] = [core::ptr::null_mut(); 7];
19272    let n = match split_colon_fields(line, buf, buflen, &mut fields) {
19273        Some(n) => n,
19274        None => return false,
19275    };
19276    if n < 7 { return false; }
19277    (*ent).pw_name = fields[0];
19278    (*ent).pw_passwd = fields[1];
19279    (*ent).pw_uid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
19280    (*ent).pw_gid = crate::strtol(fields[3], core::ptr::null_mut(), 10) as u32;
19281    (*ent).pw_gecos = fields[4];
19282    (*ent).pw_dir = fields[5];
19283    (*ent).pw_shell = fields[6];
19284    true
19285}
19286
19287unsafe fn parse_group(line: *const c_char, ent: *mut Group, buf: *mut c_char, buflen: usize) -> bool {
19288    let mut fields: [*mut c_char; 4] = [core::ptr::null_mut(); 4];
19289    let n = match split_colon_fields(line, buf, buflen, &mut fields) {
19290        Some(n) => n,
19291        None => return false,
19292    };
19293    if n < 4 { return false; }
19294    (*ent).gr_name = fields[0];
19295    (*ent).gr_passwd = fields[1];
19296    (*ent).gr_gid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
19297    let mut count = 1usize;
19298    let mut m = fields[3];
19299    while *m != 0 {
19300        if *m == b',' as c_char { count += 1; }
19301        m = m.add(1);
19302    }
19303    if !ensure_grp_mem(count + 1) { return false; }
19304    let mut mi = 0usize;
19305    m = fields[3];
19306    if *m != 0 {
19307        loop {
19308            *GRP_MEM.add(mi) = m;
19309            mi += 1;
19310            while *m != 0 && *m != b',' as c_char { m = m.add(1); }
19311            if *m == 0 { break; }
19312            *m = 0;
19313            m = m.add(1);
19314        }
19315    }
19316    *GRP_MEM.add(mi) = core::ptr::null_mut();
19317    (*ent).gr_mem = GRP_MEM;
19318    true
19319}
19320
19321unsafe fn scan_passwd(mut matches: impl FnMut(*const Passwd) -> bool) -> *mut Passwd {
19322    setpwent();
19323    loop {
19324        let p = getpwent();
19325        if p.is_null() { break; }
19326        if matches(p) {
19327            endpwent();
19328            return p;
19329        }
19330    }
19331    endpwent();
19332    core::ptr::null_mut()
19333}
19334
19335#[no_mangle]
19336pub unsafe extern "C" fn getpwnam(name: *const c_char) -> *mut Passwd {
19337    if name.is_null() { return core::ptr::null_mut(); }
19338    scan_passwd(|p| crate::strcmp((*p).pw_name as *const u8, name as *const u8) == 0)
19339}
19340
19341#[no_mangle]
19342pub unsafe extern "C" fn getpwuid(uid: u32) -> *mut Passwd {
19343    scan_passwd(|p| (*p).pw_uid == uid)
19344}
19345
19346#[no_mangle]
19347pub unsafe extern "C" fn setpwent() {
19348    endpwent();
19349    PWD_FILE = crate::fopen(b"/etc/passwd\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19350}
19351
19352#[no_mangle]
19353pub unsafe extern "C" fn getpwent() -> *mut Passwd {
19354    if PWD_FILE.is_null() { setpwent(); if PWD_FILE.is_null() { return core::ptr::null_mut(); } }
19355    loop {
19356        let n = crate::getline(&raw mut PWD_LINE, &raw mut PWD_LINE_CAP, PWD_FILE);
19357        if n < 0 { return core::ptr::null_mut(); }
19358        let mut len = n as usize;
19359        if len > 0 && *PWD_LINE.add(len - 1) == b'\n' as c_char {
19360            *PWD_LINE.add(len - 1) = 0;
19361            len -= 1;
19362        }
19363        let need = len + 1;
19364        if !ensure_pwd_buf(need) { return core::ptr::null_mut(); }
19365        if parse_passwd(PWD_LINE, &raw mut PWD_ENT, PWD_BUF, need) {
19366            return &raw mut PWD_ENT;
19367        }
19368    }
19369}
19370
19371#[no_mangle]
19372pub unsafe extern "C" fn endpwent() {
19373    if !PWD_FILE.is_null() { crate::fclose(PWD_FILE); PWD_FILE = core::ptr::null_mut(); }
19374}
19375
19376unsafe fn getpw_r_inner(
19377    name: *const c_char,
19378    uid: Option<u32>,
19379    pwd: *mut Passwd,
19380    buf: *mut c_char,
19381    buflen: usize,
19382    result: *mut *mut Passwd,
19383) -> c_int {
19384    if pwd.is_null() || buf.is_null() || result.is_null() || (uid.is_none() && name.is_null()) {
19385        return EINVAL;
19386    }
19387    *result = core::ptr::null_mut();
19388    let f = crate::fopen(b"/etc/passwd\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19389    if f.is_null() { return ERRNO!(); }
19390    let mut line: *mut c_char = core::ptr::null_mut();
19391    let mut cap: usize = 0;
19392    let mut err = 0;
19393    loop {
19394        let n = crate::getline(&raw mut line, &raw mut cap, f);
19395        if n < 0 { break; }
19396        let mut len = n as usize;
19397        if len > 0 && *line.add(len - 1) == b'\n' as c_char {
19398            *line.add(len - 1) = 0;
19399            len -= 1;
19400        }
19401        if len + 1 > buflen {
19402            err = ERANGE;
19403            break;
19404        }
19405        if parse_passwd(line, pwd, buf, buflen) {
19406            let hit = if let Some(uid) = uid {
19407                (*pwd).pw_uid == uid
19408            } else {
19409                crate::strcmp((*pwd).pw_name as *const u8, name as *const u8) == 0
19410            };
19411            if hit {
19412                *result = pwd;
19413                break;
19414            }
19415        }
19416    }
19417    crate::free(line as *mut c_void);
19418    crate::fclose(f);
19419    err
19420}
19421
19422#[no_mangle]
19423pub 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 {
19424    getpw_r_inner(name, None, pwd, buf, buflen, result)
19425}
19426
19427#[no_mangle]
19428pub unsafe extern "C" fn getpwuid_r(uid: u32, pwd: *mut Passwd, buf: *mut c_char, buflen: usize, result: *mut *mut Passwd) -> c_int {
19429    getpw_r_inner(core::ptr::null(), Some(uid), pwd, buf, buflen, result)
19430}
19431
19432#[no_mangle]
19433pub unsafe extern "C" fn fgetpwent(f: *mut FILE) -> *mut Passwd {
19434    if f.is_null() { return core::ptr::null_mut(); }
19435    loop {
19436        let n = crate::getline(&raw mut PWD_LINE, &raw mut PWD_LINE_CAP, f);
19437        if n < 0 { return core::ptr::null_mut(); }
19438        let mut len = n as usize;
19439        if len > 0 && *PWD_LINE.add(len - 1) == b'\n' as c_char {
19440            *PWD_LINE.add(len - 1) = 0;
19441            len -= 1;
19442        }
19443        let need = len + 1;
19444        if !ensure_pwd_buf(need) { return core::ptr::null_mut(); }
19445        if parse_passwd(PWD_LINE, &raw mut PWD_ENT, PWD_BUF, need) {
19446            return &raw mut PWD_ENT;
19447        }
19448    }
19449}
19450
19451#[no_mangle]
19452pub unsafe extern "C" fn putpwent(f: *mut FILE, p: *const Passwd) -> c_int {
19453    if f.is_null() || p.is_null() { return -1; }
19454    crate::fprintf(f, b"%s:%s:%u:%u:%s:%s:%s\n\0".as_ptr() as *const c_char,
19455        (*p).pw_name, (*p).pw_passwd, (*p).pw_uid, (*p).pw_gid,
19456        (*p).pw_gecos, (*p).pw_dir, (*p).pw_shell)
19457}
19458
19459unsafe fn scan_group(mut matches: impl FnMut(*const Group) -> bool) -> *mut Group {
19460    setgrent();
19461    loop {
19462        let g = getgrent();
19463        if g.is_null() { break; }
19464        if matches(g) {
19465            endgrent();
19466            return g;
19467        }
19468    }
19469    endgrent();
19470    core::ptr::null_mut()
19471}
19472
19473#[no_mangle]
19474pub unsafe extern "C" fn getgrnam(name: *const c_char) -> *mut Group {
19475    if name.is_null() { return core::ptr::null_mut(); }
19476    scan_group(|g| crate::strcmp((*g).gr_name as *const u8, name as *const u8) == 0)
19477}
19478
19479#[no_mangle]
19480pub unsafe extern "C" fn getgrgid(gid: u32) -> *mut Group {
19481    scan_group(|g| (*g).gr_gid == gid)
19482}
19483
19484#[no_mangle]
19485pub unsafe extern "C" fn setgrent() {
19486    endgrent();
19487    GRP_FILE = crate::fopen(b"/etc/group\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19488}
19489
19490#[no_mangle]
19491pub unsafe extern "C" fn getgrent() -> *mut Group {
19492    if GRP_FILE.is_null() { setgrent(); if GRP_FILE.is_null() { return core::ptr::null_mut(); } }
19493    loop {
19494        let n = crate::getline(&raw mut GRP_LINE, &raw mut GRP_LINE_CAP, GRP_FILE);
19495        if n < 0 { return core::ptr::null_mut(); }
19496        let mut len = n as usize;
19497        if len > 0 && *GRP_LINE.add(len - 1) == b'\n' as c_char {
19498            *GRP_LINE.add(len - 1) = 0;
19499            len -= 1;
19500        }
19501        let need = len + 1;
19502        if !ensure_grp_buf(need) { return core::ptr::null_mut(); }
19503        if parse_group(GRP_LINE, &raw mut GRP_ENT, GRP_BUF, need) {
19504            return &raw mut GRP_ENT;
19505        }
19506    }
19507}
19508
19509#[no_mangle]
19510pub unsafe extern "C" fn endgrent() {
19511    if !GRP_FILE.is_null() { crate::fclose(GRP_FILE); GRP_FILE = core::ptr::null_mut(); }
19512}
19513
19514// Parses one group line into the caller's buffer.  The member pointer array
19515// is placed in the same buffer, after the strings, aligned to pointer size.
19516unsafe fn parse_group_r(line: *const c_char, ent: *mut Group, buf: *mut c_char, buflen: usize) -> c_int {
19517    const OK: c_int = 0;
19518    const BAD: c_int = -1;
19519    const NOSPACE: c_int = -2;
19520
19521    let mut fields: [*mut c_char; 4] = [core::ptr::null_mut(); 4];
19522    let n = match split_colon_fields(line, buf, buflen, &mut fields) {
19523        Some(n) => n,
19524        None => return NOSPACE,
19525    };
19526    if n < 4 { return BAD; }
19527
19528    let mut count = 1usize;
19529    let mut m = fields[3];
19530    while *m != 0 {
19531        if *m == b',' as c_char { count += 1; }
19532        m = m.add(1);
19533    }
19534    // The member pointer array lives after the copied strings in `buf`.
19535    let ptr_size = core::mem::size_of::<*mut c_char>();
19536    let base = buf as usize;
19537    let o = crate::strlen(buf) + 1;
19538    let aligned = match base
19539        .checked_add(o)
19540        .and_then(|v| v.checked_add(ptr_size - 1))
19541    {
19542        Some(v) => v & !(ptr_size - 1),
19543        None => return NOSPACE,
19544    };
19545    let ptr_bytes = match (count + 1).checked_mul(ptr_size) {
19546        Some(v) => v,
19547        None => return NOSPACE,
19548    };
19549    let need = match aligned.checked_sub(base).and_then(|v| v.checked_add(ptr_bytes)) {
19550        Some(v) => v,
19551        None => return NOSPACE,
19552    };
19553    if need > buflen { return NOSPACE; }
19554
19555    let mem = aligned as *mut *mut c_char;
19556    let mut mi = 0usize;
19557    m = fields[3];
19558    if *m != 0 {
19559        loop {
19560            *mem.add(mi) = m;
19561            mi += 1;
19562            while *m != 0 && *m != b',' as c_char { m = m.add(1); }
19563            if *m == 0 { break; }
19564            *m = 0;
19565            m = m.add(1);
19566        }
19567    }
19568    *mem.add(mi) = core::ptr::null_mut();
19569
19570    (*ent).gr_name = fields[0];
19571    (*ent).gr_passwd = fields[1];
19572    (*ent).gr_gid = crate::strtol(fields[2], core::ptr::null_mut(), 10) as u32;
19573    (*ent).gr_mem = mem;
19574    OK
19575}
19576
19577unsafe fn getgr_r_inner(
19578    name: *const c_char,
19579    gid: Option<u32>,
19580    grp: *mut Group,
19581    buf: *mut c_char,
19582    buflen: usize,
19583    result: *mut *mut Group,
19584) -> c_int {
19585    if grp.is_null() || buf.is_null() || result.is_null() || (gid.is_none() && name.is_null()) {
19586        return EINVAL;
19587    }
19588    *result = core::ptr::null_mut();
19589    let f = crate::fopen(b"/etc/group\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
19590    if f.is_null() { return ERRNO!(); }
19591    let mut line: *mut c_char = core::ptr::null_mut();
19592    let mut cap: usize = 0;
19593    let mut err = 0;
19594    loop {
19595        let n = crate::getline(&raw mut line, &raw mut cap, f);
19596        if n < 0 { break; }
19597        if n > 0 && *line.add(n as usize - 1) == b'\n' as c_char {
19598            *line.add(n as usize - 1) = 0;
19599        }
19600        let r = parse_group_r(line, grp, buf, buflen);
19601        if r == -2 {
19602            err = ERANGE;
19603            break;
19604        }
19605        if r == 0 {
19606            let hit = if let Some(gid) = gid {
19607                (*grp).gr_gid == gid
19608            } else {
19609                crate::strcmp((*grp).gr_name as *const u8, name as *const u8) == 0
19610            };
19611            if hit {
19612                *result = grp;
19613                break;
19614            }
19615        }
19616    }
19617    crate::free(line as *mut c_void);
19618    crate::fclose(f);
19619    err
19620}
19621
19622#[no_mangle]
19623pub 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 {
19624    getgr_r_inner(name, None, grp, buf, buflen, result)
19625}
19626
19627#[no_mangle]
19628pub unsafe extern "C" fn getgrgid_r(gid: u32, grp: *mut Group, buf: *mut c_char, buflen: usize, result: *mut *mut Group) -> c_int {
19629    getgr_r_inner(core::ptr::null(), Some(gid), grp, buf, buflen, result)
19630}
19631
19632#[no_mangle]
19633pub unsafe extern "C" fn fgetgrent(f: *mut FILE) -> *mut Group {
19634    if f.is_null() { return core::ptr::null_mut(); }
19635    loop {
19636        let n = crate::getline(&raw mut GRP_LINE, &raw mut GRP_LINE_CAP, f);
19637        if n < 0 { return core::ptr::null_mut(); }
19638        let mut len = n as usize;
19639        if len > 0 && *GRP_LINE.add(len - 1) == b'\n' as c_char {
19640            *GRP_LINE.add(len - 1) = 0;
19641            len -= 1;
19642        }
19643        let need = len + 1;
19644        if !ensure_grp_buf(need) { return core::ptr::null_mut(); }
19645        if parse_group(GRP_LINE, &raw mut GRP_ENT, GRP_BUF, need) {
19646            return &raw mut GRP_ENT;
19647        }
19648    }
19649}
19650
19651#[no_mangle]
19652pub unsafe extern "C" fn putgrent(f: *mut FILE, g: *const Group) -> c_int {
19653    if f.is_null() || g.is_null() { return -1; }
19654    crate::fprintf(f, b"%s:%s:%u:\0".as_ptr() as *const c_char, (*g).gr_name, (*g).gr_passwd, (*g).gr_gid);
19655    if !(*g).gr_mem.is_null() {
19656        let mut i = 0;
19657        while !(*(*g).gr_mem.add(i)).is_null() {
19658            if i > 0 { crate::fputc(b',' as c_int, f); }
19659            crate::fputs(*(*g).gr_mem.add(i), f);
19660            i += 1;
19661        }
19662    }
19663    crate::fputc(b'\n' as c_int, f);
19664    0
19665}
19666
19667// ============================================================
19668// User/group functions
19669// ============================================================
19670
19671#[no_mangle]
19672pub unsafe extern "C" fn setgroups(ngroups: usize, gidset: *const u32) -> i32 {
19673    syscall_ret(<Arch as Syscalls>::syscall2(SYS_SETGROUPS, ngroups as i64, gidset as i64)) as i32
19674}
19675
19676#[no_mangle]
19677pub unsafe extern "C" fn setresuid(ruid: u32, euid: u32, suid: u32) -> i32 {
19678    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETRESUID, ruid as i64, euid as i64, suid as i64)) as i32
19679}
19680
19681#[no_mangle]
19682pub unsafe extern "C" fn setresgid(rgid: u32, egid: u32, sgid: u32) -> i32 {
19683    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETRESGID, rgid as i64, egid as i64, sgid as i64)) as i32
19684}
19685
19686#[no_mangle]
19687pub unsafe extern "C" fn getresuid(ruid: *mut u32, euid: *mut u32, suid: *mut u32) -> i32 {
19688    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETRESUID, ruid as i64, euid as i64, suid as i64)) as i32
19689}
19690
19691#[no_mangle]
19692pub unsafe extern "C" fn getresgid(rgid: *mut u32, egid: *mut u32, sgid: *mut u32) -> i32 {
19693    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETRESGID, rgid as i64, egid as i64, sgid as i64)) as i32
19694}
19695
19696// ============================================================
19697// Socket functions
19698// ============================================================
19699
19700// musl's public struct msghdr uses 32-bit msg_iovlen/msg_controllen followed
19701// by padding on 64-bit little-endian. The kernel reads 64-bit fields, so the
19702// padding must be zero; callers (nginx, for example) do not initialize it.
19703#[repr(C)]
19704struct KernelMsgHdr {
19705    msg_name: *mut c_void,
19706    msg_namelen: u32,
19707    __pad0: u32,
19708    msg_iov: *mut c_void,
19709    msg_iovlen: u64,
19710    msg_control: *mut c_void,
19711    msg_controllen: u64,
19712    msg_flags: u32,
19713    __pad1: u32,
19714}
19715
19716#[repr(C)]
19717struct UserMsgHdr {
19718    msg_name: *mut c_void,
19719    msg_namelen: u32,
19720    msg_iov: *mut c_void,
19721    msg_iovlen: i32,
19722    __pad1: i32,
19723    msg_control: *mut c_void,
19724    msg_controllen: u32,
19725    __pad2: i32,
19726    msg_flags: i32,
19727}
19728
19729unsafe fn msg_to_kernel(msg: *const UserMsgHdr, out: &mut KernelMsgHdr) {
19730    *out = KernelMsgHdr {
19731        msg_name: (*msg).msg_name,
19732        msg_namelen: (*msg).msg_namelen,
19733        __pad0: 0,
19734        msg_iov: (*msg).msg_iov,
19735        msg_iovlen: (*msg).msg_iovlen as u32 as u64,
19736        msg_control: (*msg).msg_control,
19737        msg_controllen: (*msg).msg_controllen as u64,
19738        msg_flags: (*msg).msg_flags as u32,
19739        __pad1: 0,
19740    };
19741}
19742
19743#[no_mangle]
19744pub unsafe extern "C" fn sendmsg(fd: i32, msg: *const core::ffi::c_void, flags: i32) -> isize {
19745    if msg.is_null() {
19746        ERRNO!() = EINVAL;
19747        return -1;
19748    }
19749    let mut k: KernelMsgHdr = core::mem::zeroed();
19750    msg_to_kernel(msg as *const UserMsgHdr, &mut k);
19751    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SENDMSG, fd as i64, &k as *const KernelMsgHdr as i64, flags as i64)) as isize
19752}
19753
19754#[no_mangle]
19755pub unsafe extern "C" fn recvmsg(fd: i32, msg: *mut core::ffi::c_void, flags: i32) -> isize {
19756    if msg.is_null() {
19757        ERRNO!() = EINVAL;
19758        return -1;
19759    }
19760    let user = msg as *mut UserMsgHdr;
19761    let mut k: KernelMsgHdr = core::mem::zeroed();
19762    msg_to_kernel(user, &mut k);
19763    let r = syscall_ret(<Arch as Syscalls>::syscall3(SYS_RECVMSG, fd as i64, &mut k as *mut KernelMsgHdr as i64, flags as i64));
19764    (*user).msg_flags = k.msg_flags as i32;
19765    (*user).msg_controllen = k.msg_controllen as u32;
19766    r as isize
19767}
19768
19769#[no_mangle]
19770pub unsafe extern "C" fn sendmmsg(fd: i32, msgvec: *mut core::ffi::c_void, vlen: u32, flags: i32) -> i32 {
19771    syscall_ret(<Arch as Syscalls>::syscall4(SYS_SENDMMSG, fd as i64, msgvec as i64, vlen as i64, flags as i64)) as i32
19772}
19773
19774#[no_mangle]
19775pub unsafe extern "C" fn recvmmsg(fd: i32, msgvec: *mut core::ffi::c_void, vlen: u32, flags: i32, timeout: *mut core::ffi::c_void) -> i32 {
19776    syscall_ret(<Arch as Syscalls>::syscall5(SYS_RECVMMSG, fd as i64, msgvec as i64, vlen as i64, flags as i64, timeout as i64)) as i32
19777}
19778
19779#[no_mangle]
19780pub unsafe extern "C" fn getpeername(fd: i32, addr: *mut core::ffi::c_void, addrlen: *mut u32) -> i32 {
19781    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETPEERNAME, fd as i64, addr as i64, addrlen as i64)) as i32
19782}
19783
19784#[no_mangle]
19785pub unsafe extern "C" fn getsockopt(fd: i32, level: i32, optname: i32, optval: *mut core::ffi::c_void, optlen: *mut u32) -> i32 {
19786    syscall_ret(<Arch as Syscalls>::syscall5(SYS_GETSOCKOPT, fd as i64, level as i64, optname as i64, optval as i64, optlen as i64)) as i32
19787}
19788
19789// ============================================================
19790// stdio unlocked functions
19791// ============================================================
19792
19793#[no_mangle]
19794pub unsafe extern "C" fn ftrylockfile(file: *mut FILE) -> i32 {
19795    if file.is_null() { return EINVAL; }
19796    if (*file).lock < 0 { return 0; }
19797    let tid = sys_gettid() as c_int;
19798    let v = a_load(&raw const (*file).lock);
19799    if v == tid {
19800        (*file).lockcount += 1;
19801        return 0;
19802    }
19803    if v == 0 && a_cas(&raw mut (*file).lock, 0, tid) == 0 {
19804        (*file).lockcount = 1;
19805        return 0;
19806    }
19807    EBUSY
19808}
19809
19810#[no_mangle]
19811pub unsafe extern "C" fn getc_unlocked(file: *mut core::ffi::c_char) -> i32 {
19812    getc(file as *mut FILE)
19813}
19814
19815#[no_mangle]
19816pub unsafe extern "C" fn getchar_unlocked() -> i32 {
19817    getchar()
19818}
19819
19820#[no_mangle]
19821pub unsafe extern "C" fn putc_unlocked(c: i32, file: *mut core::ffi::c_char) -> i32 {
19822    putc(c, file as *mut FILE)
19823}
19824
19825#[no_mangle]
19826pub unsafe extern "C" fn putchar_unlocked(c: i32) -> i32 {
19827    putchar(c)
19828}
19829
19830// ============================================================
19831// getopt functions
19832// ============================================================
19833
19834#[no_mangle] pub static mut optarg: *mut core::ffi::c_char = core::ptr::null_mut();
19835#[no_mangle] pub static mut optind: i32 = 1;
19836#[no_mangle] pub static mut opterr: i32 = 1;
19837#[no_mangle] pub static mut optopt: i32 = '?' as i32;
19838#[no_mangle] pub static mut optreset: i32 = 0;
19839
19840// ============================================================
19841// Timer functions
19842// ============================================================
19843
19844#[no_mangle]
19845pub unsafe extern "C" fn getitimer(which: i32, curr_value: *mut core::ffi::c_void) -> i32 {
19846    syscall_ret(<Arch as Syscalls>::syscall2(SYS_GETITIMER, which as i64, curr_value as i64)) as i32
19847}
19848
19849#[no_mangle]
19850pub unsafe extern "C" fn setitimer(which: i32, new_value: *const core::ffi::c_void, old_value: *mut core::ffi::c_void) -> i32 {
19851    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETITIMER, which as i64, new_value as i64, old_value as i64)) as i32
19852}
19853
19854// ============================================================
19855// System info functions
19856// ============================================================
19857
19858#[no_mangle]
19859pub unsafe extern "C" fn getloadavg(loadavg: *mut f64, nelem: i32) -> i32 {
19860    let fd = crate::open(b"/proc/loadavg\0".as_ptr() as *const core::ffi::c_char, 0, 0);
19861    if fd < 0 { return -1; }
19862    let mut buf: [u8; 64] = [0; 64];
19863    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
19864    crate::close(fd);
19865    if n <= 0 { return -1; }
19866    buf[n as usize] = 0;
19867    if loadavg.is_null() || nelem <= 0 { return -1; }
19868    let mut p = buf.as_ptr() as *const core::ffi::c_char;
19869    let mut i = 0usize;
19870    while i < nelem as usize && i < 3 {
19871        let mut end: *mut core::ffi::c_char = core::ptr::null_mut();
19872        let val = crate::strtod(p, &mut end);
19873        if end as *const core::ffi::c_char == p { break; }
19874        *loadavg.add(i) = val;
19875        i += 1;
19876        p = end;
19877        while *p == b' ' as c_char || *p == b'\t' as c_char || *p == b'\n' as c_char {
19878            p = p.add(1);
19879        }
19880    }
19881    i as i32
19882}
19883
19884#[no_mangle]
19885pub unsafe extern "C" fn get_nprocs() -> i32 {
19886    sysconf(84) as i32 // _SC_NPROCESSORS_ONLN
19887}
19888
19889#[no_mangle]
19890pub unsafe extern "C" fn get_nprocs_conf() -> i32 {
19891    sysconf(83) as i32 // _SC_NPROCESSORS_CONF
19892}
19893
19894#[no_mangle]
19895pub unsafe extern "C" fn get_avphys_pages() -> i64 {
19896    sysconf(86) // _SC_AVPHYS_PAGES
19897}
19898
19899#[no_mangle]
19900pub unsafe extern "C" fn get_phys_pages() -> i64 {
19901    sysconf(85) // _SC_PHYS_PAGES
19902}
19903
19904// ============================================================
19905// Capability functions
19906// ============================================================
19907
19908#[no_mangle]
19909pub unsafe extern "C" fn capget(header: *mut core::ffi::c_void, data: *mut core::ffi::c_void) -> i32 {
19910    syscall_ret(<Arch as Syscalls>::syscall2(SYS_CAPGET, header as i64, data as i64)) as i32
19911}
19912
19913#[no_mangle]
19914pub unsafe extern "C" fn capset(header: *const core::ffi::c_void, data: *const core::ffi::c_void) -> i32 {
19915    syscall_ret(<Arch as Syscalls>::syscall2(SYS_CAPSET, header as i64, data as i64)) as i32
19916}
19917
19918#[no_mangle]
19919pub unsafe extern "C" fn arch_prctl(code: i32, addr: u64) -> i32 {
19920    #[cfg(target_arch = "x86_64")]
19921    { syscall_ret(<Arch as Syscalls>::syscall2(crate::SYS_ARCH_PRCTL, code as i64, addr as i64)) as i32 }
19922    #[cfg(not(target_arch = "x86_64"))]
19923    { let _ = (code, addr); ERRNO!() = ENOSYS; -1 }
19924}
19925
19926// ============================================================
19927// termios functions
19928// ============================================================
19929
19930#[no_mangle]
19931pub unsafe extern "C" fn cfgetospeed(termios_p: *const core::ffi::c_void) -> u32 {
19932    unsafe { *(termios_p as *const u32).add(1) }
19933}
19934
19935#[no_mangle]
19936pub unsafe extern "C" fn cfgetispeed(termios_p: *const core::ffi::c_void) -> u32 {
19937    unsafe { *(termios_p as *const u32).add(2) }
19938}
19939
19940#[no_mangle]
19941pub unsafe extern "C" fn cfsetospeed(termios_p: *mut core::ffi::c_void, speed: u32) -> i32 {
19942    unsafe { *(termios_p as *mut u32).add(1) = speed; }
19943    0
19944}
19945
19946#[no_mangle]
19947pub unsafe extern "C" fn cfsetispeed(termios_p: *mut core::ffi::c_void, speed: u32) -> i32 {
19948    unsafe { *(termios_p as *mut u32).add(2) = speed; }
19949    0
19950}
19951
19952#[no_mangle]
19953pub unsafe extern "C" fn cfmakeraw(termios_p: *mut core::ffi::c_void) {
19954    unsafe {
19955        let p = termios_p as *mut u32;
19956        *p.add(0) &= !0o37;
19957        *p.add(0) &= !(0o4000 | 0o2000 | 0o10000 | 0o20);
19958        *p.add(0) |= 0o60;
19959        *p.add(3) &= !0o17;
19960        *p.add(3) &= !(0o1000 | 0o40000000);
19961        *p.add(1) = 1;
19962        *p.add(2) = 0;
19963    }
19964}
19965
19966// ============================================================
19967// Resource functions
19968// ============================================================
19969
19970#[no_mangle]
19971pub unsafe extern "C" fn getrusage(who: i32, usage: *mut core::ffi::c_void) -> i32 {
19972    syscall_ret(<Arch as Syscalls>::syscall2(SYS_GETRUSAGE, who as i64, usage as i64)) as i32
19973}
19974
19975#[no_mangle]
19976pub unsafe extern "C" fn getpriority(which: i32, who: u32) -> i32 {
19977    // The kernel encodes nice as 20 - nice; musl converts it back.
19978    let r = <Arch as Syscalls>::syscall2(SYS_GETPRIORITY, which as i64, who as i64);
19979    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
19980    20 - r as i32
19981}
19982
19983#[no_mangle]
19984pub unsafe extern "C" fn setpriority(which: i32, who: u32, prio: i32) -> i32 {
19985    syscall_ret(<Arch as Syscalls>::syscall3(SYS_SETPRIORITY, which as i64, who as i64, prio as i64)) as i32
19986}
19987
19988#[no_mangle]
19989pub unsafe extern "C" fn prlimit(pid: u32, resource: i32, new_limit: *const core::ffi::c_void, old_limit: *mut core::ffi::c_void) -> i32 {
19990    syscall_ret(<Arch as Syscalls>::syscall4(SYS_PRLIMIT64, pid as i64, resource as i64, new_limit as i64, old_limit as i64)) as i32
19991}
19992
19993// ============================================================
19994// fork/clone functions
19995// ============================================================
19996
19997#[no_mangle]
19998pub unsafe extern "C" fn clone(
19999    func: usize,
20000    stack: *mut u8,
20001    flags: c_int,
20002    arg: *mut c_void,
20003    mut args: ...
20004) -> c_int {
20005    // musl-compatible signature: clone(fn, stack, flags, arg, ptid, tls, ctid).
20006    const CLONE_PIDFD_C: c_int = 0x00001000;
20007    const CLONE_VM_C: c_int = 0x00000100;
20008    const CLONE_THREAD_C: c_int = 0x00010000;
20009    const CLONE_SETTLS_C: c_int = 0x00080000;
20010    const CLONE_PARENT_SETTID_C: c_int = 0x00100000;
20011    const CLONE_CHILD_SETTID_C: c_int = 0x01000000;
20012    const CLONE_CHILD_CLEARTID_C: c_int = 0x00200000;
20013    let _ = CLONE_VM_C;
20014    if flags & (CLONE_THREAD_C | CLONE_SETTLS_C | CLONE_CHILD_CLEARTID_C) != 0
20015        || stack.is_null()
20016    {
20017        ERRNO!() = EINVAL;
20018        return -1;
20019    }
20020    let mut ptid: *mut c_int = core::ptr::null_mut();
20021    let mut tls: c_ulong = 0;
20022    let mut ctid: *mut c_int = core::ptr::null_mut();
20023    if flags & (CLONE_PIDFD_C | CLONE_PARENT_SETTID_C | CLONE_CHILD_SETTID_C) != 0 {
20024        ptid = args.next_arg::<*mut c_int>();
20025    }
20026    if flags & CLONE_CHILD_SETTID_C != 0 {
20027        tls = args.next_arg::<c_ulong>();
20028        ctid = args.next_arg::<*mut c_int>();
20029    }
20030    let r = __keel_clone(func, stack, flags as c_ulong, arg, ptid, tls, ctid);
20031    syscall_ret(r) as c_int
20032}
20033
20034#[no_mangle]
20035pub unsafe extern "C" fn _Fork() -> i32 {
20036    crate::fork()
20037}
20038
20039#[no_mangle]
20040pub 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 {
20041    let mut master: i32 = 0;
20042    let mut slave: i32 = 0;
20043    if openpty(&mut master, &mut slave, name, termp, winp) < 0 { return -1; }
20044    let pid = crate::fork();
20045    if pid < 0 { crate::close(master); crate::close(slave); return -1; }
20046    if pid == 0 {
20047        crate::close(master);
20048        crate::setsid();
20049        crate::dup2(slave, 0);
20050        crate::dup2(slave, 1);
20051        crate::dup2(slave, 2);
20052    } else {
20053        crate::close(slave);
20054        if !amaster.is_null() { *amaster = master; }
20055    }
20056    pid
20057}
20058
20059#[no_mangle]
20060pub 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 {
20061    let master = crate::open(b"/dev/ptmx\0".as_ptr() as *const core::ffi::c_char, 0o2000, 0);
20062    if master < 0 { return -1; }
20063    grantpt(master);
20064    unlockpt(master);
20065    let slave_name = ptsname(master);
20066    if slave_name.is_null() { crate::close(master); return -1; }
20067    let slave = crate::open(slave_name, 0o2000, 0);
20068    if slave < 0 { crate::close(master); return -1; }
20069    if !amaster.is_null() { *amaster = master; }
20070    if !aslave.is_null() { *aslave = slave; }
20071    if !name.is_null() { crate::strcpy(name as *mut u8, slave_name as *const u8); }
20072    0
20073}
20074
20075#[no_mangle]
20076pub unsafe extern "C" fn login_tty(fd: i32) -> i32 {
20077    crate::setsid();
20078    crate::dup2(fd, 0);
20079    crate::dup2(fd, 1);
20080    crate::dup2(fd, 2);
20081    0
20082}
20083
20084// ============================================================
20085// dl functions
20086// ============================================================
20087
20088#[no_mangle]
20089pub unsafe extern "C" fn __dls2b() {}
20090#[no_mangle]
20091pub unsafe extern "C" fn __dls3() {}
20092#[no_mangle]
20093pub unsafe extern "C" fn _dlstart() {}
20094
20095// ============================================================
20096// string functions
20097// ============================================================
20098
20099#[no_mangle]
20100pub unsafe extern "C" fn index(s: *const core::ffi::c_char, c: i32) -> *mut core::ffi::c_char {
20101    let mut i = 0;
20102    loop {
20103        let ch = *s.add(i);
20104        if ch == c as core::ffi::c_char { return s.add(i) as *mut core::ffi::c_char; }
20105        if ch == 0 { return core::ptr::null_mut(); }
20106        i += 1;
20107    }
20108}
20109
20110#[no_mangle]
20111pub unsafe extern "C" fn rindex(s: *const core::ffi::c_char, c: i32) -> *mut core::ffi::c_char {
20112    let mut last = core::ptr::null_mut();
20113    let mut i = 0;
20114    loop {
20115        let ch = *s.add(i);
20116        if ch == 0 { return last; }
20117        if ch == c as core::ffi::c_char { last = s.add(i) as *mut core::ffi::c_char; }
20118        i += 1;
20119    }
20120}
20121
20122// ============================================================
20123// intmax functions
20124// ============================================================
20125
20126#[no_mangle]
20127pub unsafe extern "C" fn imaxabs(j: i64) -> i64 {
20128    j.abs()
20129}
20130
20131#[no_mangle]
20132pub unsafe extern "C" fn imaxdiv(numer: i64, denom: i64) -> (i64, i64) {
20133    (numer / denom, numer % denom)
20134}
20135
20136// ============================================================
20137// herror functions
20138// ============================================================
20139
20140#[no_mangle]
20141pub static mut h_errno: i32 = 0;
20142
20143#[no_mangle]
20144pub unsafe extern "C" fn __h_errno_location() -> *mut i32 {
20145    h_errno_ptr()
20146}
20147
20148#[no_mangle]
20149pub unsafe extern "C" fn herror(s: *const core::ffi::c_char) {
20150    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
20151    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20152    let msg = hstrerror(*__h_errno_location());
20153    crate::write(2, msg as *const core::ffi::c_void, crate::strlen(msg));
20154    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20155}
20156
20157#[no_mangle]
20158pub unsafe extern "C" fn hstrerror(err: i32) -> *const core::ffi::c_char {
20159    let msg: &[u8] = match err {
20160        1 => b"Host not found\0",
20161        2 => b"Try again\0",
20162        3 => b"Non-recoverable error\0",
20163        4 => b"Address not available\0",
20164        _ => b"Unknown error\0",
20165    };
20166    msg.as_ptr() as *const core::ffi::c_char
20167}
20168
20169// ============================================================
20170// gettid function
20171// ============================================================
20172
20173#[no_mangle]
20174pub unsafe extern "C" fn gettid() -> i32 {
20175    syscall_ret(<Arch as Syscalls>::syscall0(SYS_GETTID)) as i32
20176}
20177
20178// ============================================================
20179// ioctl functions
20180// ============================================================
20181
20182#[no_mangle]
20183pub unsafe extern "C" fn ioctl(fd: i32, request: u32, mut args: ...) -> i32 {
20184    let arg = args.next_arg::<i64>();
20185    syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg)) as i32
20186}
20187
20188#[no_mangle]
20189pub unsafe extern "C" fn ioperm(from: u64, num: u64, turn_on: i32) -> i32 {
20190    #[cfg(target_arch = "x86_64")]
20191    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_IOPERM, from as i64, num as i64, turn_on as i64)) as i32 }
20192    #[cfg(not(target_arch = "x86_64"))]
20193    {
20194        let _ = (from, num, turn_on);
20195        ERRNO!() = ENOSYS;
20196        -1
20197    }
20198}
20199
20200#[no_mangle]
20201pub unsafe extern "C" fn iopl(level: i32) -> i32 {
20202    #[cfg(target_arch = "x86_64")]
20203    { syscall_ret(<Arch as Syscalls>::syscall1(SYS_IOPL, level as i64)) as i32 }
20204    #[cfg(not(target_arch = "x86_64"))]
20205    {
20206        let _ = level;
20207        ERRNO!() = ENOSYS;
20208        -1
20209    }
20210}
20211
20212// ============================================================
20213// xattr functions
20214// ============================================================
20215
20216#[no_mangle]
20217pub unsafe extern "C" fn getxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
20218    syscall_ret(<Arch as Syscalls>::syscall4(SYS_GETXATTR, path as i64, name as i64, value as i64, size as i64)) as isize
20219}
20220
20221#[no_mangle]
20222pub unsafe extern "C" fn lgetxattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
20223    syscall_ret(<Arch as Syscalls>::syscall4(SYS_LGETXATTR, path as i64, name as i64, value as i64, size as i64)) as isize
20224}
20225
20226#[no_mangle]
20227pub unsafe extern "C" fn fgetxattr(fd: i32, name: *const core::ffi::c_char, value: *mut u8, size: usize) -> isize {
20228    syscall_ret(<Arch as Syscalls>::syscall4(SYS_FGETXATTR, fd as i64, name as i64, value as i64, size as i64)) as isize
20229}
20230
20231#[no_mangle]
20232pub unsafe extern "C" fn listxattr(path: *const core::ffi::c_char, list: *mut u8, size: usize) -> isize {
20233    syscall_ret(<Arch as Syscalls>::syscall3(SYS_LISTXATTR, path as i64, list as i64, size as i64)) as isize
20234}
20235
20236#[no_mangle]
20237pub unsafe extern "C" fn llistxattr(path: *const core::ffi::c_char, list: *mut u8, size: usize) -> isize {
20238    syscall_ret(<Arch as Syscalls>::syscall3(SYS_LLISTXATTR, path as i64, list as i64, size as i64)) as isize
20239}
20240
20241#[no_mangle]
20242pub unsafe extern "C" fn flistxattr(fd: i32, list: *mut u8, size: usize) -> isize {
20243    syscall_ret(<Arch as Syscalls>::syscall3(SYS_FLISTXATTR, fd as i64, list as i64, size as i64)) as isize
20244}
20245
20246#[no_mangle]
20247pub 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 {
20248    syscall_ret(<Arch as Syscalls>::syscall5(SYS_SETXATTR, path as i64, name as i64, value as i64, size as i64, flags as i64)) as i32
20249}
20250
20251#[no_mangle]
20252pub 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 {
20253    syscall_ret(<Arch as Syscalls>::syscall5(SYS_LSETXATTR, path as i64, name as i64, value as i64, size as i64, flags as i64)) as i32
20254}
20255
20256#[no_mangle]
20257pub unsafe extern "C" fn fsetxattr(fd: i32, name: *const core::ffi::c_char, value: *const u8, size: usize, flags: i32) -> i32 {
20258    syscall_ret(<Arch as Syscalls>::syscall5(SYS_FSETXATTR, fd as i64, name as i64, value as i64, size as i64, flags as i64)) as i32
20259}
20260
20261#[no_mangle]
20262pub unsafe extern "C" fn removexattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char) -> i32 {
20263    syscall_ret(<Arch as Syscalls>::syscall2(SYS_REMOVEXATTR, path as i64, name as i64)) as i32
20264}
20265
20266#[no_mangle]
20267pub unsafe extern "C" fn lremovexattr(path: *const core::ffi::c_char, name: *const core::ffi::c_char) -> i32 {
20268    syscall_ret(<Arch as Syscalls>::syscall2(SYS_LREMOVEXATTR, path as i64, name as i64)) as i32
20269}
20270
20271#[no_mangle]
20272pub unsafe extern "C" fn fremovexattr(fd: i32, name: *const core::ffi::c_char) -> i32 {
20273    syscall_ret(<Arch as Syscalls>::syscall2(SYS_FREMOVEXATTR, fd as i64, name as i64)) as i32
20274}
20275
20276// ============================================================
20277// adjtime functions
20278// ============================================================
20279
20280#[repr(C)]
20281struct TimexBuf {
20282    modes: c_uint,
20283    offset: c_long,
20284    freq: c_long,
20285    maxerror: c_long,
20286    esterror: c_long,
20287    status: c_int,
20288    constant: c_long,
20289    precision: c_long,
20290    tolerance: c_long,
20291    time: timeval,
20292    tick: c_long,
20293    ppsfreq: c_long,
20294    jitter: c_long,
20295    shift: c_int,
20296    stabil: c_long,
20297    jitcnt: c_long,
20298    calcnt: c_long,
20299    errcnt: c_long,
20300    stbcnt: c_long,
20301    tai: c_int,
20302    padding: [c_int; 11],
20303}
20304
20305#[no_mangle]
20306pub unsafe extern "C" fn adjtime(delta: *const timeval, olddelta: *mut timeval) -> i32 {
20307    // Port of musl's linux/adjtime.c.
20308    let mut tx: TimexBuf = core::mem::zeroed();
20309    if !delta.is_null() {
20310        if (*delta).tv_sec > 1000 || (*delta).tv_usec > 1_000_000_000 {
20311            ERRNO!() = EINVAL;
20312            return -1;
20313        }
20314        tx.offset = (*delta).tv_sec * 1_000_000 + (*delta).tv_usec;
20315        tx.modes = 0x8001; // ADJ_OFFSET_SINGLESHOT
20316    }
20317    let r = <Arch as Syscalls>::syscall1(SYS_ADJTIMEX, &mut tx as *mut TimexBuf as i64);
20318    if r < 0 {
20319        ERRNO!() = (-r) as c_int;
20320        return -1;
20321    }
20322    if !olddelta.is_null() {
20323        let mut sec = tx.offset / 1_000_000;
20324        let mut usec = tx.offset % 1_000_000;
20325        if usec < 0 {
20326            sec -= 1;
20327            usec += 1_000_000;
20328        }
20329        (*olddelta).tv_sec = sec;
20330        (*olddelta).tv_usec = usec;
20331    }
20332    0
20333}
20334
20335#[no_mangle]
20336pub unsafe extern "C" fn adjtimex(buf: *mut core::ffi::c_void) -> i32 {
20337    syscall_ret(<Arch as Syscalls>::syscall1(SYS_ADJTIMEX, buf as i64)) as i32
20338}
20339
20340// ============================================================
20341// pty functions
20342// ============================================================
20343
20344// Linux devpts ioctls (asm-generic/ioctls.h): TIOCGPTN = _IOR('T', 0x30, int),
20345// TIOCSPTLCK = _IOW('T', 0x31, int). The old 0x541x values are the window-size
20346// and process-group requests, which both return the wrong data and write more
20347// bytes than the int the caller supplied.
20348const TIOCGPTN: i64 = 0x80045430;
20349const TIOCSPTLCK: i64 = 0x40045431;
20350
20351#[no_mangle]
20352pub unsafe extern "C" fn grantpt(_fd: i32) -> i32 {
20353    // devpts creates the slave already owned by the caller.
20354    0
20355}
20356
20357#[no_mangle]
20358pub unsafe extern "C" fn unlockpt(fd: i32) -> i32 {
20359    let mut unlock: i32 = 0;
20360    let r = <Arch as Syscalls>::syscall3(
20361        SYS_IOCTL,
20362        fd as i64,
20363        TIOCSPTLCK,
20364        &mut unlock as *mut i32 as i64,
20365    );
20366    syscall_ret(r) as c_int
20367}
20368
20369#[no_mangle]
20370pub unsafe extern "C" fn ptsname(fd: i32) -> *mut core::ffi::c_char {
20371    static mut BUF: [core::ffi::c_char; 32] = [0; 32];
20372    let mut pty_nr: i32 = 0;
20373    if <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, TIOCGPTN, &mut pty_nr as *mut i32 as i64) < 0 {
20374        return core::ptr::null_mut();
20375    }
20376    // Format /dev/pts/N
20377    BUF[0] = '/' as c_char; BUF[1] = 'd' as c_char; BUF[2] = 'e' as c_char; BUF[3] = 'v' as c_char;
20378    BUF[4] = '/' as c_char; BUF[5] = 'p' as c_char; BUF[6] = 't' as c_char; BUF[7] = 's' as c_char;
20379    BUF[8] = '/' as c_char;
20380    let i = 9 + write_decimal(BUF.as_mut_ptr().add(9), pty_nr as usize);
20381    if i >= BUF.len() { return core::ptr::null_mut(); }
20382    BUF[i] = 0;
20383    BUF.as_mut_ptr()
20384}
20385
20386// ============================================================
20387// fpclassify functions
20388// ============================================================
20389
20390#[no_mangle]
20391pub unsafe extern "C" fn finite(x: f64) -> i32 {
20392    (!x.is_nan() && !x.is_infinite()) as i32
20393}
20394
20395#[no_mangle]
20396pub unsafe extern "C" fn finitef(x: f32) -> i32 {
20397    (!x.is_nan() && !x.is_infinite()) as i32
20398}
20399
20400#[no_mangle]
20401pub unsafe extern "C" fn __fpclassifyl(x: f64) -> i32 {
20402    __fpclassify(x)
20403}
20404
20405#[no_mangle]
20406pub unsafe extern "C" fn __signbitl(x: f64) -> i32 {
20407    __signbit(x)
20408}
20409
20410// ============================================================
20411// ftw functions
20412// ============================================================
20413
20414// ============================================================
20415// Bessel functions
20416// ============================================================
20417
20418#[no_mangle]
20419pub unsafe extern "C" fn j0(x: f64) -> f64 {
20420    libm::j0(x)
20421}
20422
20423#[no_mangle]
20424pub unsafe extern "C" fn j0f(x: f32) -> f32 {
20425    libm::j0f(x)
20426}
20427
20428#[no_mangle]
20429pub unsafe extern "C" fn j1(x: f64) -> f64 {
20430    libm::j1(x)
20431}
20432
20433#[no_mangle]
20434pub unsafe extern "C" fn j1f(x: f32) -> f32 {
20435    libm::j1f(x)
20436}
20437
20438#[no_mangle]
20439pub unsafe extern "C" fn jn(n: i32, x: f64) -> f64 {
20440    libm::jn(n, x)
20441}
20442
20443#[no_mangle]
20444pub unsafe extern "C" fn jnf(n: i32, x: f32) -> f32 {
20445    libm::jnf(n, x)
20446}
20447
20448#[no_mangle]
20449pub unsafe extern "C" fn y0(x: f64) -> f64 {
20450    y0_impl(x)
20451}
20452
20453#[no_mangle]
20454pub unsafe extern "C" fn y0f(x: f32) -> f32 {
20455    if x.is_nan() { return x; }
20456    if x < 0.0 { return __math_invalidf(x); }
20457    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f32::NEG_INFINITY; }
20458    libm::y0f(x)
20459}
20460
20461#[no_mangle]
20462pub unsafe extern "C" fn y1(x: f64) -> f64 {
20463    if x.is_nan() { return x; }
20464    if x < 0.0 { return __math_invalid(x); }
20465    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f64::NEG_INFINITY; }
20466    libm::y1(x)
20467}
20468
20469#[no_mangle]
20470pub unsafe extern "C" fn y1f(x: f32) -> f32 {
20471    if x.is_nan() { return x; }
20472    if x < 0.0 { return __math_invalidf(x); }
20473    if x == 0.0 { feraiseexcept(FE_DIVBYZERO); return f32::NEG_INFINITY; }
20474    libm::y1f(x)
20475}
20476
20477#[no_mangle]
20478pub unsafe extern "C" fn yn(n: i32, x: f64) -> f64 {
20479    if x.is_nan() { return x; }
20480    if x < 0.0 { return __math_invalid(x); }
20481    if x == 0.0 {
20482        feraiseexcept(FE_DIVBYZERO);
20483        if n >= 0 { return f64::NEG_INFINITY; }
20484    }
20485    libm::yn(n, x)
20486}
20487
20488#[no_mangle]
20489pub unsafe extern "C" fn ynf(n: i32, x: f32) -> f32 {
20490    if x.is_nan() { return x; }
20491    if x < 0.0 { return __math_invalidf(x); }
20492    if x == 0.0 {
20493        feraiseexcept(FE_DIVBYZERO);
20494        if n >= 0 { return f32::NEG_INFINITY; }
20495    }
20496    libm::ynf(n, x)
20497}
20498
20499// ============================================================
20500// ctype locale functions
20501// ============================================================
20502
20503#[no_mangle]
20504pub unsafe extern "C" fn __isalnum_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20505    (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
20506}
20507
20508#[no_mangle]
20509pub unsafe extern "C" fn __isalpha_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20510    (c >= 'A' as i32 && c <= 'Z' as i32 || c >= 'a' as i32 && c <= 'z' as i32) as i32
20511}
20512
20513#[no_mangle]
20514pub unsafe extern "C" fn __isblank_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20515    (c == ' ' as i32 || c == '\t' as i32) as i32
20516}
20517
20518#[no_mangle]
20519pub unsafe extern "C" fn __iscntrl_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20520    (c < 0x20 || c == 0x7f) as i32
20521}
20522
20523#[no_mangle]
20524pub unsafe extern "C" fn __isdigit_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20525    (c >= '0' as i32 && c <= '9' as i32) as i32
20526}
20527
20528#[no_mangle]
20529pub unsafe extern "C" fn __isgraph_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20530    (c > 0x20 && c < 0x7f) as i32
20531}
20532
20533#[no_mangle]
20534pub unsafe extern "C" fn __islower_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20535    (c >= 'a' as i32 && c <= 'z' as i32) as i32
20536}
20537
20538#[no_mangle]
20539pub unsafe extern "C" fn __isprint_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20540    (c >= 0x20 && c < 0x7f) as i32
20541}
20542
20543#[no_mangle]
20544pub unsafe extern "C" fn __ispunct_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20545    (c >= 0x21 && c <= 0x2f || c >= 0x3a && c <= 0x40 || c >= 0x5b && c <= 0x60 || c >= 0x7b && c <= 0x7e) as i32
20546}
20547
20548#[no_mangle]
20549pub unsafe extern "C" fn __isspace_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20550    (c == ' ' as i32 || c >= 0x09 && c <= 0x0d) as i32
20551}
20552
20553#[no_mangle]
20554pub unsafe extern "C" fn __isupper_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20555    (c >= 'A' as i32 && c <= 'Z' as i32) as i32
20556}
20557
20558#[no_mangle]
20559pub unsafe extern "C" fn __isxdigit_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
20560    (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
20561}
20562
20563// ============================================================
20564// wide char locale functions
20565// ============================================================
20566
20567#[no_mangle]
20568pub unsafe extern "C" fn __iswalnum_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20569    (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
20570}
20571
20572#[no_mangle]
20573pub unsafe extern "C" fn __iswalpha_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20574    (c >= 'A' as u32 && c <= 'Z' as u32 || c >= 'a' as u32 && c <= 'z' as u32) as i32
20575}
20576
20577#[no_mangle]
20578pub unsafe extern "C" fn __iswblank_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20579    (c == ' ' as u32 || c == '\t' as u32) as i32
20580}
20581
20582#[no_mangle]
20583pub unsafe extern "C" fn __iswcntrl_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20584    (c < 0x20 || c == 0x7f) as i32
20585}
20586
20587#[no_mangle]
20588pub unsafe extern "C" fn __iswdigit_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20589    (c >= '0' as u32 && c <= '9' as u32) as i32
20590}
20591
20592#[no_mangle]
20593pub unsafe extern "C" fn __iswgraph_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20594    (c > 0x20 && c < 0x7f) as i32
20595}
20596
20597#[no_mangle]
20598pub unsafe extern "C" fn __iswlower_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20599    (c >= 'a' as u32 && c <= 'z' as u32) as i32
20600}
20601
20602#[no_mangle]
20603pub unsafe extern "C" fn __iswprint_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20604    (c >= 0x20 && c < 0x7f) as i32
20605}
20606
20607#[no_mangle]
20608pub unsafe extern "C" fn __iswpunct_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20609    (c >= 0x21 && c <= 0x2f || c >= 0x3a && c <= 0x40 || c >= 0x5b && c <= 0x60 || c >= 0x7b && c <= 0x7e) as i32
20610}
20611
20612#[no_mangle]
20613pub unsafe extern "C" fn __iswspace_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20614    (c == ' ' as u32 || c >= 0x09 && c <= 0x0d) as i32
20615}
20616
20617#[no_mangle]
20618pub unsafe extern "C" fn __iswupper_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20619    (c >= 'A' as u32 && c <= 'Z' as u32) as i32
20620}
20621
20622#[no_mangle]
20623pub unsafe extern "C" fn __iswxdigit_l(c: u32, _loc: *mut core::ffi::c_void) -> i32 {
20624    (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
20625}
20626
20627#[no_mangle]
20628pub unsafe extern "C" fn __iswctype_l(c: u32, ctype: u32, _loc: *mut core::ffi::c_void) -> i32 {
20629    crate::iswctype(c as wint_t, ctype as wctype_t)
20630}
20631
20632#[no_mangle]
20633pub unsafe extern "C" fn __towlower_l(c: u32, _loc: *mut core::ffi::c_void) -> u32 {
20634    crate::towlower(c)
20635}
20636
20637#[no_mangle]
20638pub unsafe extern "C" fn __towupper_l(c: u32, _loc: *mut core::ffi::c_void) -> u32 {
20639    crate::towupper(c)
20640}
20641
20642#[no_mangle]
20643pub unsafe extern "C" fn __towctrans_l(c: u32, _trans: u32, _loc: *mut core::ffi::c_void) -> u32 {
20644    c
20645}
20646
20647// ============================================================
20648// _r functions
20649// ============================================================
20650
20651// ============================================================
20652// stdio internal functions
20653// ============================================================
20654
20655// ============================================================
20656// Misc functions
20657// ============================================================
20658
20659#[no_mangle]
20660pub 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) {
20661    crate::write(2, b"Assertion failed: ".as_ptr() as *const core::ffi::c_void, 18);
20662    if !expr.is_null() { crate::write(2, expr as *const core::ffi::c_void, crate::strlen(expr)); }
20663    crate::write(2, b" (".as_ptr() as *const core::ffi::c_void, 2);
20664    if !file.is_null() { crate::write(2, file as *const core::ffi::c_void, crate::strlen(file)); }
20665    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20666    let mut n = line as usize;
20667    let mut digits: [u8; 32] = [0; 32];
20668    let mut di = 0;
20669    if n == 0 { digits[0] = 0; di = 1; }
20670    while n > 0 && di < 32 { digits[di] = (n % 10) as u8; n /= 10; di += 1; }
20671    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); }
20672    crate::write(2, b")".as_ptr() as *const core::ffi::c_void, 1);
20673    if !func.is_null() { crate::write(2, func as *const core::ffi::c_void, crate::strlen(func)); }
20674    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20675    crate::abort()
20676}
20677
20678const QUICK_EXIT_MAX: usize = 32;
20679static mut QUICK_EXIT_FNS: [Option<unsafe extern "C" fn()>; QUICK_EXIT_MAX] =
20680    [None; QUICK_EXIT_MAX];
20681static mut QUICK_EXIT_COUNT: usize = 0;
20682
20683#[no_mangle]
20684pub unsafe extern "C" fn at_quick_exit(func: Option<unsafe extern "C" fn()>) -> i32 {
20685    let Some(func) = func else { return -1; };
20686    if QUICK_EXIT_COUNT >= QUICK_EXIT_MAX {
20687        return -1;
20688    }
20689    QUICK_EXIT_FNS[QUICK_EXIT_COUNT] = Some(func);
20690    QUICK_EXIT_COUNT += 1;
20691    0
20692}
20693
20694#[no_mangle]
20695pub unsafe extern "C" fn brk(addr: *mut u8) -> i32 {
20696    syscall_ret(<Arch as Syscalls>::syscall1(SYS_BRK, addr as i64)) as i32
20697}
20698
20699#[no_mangle]
20700pub 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 {
20701    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
20702}
20703
20704#[no_mangle]
20705pub unsafe extern "C" fn ctermid(s: *mut core::ffi::c_char) -> *mut core::ffi::c_char {
20706    static mut BUF: [core::ffi::c_char; 20] = [0; 20];
20707    let dst = if s.is_null() { BUF.as_mut_ptr() } else { s };
20708    let src = b"/dev/tty\0".as_ptr() as *const core::ffi::c_char;
20709    let mut i = 0;
20710    while i < 9 { *dst.add(i) = *src.add(i); i += 1; }
20711    dst
20712}
20713
20714#[no_mangle]
20715pub unsafe extern "C" fn delete_module(name: *const core::ffi::c_char, flags: u32) -> i32 {
20716    syscall_ret(<Arch as Syscalls>::syscall2(SYS_DELETE_MODULE, name as i64, flags as i64)) as i32
20717}
20718
20719
20720
20721
20722
20723#[no_mangle]
20724pub unsafe extern "C" fn __duplocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
20725    loc
20726}
20727
20728#[no_mangle]
20729pub unsafe extern "C" fn euidaccess(pathname: *const core::ffi::c_char, mode: i32) -> i32 {
20730    faccessat(AT_FDCWD, pathname, mode, AT_EACCESS)
20731}
20732
20733#[no_mangle]
20734pub unsafe extern "C" fn fgetln(f: *mut core::ffi::c_void, lenp: *mut usize) -> *mut core::ffi::c_char {
20735    static mut BUF: *mut core::ffi::c_char = core::ptr::null_mut();
20736    static mut CAP: usize = 0;
20737    let n = getline(&raw mut BUF, &raw mut CAP, f as *mut FILE);
20738    if n <= 0 {
20739        if !lenp.is_null() { *lenp = 0; }
20740        return core::ptr::null_mut();
20741    }
20742    if !lenp.is_null() { *lenp = n as usize; }
20743    BUF
20744}
20745
20746#[no_mangle]
20747pub unsafe extern "C" fn fgetws(ws: *mut u32, n: i32, f: *mut core::ffi::c_void) -> *mut u32 {
20748    let mut i = 0;
20749    while i < n - 1 {
20750        let c = getwc(f as *mut core::ffi::c_void);
20751        if c == 0 { break; }
20752        *ws.add(i as usize) = c;
20753        i += 1;
20754        if c == '\n' as u32 { break; }
20755    }
20756    *ws.add(i as usize) = 0;
20757    if i == 0 { core::ptr::null_mut() } else { ws }
20758}
20759
20760#[no_mangle]
20761pub 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 {
20762    if !label.is_null() { crate::write(2, label as *const core::ffi::c_void, crate::strlen(label)); }
20763    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
20764    if !text.is_null() { crate::write(2, text as *const core::ffi::c_void, crate::strlen(text)); }
20765    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
20766    0
20767}
20768
20769#[no_mangle]
20770pub unsafe extern "C" fn ftime(tp: *mut core::ffi::c_void) -> i32 {
20771    let mut tv: timeval = core::mem::zeroed();
20772    if gettimeofday(&mut tv, core::ptr::null_mut()) == 0 {
20773        let tb = tp as *mut Timeb;
20774        (*tb).time = tv.tv_sec;
20775        (*tb).millitm = (tv.tv_usec / 1000) as u16;
20776        (*tb).timezone = 0;
20777        (*tb).dstflag = 0;
20778        0
20779    } else {
20780        -1
20781    }
20782}
20783
20784#[no_mangle]
20785pub unsafe extern "C" fn getdents(fd: i32, dirp: *mut u8, count: usize) -> isize {
20786    syscall_ret(<Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, dirp as i64, count as i64)) as isize
20787}
20788
20789#[no_mangle]
20790pub unsafe extern "C" fn gethostid() -> i64 {
20791    // Read from /proc/sys/kernel/random/boot_id or similar
20792    let fd = crate::open(b"/proc/sys/kernel/random/boot_id\0".as_ptr() as *const core::ffi::c_char, 0, 0);
20793    if fd < 0 { return 0; }
20794    let mut buf: [u8; 64] = [0; 64];
20795    let n = crate::read(fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 63);
20796    crate::close(fd);
20797    if n <= 0 { return 0; }
20798    buf[n as usize] = 0;
20799    crate::strtol(buf.as_ptr() as *const core::ffi::c_char, core::ptr::null_mut(), 16)
20800}
20801
20802#[repr(C)]
20803#[derive(Copy, Clone)]
20804struct TermiosBuf {
20805    c_iflag: u32,
20806    c_oflag: u32,
20807    c_cflag: u32,
20808    c_lflag: u32,
20809    c_line: u8,
20810    c_cc: [u8; 32],
20811    c_ispeed: u32,
20812    c_ospeed: u32,
20813}
20814
20815#[no_mangle]
20816pub unsafe extern "C" fn getpass(prompt: *const core::ffi::c_char) -> *mut core::ffi::c_char {
20817    static mut BUF: [core::ffi::c_char; 256] = [0; 256];
20818    if prompt.is_null() { return core::ptr::null_mut(); }
20819    const O_NOCTTY_V: i32 = 0x100;
20820    const ECHO_V: u32 = 0o10;
20821    const ISIG_V: u32 = 0o1;
20822    const ICANON_V: u32 = 0o2;
20823    const INLCR_V: u32 = 0o100;
20824    const IGNCR_V: u32 = 0o200;
20825    const ICRNL_V: u32 = 0o400;
20826    const TCSAFLUSH_V: i32 = 2;
20827
20828    let fd = crate::open(
20829        b"/dev/tty\0".as_ptr() as *const core::ffi::c_char,
20830        O_RDWR | O_NOCTTY_V | O_CLOEXEC,
20831        0,
20832    );
20833    if fd < 0 { return core::ptr::null_mut(); }
20834    let mut t: TermiosBuf = core::mem::zeroed();
20835    if tcgetattr(fd, &mut t as *mut TermiosBuf as *mut core::ffi::c_void) < 0 {
20836        crate::close(fd);
20837        return core::ptr::null_mut();
20838    }
20839    let old = t;
20840    t.c_lflag &= !(ECHO_V | ISIG_V);
20841    t.c_lflag |= ICANON_V;
20842    t.c_iflag &= !(INLCR_V | IGNCR_V);
20843    t.c_iflag |= ICRNL_V;
20844    tcsetattr(fd, TCSAFLUSH_V, &t as *const TermiosBuf as *const core::ffi::c_void);
20845    tcdrain(fd);
20846    dprintf(fd, b"%s\0".as_ptr() as *const core::ffi::c_char, prompt);
20847    let n = crate::read(fd, BUF.as_mut_ptr() as *mut core::ffi::c_void, BUF.len() - 1);
20848    let ok = n >= 0;
20849    if ok {
20850        let mut len = n as usize;
20851        if (len > 0 && BUF[len - 1] == b'\n' as core::ffi::c_char) || len == BUF.len() - 1 {
20852            len -= 1;
20853        }
20854        BUF[len] = 0;
20855    }
20856    tcsetattr(fd, TCSAFLUSH_V, &old as *const TermiosBuf as *const core::ffi::c_void);
20857    dprintf(fd, b"\n\0".as_ptr() as *const core::ffi::c_char);
20858    crate::close(fd);
20859    if ok { BUF.as_mut_ptr() } else { core::ptr::null_mut() }
20860}
20861
20862#[no_mangle]
20863pub 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 {
20864    let s = *optionp;
20865    if s.is_null() { return -1; }
20866    // Find end of suboption
20867    let mut end = s;
20868    while *end != 0 && *end != ',' as c_char && *end != '=' as c_char { end = end.add(1); }
20869    let eq = *end == '=' as c_char;
20870    if eq { *end = 0; *valuep = end.add(1); }
20871    // Find matching token
20872    let mut i = 0;
20873    loop {
20874        let tok = *tokens.add(i);
20875        if tok.is_null() { break; }
20876        if crate::strcmp(s as *const u8, tok as *const u8) == 0 {
20877            // Skip to next option
20878    while *end != 0 && *end != ',' as c_char { end = end.add(1); }
20879            if *end == ',' as c_char { end = end.add(1); }
20880            *optionp = end;
20881            return i as i32;
20882        }
20883        i += 1;
20884    }
20885    -1
20886}
20887
20888#[no_mangle]
20889pub unsafe extern "C" fn getw(f: *mut core::ffi::c_void) -> i32 {
20890    let c0 = getc(f as *mut FILE);
20891    if c0 < 0 { return -1; }
20892    let c1 = getc(f as *mut FILE);
20893    if c1 < 0 { return -1; }
20894    let c2 = getc(f as *mut FILE);
20895    if c2 < 0 { return -1; }
20896    let c3 = getc(f as *mut FILE);
20897    if c3 < 0 { return -1; }
20898    (c0 | (c1 << 8) | (c2 << 16) | (c3 << 24)) as i32
20899}
20900
20901#[no_mangle]
20902pub unsafe extern "C" fn getwc(f: *mut core::ffi::c_void) -> u32 {
20903    getc(f as *mut FILE) as u32
20904}
20905
20906#[no_mangle]
20907pub unsafe extern "C" fn init_module(module_image: *mut u8, len: usize, param_values: *const core::ffi::c_char) -> i32 {
20908    syscall_ret(<Arch as Syscalls>::syscall3(SYS_INIT_MODULE, module_image as i64, len as i64, param_values as i64)) as i32
20909}
20910
20911
20912
20913#[no_mangle]
20914pub unsafe extern "C" fn issetugid() -> i32 {
20915    let ruid = crate::getuid();
20916    let euid = crate::geteuid();
20917    let rgid = crate::getgid();
20918    let egid = crate::getegid();
20919    (ruid != euid || rgid != egid) as i32
20920}
20921
20922// ============================================================
20923// poll functions
20924// ============================================================
20925
20926#[repr(C)]
20927struct PollTimespec {
20928    tv_sec: i64,
20929    tv_nsec: i64,
20930}
20931
20932#[no_mangle]
20933pub unsafe extern "C" fn poll(fds: *mut core::ffi::c_void, nfds: u32, timeout: i32) -> i32 {
20934    #[cfg(target_arch = "x86_64")]
20935    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_POLL, fds as i64, nfds as i64, timeout as i64)) as i32 }
20936    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
20937    {
20938        // poll(2) does not exist on these architectures.  ppoll(2) takes a
20939        // struct timespec, not a millisecond count; passing the integer
20940        // directly made poll(..., 0) wait forever.
20941        let mut ts = PollTimespec { tv_sec: 0, tv_nsec: 0 };
20942        let ts_ptr = if timeout < 0 {
20943            core::ptr::null()
20944        } else {
20945            ts.tv_sec = (timeout / 1000) as i64;
20946            ts.tv_nsec = ((timeout % 1000) as i64) * 1_000_000;
20947            &ts as *const PollTimespec as *const core::ffi::c_void
20948        };
20949        syscall_ret(<Arch as Syscalls>::syscall5(
20950            SYS_PPOLL,
20951            fds as i64,
20952            nfds as i64,
20953            ts_ptr as i64,
20954            0,
20955            8,
20956        )) as i32
20957    }
20958}
20959
20960#[no_mangle]
20961pub unsafe extern "C" fn ppoll(fds: *mut core::ffi::c_void, nfds: u32, timeout: *const core::ffi::c_void, sigmask: *const u64) -> i32 {
20962    syscall_ret(<Arch as Syscalls>::syscall5(SYS_PPOLL, fds as i64, nfds as i64, timeout as i64, sigmask as i64, 8)) as i32
20963}
20964
20965#[repr(C)]
20966struct PselectSigmask {
20967    ss: *const u64,
20968    ss_len: usize,
20969}
20970
20971#[no_mangle]
20972pub 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 {
20973    // pselect6 takes a { sigset_t *, size_t } pair, not the sigset pointer.
20974    // GNU make blocks SIGCHLD and depends on this temporary mask, so passing
20975    // the pointer directly deadlocks parallel builds.
20976    let arg = PselectSigmask {
20977        ss: sigmask,
20978        ss_len: core::mem::size_of::<SigSetT>(),
20979    };
20980    let arg_ptr = if sigmask.is_null() {
20981        0
20982    } else {
20983        &arg as *const PselectSigmask as i64
20984    };
20985    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
20986}
20987
20988// ============================================================
20989// realpath function
20990// ============================================================
20991
20992// ============================================================
20993// quick_exit function
20994// ============================================================
20995
20996#[no_mangle]
20997pub unsafe extern "C" fn quick_exit(status: i32) -> ! {
20998    // Run handlers in reverse registration order, like atexit.
20999    while QUICK_EXIT_COUNT > 0 {
21000        QUICK_EXIT_COUNT -= 1;
21001        if let Some(func) = QUICK_EXIT_FNS[QUICK_EXIT_COUNT] {
21002            func();
21003        }
21004    }
21005    crate::_exit(status)
21006}
21007
21008// ============================================================
21009// stat functions
21010// ============================================================
21011
21012#[no_mangle]
21013pub unsafe extern "C" fn lstat(path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
21014    let r = <Arch as Syscalls>::syscall4(SYS_NEWFSTATAT, AT_FDCWD as i64, path as i64, buf as i64, AT_SYMLINK_NOFOLLOW as i64);
21015    syscall_ret(r) as c_int
21016}
21017
21018#[no_mangle]
21019pub unsafe extern "C" fn __xstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
21020    crate::stat(path, buf as *mut Stat)
21021}
21022
21023#[no_mangle]
21024pub unsafe extern "C" fn __lxstat(_ver: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void) -> i32 {
21025    crate::lstat(path, buf)
21026}
21027
21028#[no_mangle]
21029pub unsafe extern "C" fn __fxstat(_ver: i32, fd: i32, buf: *mut core::ffi::c_void) -> i32 {
21030    crate::fstat(fd, buf as *mut Stat)
21031}
21032
21033#[no_mangle]
21034pub unsafe extern "C" fn __fxstatat(_ver: i32, dirfd: i32, path: *const core::ffi::c_char, buf: *mut core::ffi::c_void, flags: i32) -> i32 {
21035    crate::fstatat(dirfd, path, buf as *mut Stat, flags)
21036}
21037
21038// ============================================================
21039// mempcpy function
21040// ============================================================
21041
21042#[no_mangle]
21043pub unsafe extern "C" fn mempcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8 {
21044    core::ptr::copy_nonoverlapping(src, dest, n);
21045    dest.add(n)
21046}
21047
21048// ============================================================
21049// mktemp functions
21050// ============================================================
21051
21052#[no_mangle]
21053pub unsafe extern "C" fn mkostemp(template: *mut core::ffi::c_char, flags: i32) -> i32 {
21054    mkstemps_flags(template, 0, flags)
21055}
21056
21057#[no_mangle]
21058pub unsafe extern "C" fn mkstemps(template: *mut core::ffi::c_char, suffixlen: i32) -> i32 {
21059    mkstemps_impl(template, suffixlen)
21060}
21061
21062// ============================================================
21063// system functions
21064// ============================================================
21065
21066const PTRACE_PEEKTEXT: i32 = 1;
21067const PTRACE_PEEKDATA: i32 = 2;
21068const PTRACE_PEEKUSER: i32 = 3;
21069
21070#[no_mangle]
21071pub unsafe extern "C" fn ptrace(request: i32, mut args: ...) -> i64 {
21072    let pid = args.next_arg::<c_long>();
21073    let addr = args.next_arg::<c_long>();
21074    let data = args.next_arg::<c_long>();
21075    // PEEKTEXT/PEEKDATA/PEEKUSER write the result through the data pointer
21076    // (the kernel returns EFAULT for a NULL pointer), so supply a local slot.
21077    if (PTRACE_PEEKTEXT..=PTRACE_PEEKUSER).contains(&request) {
21078        let mut result: c_long = 0;
21079        let r = <Arch as Syscalls>::syscall4(
21080            SYS_PTRACE,
21081            request as i64,
21082            pid,
21083            addr,
21084            &mut result as *mut c_long as i64,
21085        );
21086        if r < 0 {
21087            ERRNO!() = (-r) as c_int;
21088            return -1;
21089        }
21090        return result;
21091    }
21092    syscall_ret(<Arch as Syscalls>::syscall4(SYS_PTRACE, request as i64, pid, addr, data))
21093}
21094
21095#[no_mangle]
21096pub unsafe extern "C" fn personality(persona: u64) -> i64 {
21097    <Arch as Syscalls>::syscall1(SYS_PERSONALITY, persona as i64)
21098}
21099
21100const LINUX_REBOOT_MAGIC1: i64 = 0xfee1dead;
21101const LINUX_REBOOT_MAGIC2: i64 = 0x28121969;
21102
21103#[no_mangle]
21104pub unsafe extern "C" fn reboot(cmd: c_int) -> i32 {
21105    // musl's public API is reboot(cmd), not the four-argument syscall.
21106    syscall_ret(<Arch as Syscalls>::syscall3(
21107        SYS_REBOOT,
21108        LINUX_REBOOT_MAGIC1,
21109        LINUX_REBOOT_MAGIC2,
21110        cmd as i64,
21111    )) as i32
21112}
21113
21114#[no_mangle]
21115pub unsafe extern "C" fn pivot_root(new_root: *const core::ffi::c_char, put_old: *const core::ffi::c_char) -> i32 {
21116    syscall_ret(<Arch as Syscalls>::syscall2(SYS_PIVOT_ROOT, new_root as i64, put_old as i64)) as i32
21117}
21118
21119#[no_mangle]
21120pub 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 {
21121    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
21122}
21123
21124#[no_mangle]
21125pub unsafe extern "C" fn umount(target: *const core::ffi::c_char) -> i32 {
21126    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, 0)) as i32
21127}
21128
21129#[no_mangle]
21130pub unsafe extern "C" fn umount2(target: *const core::ffi::c_char, flags: i32) -> i32 {
21131    syscall_ret(<Arch as Syscalls>::syscall2(SYS_UMOUNT2, target as i64, flags as i64)) as i32
21132}
21133
21134// ============================================================
21135// resolver functions
21136// ============================================================
21137
21138
21139// ============================================================
21140// signal/error functions
21141// ============================================================
21142
21143#[no_mangle]
21144pub unsafe extern "C" fn psiginfo(_pinfo: *const core::ffi::c_void, s: *const core::ffi::c_char) {
21145    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
21146    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
21147}
21148
21149#[no_mangle]
21150pub unsafe extern "C" fn psignal(sig: i32, s: *const core::ffi::c_char) {
21151    if !s.is_null() { crate::write(2, s as *const core::ffi::c_void, crate::strlen(s)); }
21152    crate::write(2, b": ".as_ptr() as *const core::ffi::c_void, 2);
21153    let msg = strsignal(sig);
21154    crate::write(2, msg as *const core::ffi::c_void, crate::strlen(msg));
21155    crate::write(2, b"\n".as_ptr() as *const core::ffi::c_void, 1);
21156}
21157
21158#[no_mangle]
21159pub unsafe extern "C" fn strsignal(sig: c_int) -> *const c_char {
21160    static NAMES: [&[u8]; 32] = [
21161        b"Unknown signal\0",
21162        b"Hangup\0",
21163        b"Interrupt\0",
21164        b"Quit\0",
21165        b"Illegal instruction\0",
21166        b"Trace/breakpoint trap\0",
21167        b"Aborted\0",
21168        b"Bus error\0",
21169        b"Floating point exception\0",
21170        b"Killed\0",
21171        b"User defined signal 1\0",
21172        b"Segmentation fault\0",
21173        b"User defined signal 2\0",
21174        b"Broken pipe\0",
21175        b"Alarm clock\0",
21176        b"Terminated\0",
21177        b"Stack fault\0",
21178        b"Child process status\0",
21179        b"Continued\0",
21180        b"Stopped (signal)\0",
21181        b"Stopped\0",
21182        b"Stopped (tty input)\0",
21183        b"Stopped (tty output)\0",
21184        b"Urgent I/O condition\0",
21185        b"CPU time limit exceeded\0",
21186        b"File size limit exceeded\0",
21187        b"Virtual timer expired\0",
21188        b"Profiling timer expired\0",
21189        b"Window changed\0",
21190        b"I/O possible\0",
21191        b"Power failure\0",
21192        b"Bad system call\0",
21193    ];
21194    static mut RT_BUF: [c_char; 32] = [0; 32];
21195    if sig > 0 && sig < 32 {
21196        return NAMES[sig as usize].as_ptr() as *const c_char;
21197    }
21198    if sig >= 32 && sig < 65 {
21199        let mut o = 0usize;
21200        for &c in b"Real-time signal \0" {
21201            if c == 0 { break; }
21202            RT_BUF[o] = c as c_char;
21203            o += 1;
21204        }
21205        let mut v = (sig - 32) as u32;
21206        let mut digits = [0u8; 10];
21207        let mut d = 0usize;
21208        if v == 0 { digits[0] = b'0'; d = 1; }
21209        while v > 0 { digits[d] = b'0' + (v % 10) as u8; v /= 10; d += 1; }
21210        while d > 0 { d -= 1; RT_BUF[o] = digits[d] as c_char; o += 1; }
21211        RT_BUF[o] = 0;
21212        return RT_BUF.as_ptr();
21213    }
21214    b"Unknown signal\0".as_ptr() as *const c_char
21215}
21216
21217#[no_mangle]
21218pub unsafe extern "C" fn __strerror_l(errnum: i32, _loc: *mut core::ffi::c_void) -> *const core::ffi::c_char {
21219    crate::strerror(errnum)
21220}
21221
21222// ============================================================
21223// preadv functions
21224// ============================================================
21225
21226#[no_mangle]
21227pub unsafe extern "C" fn preadv(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
21228    // preadv takes a 64-bit offset split into pos_l/pos_h on x86_64 and the
21229    // generic ABI; passing only pos_l leaves the high half undefined.
21230    syscall_ret(<Arch as Syscalls>::syscall5(
21231        SYS_PREADV,
21232        fd as i64,
21233        iov as i64,
21234        iovcnt as i64,
21235        offset,
21236        offset >> 32,
21237    )) as isize
21238}
21239
21240#[no_mangle]
21241pub unsafe extern "C" fn pwritev(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64) -> isize {
21242    syscall_ret(<Arch as Syscalls>::syscall5(
21243        SYS_PWRITEV,
21244        fd as i64,
21245        iov as i64,
21246        iovcnt as i64,
21247        offset,
21248        offset >> 32,
21249    )) as isize
21250}
21251
21252#[no_mangle]
21253pub unsafe extern "C" fn preadv2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
21254    // x86_64/generic preadv2 split the 64-bit offset into pos_l/pos_h and
21255    // take the flags as the sixth argument.
21256    syscall_ret(<Arch as Syscalls>::syscall6(
21257        SYS_PREADV2,
21258        fd as i64,
21259        iov as i64,
21260        iovcnt as i64,
21261        offset,
21262        offset >> 32,
21263        flags as i64,
21264    )) as isize
21265}
21266
21267#[no_mangle]
21268pub unsafe extern "C" fn pwritev2(fd: i32, iov: *const core::ffi::c_void, iovcnt: i32, offset: i64, flags: u32) -> isize {
21269    syscall_ret(<Arch as Syscalls>::syscall6(
21270        SYS_PWRITEV2,
21271        fd as i64,
21272        iov as i64,
21273        iovcnt as i64,
21274        offset,
21275        offset >> 32,
21276        flags as i64,
21277    )) as isize
21278}
21279
21280// ============================================================
21281// nice function
21282// ============================================================
21283
21284#[no_mangle]
21285pub unsafe extern "C" fn nice(inc: i32) -> i32 {
21286    let mut prio = inc;
21287    if inc > -40 && inc < 40 {
21288        prio += getpriority(0, 0);
21289    }
21290    if prio > 19 { prio = 19; }
21291    if prio < -20 { prio = -20; }
21292    if setpriority(0, 0, prio) != 0 {
21293        if ERRNO!() == EACCES { ERRNO!() = EPERM; } // EACCES -> EPERM, as musl does
21294        return -1;
21295    }
21296    prio
21297}
21298
21299// ============================================================
21300// misc functions
21301// ============================================================
21302
21303const A64L_DIGITS: &[u8; 64] =
21304    b"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
21305
21306#[no_mangle]
21307pub unsafe extern "C" fn l64a(value: i64) -> *mut core::ffi::c_char {
21308    static mut BUF: [core::ffi::c_char; 7] = [0; 7];
21309    let mut v = value as u32;
21310    let mut i = 0;
21311    while v > 0 && i < 6 {
21312        BUF[i] = A64L_DIGITS[(v & 0x3f) as usize] as core::ffi::c_char;
21313        v >>= 6;
21314        i += 1;
21315    }
21316    BUF[i] = 0;
21317    BUF.as_mut_ptr()
21318}
21319
21320#[no_mangle]
21321pub unsafe extern "C" fn a64l(s: *const core::ffi::c_char) -> i64 {
21322    let mut x: u32 = 0;
21323    let mut e = 0u32;
21324    while e < 36 {
21325        let c = *s.add((e / 6) as usize) as u8;
21326        if c == 0 { break; }
21327        let d = match A64L_DIGITS.iter().position(|&d| d == c) {
21328            Some(d) => d as u32,
21329            None => break,
21330        };
21331        x |= d << e;
21332        e += 6;
21333    }
21334    x as i32 as i64
21335}
21336
21337#[no_mangle]
21338pub unsafe extern "C" fn lchmod(path: *const core::ffi::c_char, mode: u32) -> i32 {
21339    fchmodat(AT_FDCWD, path, mode, AT_SYMLINK_NOFOLLOW)
21340}
21341
21342#[no_mangle]
21343pub unsafe extern "C" fn lutimes(filename: *const core::ffi::c_char, times: *const core::ffi::c_void) -> i32 {
21344    utimensat(AT_FDCWD, filename, times as *const timespec, AT_SYMLINK_NOFOLLOW)
21345}
21346
21347#[no_mangle]
21348pub unsafe extern "C" fn mknod(pathname: *const core::ffi::c_char, mode: u32, dev: u64) -> i32 {
21349    #[cfg(target_arch = "x86_64")]
21350    { syscall_ret(<Arch as Syscalls>::syscall3(SYS_MKNOD, pathname as i64, mode as i64, dev as i64)) as i32 }
21351    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
21352    {
21353        syscall_ret(<Arch as Syscalls>::syscall4(SYS_MKNODAT, AT_FDCWD as i64, pathname as i64, mode as i64, dev as i64)) as i32
21354    }
21355}
21356
21357#[no_mangle]
21358pub unsafe extern "C" fn memfd_create(name: *const core::ffi::c_char, flags: u32) -> i32 {
21359    syscall_ret(<Arch as Syscalls>::syscall2(SYS_MEMFD_CREATE, name as i64, flags as i64)) as i32
21360}
21361
21362#[no_mangle]
21363pub unsafe extern "C" fn mlock2(addr: *const core::ffi::c_void, len: usize, flags: u32) -> i32 {
21364    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MLOCK2, addr as i64, len as i64, flags as i64)) as i32
21365}
21366
21367
21368
21369#[no_mangle]
21370pub unsafe extern "C" fn remap_file_pages(addr: *mut core::ffi::c_void, size: usize, prot: i32, pgoff: usize, flags: u32) -> i32 {
21371    syscall_ret(<Arch as Syscalls>::syscall5(SYS_REMAP_FILE_PAGES, addr as i64, size as i64, prot as i64, pgoff as i64, flags as i64)) as i32
21372}
21373
21374// ============================================================
21375// nan functions
21376// ============================================================
21377
21378#[no_mangle]
21379pub unsafe extern "C" fn nan(_tagp: *const core::ffi::c_char) -> f64 {
21380    f64::NAN
21381}
21382
21383#[no_mangle]
21384pub unsafe extern "C" fn nanf(_tagp: *const core::ffi::c_char) -> f32 {
21385    f32::NAN
21386}
21387
21388// ============================================================
21389// Remaining symbols - batch 1
21390// ============================================================
21391
21392#[no_mangle]
21393pub unsafe extern "C" fn __lgammal_r(x: f64, signgamp: *mut i32) -> f64 {
21394    *signgamp = 1;
21395    lgamma(x)
21396}
21397
21398#[no_mangle]
21399pub unsafe extern "C" fn __libc_current_sigrtmax() -> i32 {
21400    64
21401}
21402
21403#[no_mangle]
21404pub unsafe extern "C" fn _longjmp(env: *mut core::ffi::c_void, val: i32) {
21405    crate::longjmp(env as *mut u64, val)
21406}
21407
21408#[no_mangle]
21409pub unsafe extern "C" fn __newlocale(_mask: i32, _name: *const core::ffi::c_char, base: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
21410    base
21411}
21412
21413#[no_mangle]
21414pub unsafe extern "C" fn __nl_langinfo(_item: i32) -> *mut core::ffi::c_char {
21415    b"\0".as_ptr() as *mut core::ffi::c_char
21416}
21417
21418#[no_mangle]
21419pub unsafe extern "C" fn __nl_langinfo_l(_item: i32, _loc: *mut core::ffi::c_void) -> *mut core::ffi::c_char {
21420    b"\0".as_ptr() as *mut core::ffi::c_char
21421}
21422
21423#[no_mangle]
21424pub unsafe extern "C" fn ns_get16(cp: *const u8) -> u16 {
21425    ((*cp.add(0) as u16) << 8) | *cp.add(1) as u16
21426}
21427
21428#[no_mangle]
21429pub unsafe extern "C" fn ns_get32(cp: *const u8) -> u32 {
21430    ((*cp.add(0) as u32) << 24) | ((*cp.add(1) as u32) << 16) | ((*cp.add(2) as u32) << 8) | *cp.add(3) as u32
21431}
21432
21433#[no_mangle]
21434pub unsafe extern "C" fn ns_put16(s: u16, dst: *mut u8) {
21435    *dst.add(0) = (s >> 8) as u8;
21436    *dst.add(1) = (s & 0xff) as u8;
21437}
21438
21439#[no_mangle]
21440pub unsafe extern "C" fn ns_put32(l: u32, dst: *mut u8) {
21441    *dst.add(0) = (l >> 24) as u8;
21442    *dst.add(1) = ((l >> 16) & 0xff) as u8;
21443    *dst.add(2) = ((l >> 8) & 0xff) as u8;
21444    *dst.add(3) = (l & 0xff) as u8;
21445}
21446
21447#[no_mangle]
21448pub unsafe extern "C" fn posix_close(fd: i32) -> i32 {
21449    crate::close(fd)
21450}
21451
21452#[no_mangle]
21453pub unsafe extern "C" fn posix_openpt(flags: i32) -> i32 {
21454    crate::open(b"/dev/ptmx\0".as_ptr() as *const core::ffi::c_char, flags, 0)
21455}
21456
21457#[no_mangle]
21458pub unsafe extern "C" fn putw(w: i32, f: *mut core::ffi::c_void) {
21459    putc((w & 0xff) as i32, f as *mut FILE);
21460    putc(((w >> 8) & 0xff) as i32, f as *mut FILE);
21461    putc(((w >> 16) & 0xff) as i32, f as *mut FILE);
21462    putc(((w >> 24) & 0xff) as i32, f as *mut FILE);
21463}
21464
21465
21466
21467#[no_mangle]
21468pub unsafe extern "C" fn rand_r(seedp: *mut u32) -> i32 {
21469    let seed = (*seedp).wrapping_mul(1103515245).wrapping_add(12345);
21470    *seedp = seed;
21471    ((seed >> 16) & 0x7fff) as i32
21472}
21473
21474#[no_mangle]
21475pub unsafe extern "C" fn reallocarray(ptr: *mut core::ffi::c_void, nmemb: usize, size: usize) -> *mut core::ffi::c_void {
21476    let total = match nmemb.checked_mul(size) {
21477        Some(v) => v,
21478        None => { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
21479    };
21480    crate::realloc(ptr, total)
21481}
21482
21483#[no_mangle]
21484pub unsafe extern "C" fn __res_state() -> *mut core::ffi::c_void {
21485    static mut STATE: [u8; 512] = [0; 512];
21486    STATE.as_mut_ptr() as *mut core::ffi::c_void
21487}
21488
21489#[no_mangle]
21490pub unsafe extern "C" fn sbrk(increment: isize) -> *mut u8 {
21491    // musl does not support growing the break directly (malloc uses mmap);
21492    // sbrk(nonzero) always fails with ENOMEM.
21493    if increment != 0 {
21494        ERRNO!() = ENOMEM;
21495        return -1isize as usize as *mut u8;
21496    }
21497    <Arch as Syscalls>::syscall1(SYS_BRK, 0) as *mut u8
21498}
21499
21500#[no_mangle]
21501pub unsafe extern "C" fn scalb(x: f64, exp: f64) -> f64 {
21502    if x.is_nan() || exp.is_nan() { return x * exp; }
21503    if !exp.is_finite() {
21504        let r = if exp > 0.0 { x * exp } else { x / (-exp) };
21505        if r.is_nan() && !x.is_nan() {
21506            feraiseexcept(FE_INVALID);
21507        }
21508        return r;
21509    }
21510    if libm::rint(exp) != exp {
21511        return __math_invalid(exp);
21512    }
21513    if exp > 65000.0 { return libm::scalbn(x, 65000); }
21514    if -exp > 65000.0 { return libm::scalbn(x, -65000); }
21515    libm::scalbn(x, exp as i32)
21516}
21517
21518#[no_mangle]
21519pub unsafe extern "C" fn scalbf(x: f32, exp: f32) -> f32 {
21520    if x.is_nan() || exp.is_nan() { return x * exp; }
21521    if !exp.is_finite() {
21522        let r = if exp > 0.0 { x * exp } else { x / (-exp) };
21523        if r.is_nan() && !x.is_nan() {
21524            feraiseexcept(FE_INVALID);
21525        }
21526        return r;
21527    }
21528    if libm::rintf(exp) != exp {
21529        return __math_invalidf(exp);
21530    }
21531    if exp > 65000.0 { return libm::scalbnf(x, 65000); }
21532    if -exp > 65000.0 { return libm::scalbnf(x, -65000); }
21533    libm::scalbnf(x, exp as i32)
21534}
21535
21536#[no_mangle]
21537pub unsafe extern "C" fn __sched_cpucount(setsize: usize, setp: *const u8) -> i32 {
21538    let mut count = 0;
21539    let mut i = 0;
21540    while i < setsize * 8 {
21541        if (*setp.add(i / 8) >> (i % 8)) & 1 != 0 { count += 1; }
21542        i += 1;
21543    }
21544    count
21545}
21546
21547
21548
21549#[no_mangle]
21550pub unsafe extern "C" fn select(nfds: i32, readfds: *mut u8, writefds: *mut u8, exceptfds: *mut u8, timeout: *mut core::ffi::c_void) -> i32 {
21551    syscall_ret(<Arch as Syscalls>::syscall6(SYS_SELECT, nfds as i64, readfds as i64, writefds as i64, exceptfds as i64, timeout as i64, 0)) as i32
21552}
21553
21554
21555
21556#[no_mangle]
21557pub unsafe extern "C" fn sendfile(out_fd: i32, in_fd: i32, offset: *mut i64, count: usize) -> isize {
21558    syscall_ret(<Arch as Syscalls>::syscall4(SYS_SENDFILE, out_fd as i64, in_fd as i64, offset as i64, count as i64)) as isize
21559}
21560
21561
21562
21563
21564
21565#[no_mangle]
21566pub unsafe extern "C" fn __setjmp(env: *mut core::ffi::c_void) -> i32 {
21567    crate::setjmp(env as *mut u64)
21568}
21569
21570#[no_mangle]
21571pub unsafe extern "C" fn _setjmp(env: *mut core::ffi::c_void) -> i32 {
21572    crate::setjmp(env as *mut u64)
21573}
21574
21575#[no_mangle]
21576pub unsafe extern "C" fn setlinebuf(stream: *mut core::ffi::c_void) {
21577    setvbuf(stream as *mut FILE, core::ptr::null_mut(), 1, 0);
21578}
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594#[no_mangle]
21595pub unsafe extern "C" fn significand(x: f64) -> f64 {
21596    let bits = x.to_bits();
21597    let exp = ((bits >> 52) & 0x7ff) as i32;
21598    if exp == 0 || exp == 0x7ff { return x; }
21599    f64::from_bits((bits & 0x000fffffffffffff) | (1023u64 << 52))
21600}
21601
21602#[no_mangle]
21603pub unsafe extern "C" fn significandf(x: f32) -> f32 {
21604    let bits = x.to_bits();
21605    let exp = ((bits >> 23) & 0xff) as i32;
21606    if exp == 0 || exp == 0xff { return x; }
21607    f32::from_bits((bits & 0x007fffff) | (127u32 << 23))
21608}
21609
21610
21611
21612
21613
21614#[no_mangle]
21615pub unsafe extern "C" fn sigset(sig: i32, handler: usize) -> usize {
21616    // BSD/glibc-compatible sigset() is an alias for signal().
21617    signal(sig, handler)
21618}
21619
21620#[no_mangle]
21621pub unsafe extern "C" fn sincos(x: f64, sin: *mut f64, cos: *mut f64) {
21622    *sin = libm::sin(x);
21623    *cos = libm::cos(x);
21624}
21625
21626#[no_mangle]
21627pub unsafe extern "C" fn sincosf(x: f32, sin: *mut f32, cos: *mut f32) {
21628    *sin = libm::sinf(x);
21629    *cos = libm::cosf(x);
21630}
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640unsafe fn nd_ascii_lower(c: c_char) -> c_int {
21641    let b = c as u8;
21642    if b >= b'A' && b <= b'Z' { (b + 32) as c_int } else { b as c_int }
21643}
21644
21645unsafe fn nd_strncasecmp(s1: *const c_char, s2: *const c_char, n: usize) -> c_int {
21646    let mut i = 0usize;
21647    while i < n {
21648        let c1 = nd_ascii_lower(*s1.add(i));
21649        let c2 = nd_ascii_lower(*s2.add(i));
21650        if c1 != c2 || c1 == 0 { return c1 - c2; }
21651        i += 1;
21652    }
21653    0
21654}
21655
21656#[no_mangle]
21657pub unsafe extern "C" fn strcasecmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> i32 {
21658    nd_strncasecmp(s1, s2, usize::MAX)
21659}
21660
21661#[no_mangle]
21662pub 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 {
21663    nd_strncasecmp(s1, s2, usize::MAX)
21664}
21665
21666#[no_mangle]
21667pub unsafe extern "C" fn strcasestr(haystack: *const core::ffi::c_char, needle: *const core::ffi::c_char) -> *mut core::ffi::c_char {
21668    let nlen = crate::strlen(needle);
21669    if nlen == 0 { return haystack as *mut core::ffi::c_char; }
21670    let mut i = 0;
21671    loop {
21672        let h = haystack.add(i);
21673        if *h == 0 { return core::ptr::null_mut(); }
21674        if crate::strncasecmp(h, needle, nlen) == 0 { return h as *mut core::ffi::c_char; }
21675        i += 1;
21676    }
21677}
21678
21679#[no_mangle]
21680pub 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 {
21681    crate::strcmp(s1 as *const u8, s2 as *const u8)
21682}
21683
21684#[no_mangle]
21685pub unsafe extern "C" fn strncasecmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char, n: usize) -> i32 {
21686    nd_strncasecmp(s1, s2, n)
21687}
21688
21689#[no_mangle]
21690pub 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 {
21691    nd_strncasecmp(s1, s2, n)
21692}
21693
21694#[no_mangle]
21695pub unsafe extern "C" fn strsep(stringp: *mut *mut core::ffi::c_char, delim: *const core::ffi::c_char) -> *mut core::ffi::c_char {
21696    let s = *stringp;
21697    if s.is_null() { return core::ptr::null_mut(); }
21698    let mut p = s;
21699    while *p != 0 {
21700        let mut d = delim;
21701        while *d != 0 {
21702            if *p == *d { *p = 0; *stringp = p.add(1); return s; }
21703            d = d.add(1);
21704        }
21705        p = p.add(1);
21706    }
21707    *stringp = core::ptr::null_mut();
21708    s
21709}
21710
21711#[no_mangle]
21712pub unsafe extern "C" fn strtoimax(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, base: i32) -> i64 {
21713    crate::strtol(nptr, endptr, base)
21714}
21715
21716#[no_mangle]
21717pub 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 {
21718    let mut s = if s.is_null() { *saveptr } else { s };
21719    if s.is_null() { return core::ptr::null_mut(); }
21720    // Skip leading delimiters
21721    while *s != 0 {
21722        let mut d = delim;
21723        let mut found = false;
21724        while *d != 0 {
21725            if *s == *d { found = true; break; }
21726            d = d.add(1);
21727        }
21728        if !found { break; }
21729        s = s.add(1);
21730    }
21731    if *s == 0 { *saveptr = s; return core::ptr::null_mut(); }
21732    let start = s;
21733    // Find end of token
21734    while *s != 0 {
21735        let mut d = delim;
21736        while *d != 0 {
21737            if *s == *d { *s = 0; *saveptr = s.add(1); return start; }
21738            d = d.add(1);
21739        }
21740        s = s.add(1);
21741    }
21742    *saveptr = s;
21743    start
21744}
21745
21746#[no_mangle]
21747pub unsafe extern "C" fn strtoumax(nptr: *const core::ffi::c_char, endptr: *mut *mut core::ffi::c_char, base: i32) -> u64 {
21748    crate::strtoul(nptr, endptr, base) as u64
21749}
21750
21751#[no_mangle]
21752pub 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 {
21753    crate::strlcpy(dest as *mut u8, src as *const u8, n)
21754}
21755
21756#[no_mangle]
21757pub unsafe extern "C" fn swab(src: *const u8, dest: *mut u8, nbytes: isize) {
21758    let mut i = 0;
21759    while i + 1 < nbytes {
21760        let a = *src.add(i as usize);
21761        let b = *src.add(i as usize + 1);
21762        *dest.add(i as usize) = b;
21763        *dest.add(i as usize + 1) = a;
21764        i += 2;
21765    }
21766}
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778#[no_mangle]
21779pub unsafe extern "C" fn __tolower_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
21780    if c >= 'A' as i32 && c <= 'Z' as i32 { c + 32 } else { c }
21781}
21782
21783#[no_mangle]
21784pub unsafe extern "C" fn __toupper_l(c: i32, _loc: *mut core::ffi::c_void) -> i32 {
21785    if c >= 'a' as i32 && c <= 'z' as i32 { c - 32 } else { c }
21786}
21787
21788#[no_mangle]
21789pub unsafe extern "C" fn ulimit(cmd: c_int, mut args: ...) -> c_long {
21790    let mut rl: Rlimit = core::mem::zeroed();
21791    if getrlimit(RLIMIT_FSIZE, &mut rl) != 0 { return -1; }
21792    if cmd == 2 {
21793        let val = args.next_arg::<c_long>();
21794        rl.rlim_cur = 512u64.wrapping_mul(val as u64);
21795        if setrlimit(RLIMIT_FSIZE, &rl) != 0 { return -1; }
21796    }
21797    (rl.rlim_cur / 512) as c_long
21798}
21799
21800#[repr(C)]
21801struct UtsName {
21802    sysname: [u8; 65],
21803    nodename: [u8; 65],
21804    release: [u8; 65],
21805    version: [u8; 65],
21806    machine: [u8; 65],
21807    domainname: [u8; 65],
21808}
21809
21810#[no_mangle]
21811pub unsafe extern "C" fn uname(buf: *mut c_void) -> c_int {
21812    // Let the kernel validate the user pointer: an invalid but non-null
21813    // address must produce EFAULT instead of a fault in a local copy.
21814    let r = <Arch as Syscalls>::syscall1(SYS_UNAME, buf as i64);
21815    syscall_ret(r) as c_int
21816}
21817
21818#[no_mangle]
21819pub unsafe extern "C" fn unshare(flags: i32) -> i32 {
21820    let r = <Arch as Syscalls>::syscall1(SYS_UNSHARE, flags as i64);
21821    syscall_ret(r) as c_int
21822}
21823
21824#[no_mangle]
21825pub unsafe extern "C" fn updwtmpx(wtmpx_file: *const core::ffi::c_char, utx: *const core::ffi::c_void) {
21826    updwtmp(wtmpx_file, utx)
21827}
21828
21829#[no_mangle]
21830pub unsafe extern "C" fn __uselocale(loc: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
21831    loc
21832}
21833
21834#[repr(C)]
21835pub struct Utimbuf { actime: i64, modtime: i64 }
21836
21837#[no_mangle]
21838pub unsafe extern "C" fn utime(filename: *const c_char, times: *const Utimbuf) -> c_int {
21839    if times.is_null() {
21840        return utimensat(AT_FDCWD, filename, core::ptr::null(), 0);
21841    }
21842    let ts = [
21843        timespec { tv_sec: (*times).actime, tv_nsec: 0 },
21844        timespec { tv_sec: (*times).modtime, tv_nsec: 0 },
21845    ];
21846    utimensat(AT_FDCWD, filename, ts.as_ptr(), 0)
21847}
21848
21849#[no_mangle]
21850pub unsafe extern "C" fn vhangup() -> c_int {
21851    let r = <Arch as Syscalls>::syscall0(SYS_VHANGUP);
21852    syscall_ret(r) as c_int
21853}
21854
21855#[no_mangle]
21856pub unsafe extern "C" fn vmsplice(fd: i32, iov: *const c_void, nr_segs: usize, flags: u32) -> isize {
21857    let r = <Arch as Syscalls>::syscall4(SYS_VMSPLICE, fd as i64, iov as i64, nr_segs as i64, flags as i64);
21858    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
21859}
21860
21861
21862
21863#[no_mangle]
21864pub unsafe extern "C" fn wait4(pid: i32, wstatus: *mut i32, options: i32, rusage: *mut core::ffi::c_void) -> i32 {
21865    syscall_ret(<Arch as Syscalls>::syscall4(SYS_WAIT4, pid as i64, wstatus as i64, options as i64, rusage as i64)) as i32
21866}
21867
21868#[no_mangle]
21869pub unsafe extern "C" fn waitid(idtype: i32, id: u32, infop: *mut core::ffi::c_void, options: i32) -> i32 {
21870    // The kernel takes a fifth rusage pointer; it must be NULL, not whatever
21871    // happens to be in r10.
21872    syscall_ret(<Arch as Syscalls>::syscall5(
21873        SYS_WAITID,
21874        idtype as i64,
21875        id as i64,
21876        infop as i64,
21877        options as i64,
21878        0,
21879    )) as i32
21880}
21881
21882#[no_mangle]
21883pub unsafe extern "C" fn __wcscoll_l(s1: *const u32, s2: *const u32, _loc: *mut core::ffi::c_void) -> i32 {
21884    crate::wcscmp(s1 as *const i32, s2 as *const i32)
21885}
21886
21887#[no_mangle]
21888pub unsafe extern "C" fn __wcsxfrm_l(dest: *mut u32, src: *const u32, n: usize, _loc: *mut core::ffi::c_void) -> usize {
21889    wcsxfrm(dest as *mut wchar_t, src as *const wchar_t, n)
21890}
21891
21892#[inline]
21893fn wctable_width(table: &[u8], wc: u32) -> bool {
21894    let page = table[(wc >> 8) as usize] as usize;
21895    (table[page * 32 + ((wc & 255) >> 3) as usize] >> (wc & 7)) & 1 != 0
21896}
21897
21898#[no_mangle]
21899pub unsafe extern "C" fn wcwidth(c: u32) -> i32 {
21900    // Port of musl's wcwidth, using the nonspacing/wide tables.
21901    let wc = c;
21902    if wc < 0xff {
21903        return if ((wc + 1) & 0x7f) >= 0x21 {
21904            1
21905        } else if wc != 0 {
21906            -1
21907        } else {
21908            0
21909        };
21910    }
21911    if (wc & 0xfffe_ffff) < 0xfffe {
21912        if wctable_width(&WCTYPE_NONSPACING_TABLE, wc) {
21913            return 0;
21914        }
21915        if wctable_width(&WCTYPE_WIDE_TABLE, wc) {
21916            return 2;
21917        }
21918        return 1;
21919    }
21920    if (wc & 0xfffe) == 0xfffe {
21921        return -1;
21922    }
21923    if wc.wrapping_sub(0x20000) < 0x20000 {
21924        return 2;
21925    }
21926    if wc == 0xe0001 || wc.wrapping_sub(0xe0020) < 0x5f || wc.wrapping_sub(0xe0100) < 0xef {
21927        return 0;
21928    }
21929    1
21930}
21931
21932
21933
21934
21935
21936// ============================================================
21937// Final missing symbols
21938// ============================================================
21939
21940
21941
21942#[no_mangle]
21943pub 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 {
21944    crate::strtod(nptr, endptr)
21945}
21946
21947#[no_mangle]
21948pub 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 {
21949    crate::strtof(nptr, endptr)
21950}
21951
21952#[no_mangle]
21953pub 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 {
21954    crate::strtod(nptr, endptr)
21955}
21956
21957// ============================================================
21958// Directory operations - real implementations
21959// ============================================================
21960
21961#[repr(C)]
21962struct linux_dirent64 {
21963    d_ino: u64,
21964    d_off: i64,
21965    d_reclen: u16,
21966    d_type: u8,
21967    d_name: [u8; 0], // flexible array
21968}
21969
21970// Directory streams used to be a process-wide singleton, which broke any
21971// nested opendir/readdir sequence (git, find, glob, ...). Each DIR now owns
21972// its fd and read buffer, like musl's __dirstream.
21973const DIR_BUF_SIZE: usize = 4096;
21974
21975#[repr(C)]
21976struct DirStream {
21977    fd: i32,
21978    pos: usize,
21979    len: usize,
21980    last_off: i64,
21981    buf: [u8; DIR_BUF_SIZE],
21982}
21983
21984unsafe fn dir_stream_new(fd: i32) -> *mut core::ffi::c_void {
21985    let ds = malloc(core::mem::size_of::<DirStream>()) as *mut DirStream;
21986    if ds.is_null() {
21987        crate::close(fd);
21988        ERRNO!() = ENOMEM;
21989        return core::ptr::null_mut();
21990    }
21991    core::ptr::write_bytes(ds, 0, 1);
21992    (*ds).fd = fd;
21993    ds as *mut core::ffi::c_void
21994}
21995
21996#[no_mangle]
21997pub unsafe extern "C" fn opendir(dirname: *const core::ffi::c_char) -> *mut core::ffi::c_void {
21998    let fd = openat(AT_FDCWD, dirname, O_DIRECTORY, 0); // O_RDONLY | O_DIRECTORY
21999    if fd < 0 { return core::ptr::null_mut(); }
22000    dir_stream_new(fd)
22001}
22002
22003#[no_mangle]
22004pub unsafe extern "C" fn closedir(dirp: *mut core::ffi::c_void) -> i32 {
22005    if dirp.is_null() { ERRNO!() = EINVAL; return -1; }
22006    let ds = dirp as *mut DirStream;
22007    let r = crate::close((*ds).fd);
22008    free(dirp);
22009    r
22010}
22011
22012#[no_mangle]
22013pub unsafe extern "C" fn readdir(dirp: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
22014    if dirp.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
22015    let ds = &mut *(dirp as *mut DirStream);
22016
22017    loop {
22018        if ds.pos >= ds.len {
22019            let nread = syscall_ret(<Arch as Syscalls>::syscall3(
22020                SYS_GETDENTS64,
22021                ds.fd as i64,
22022                ds.buf.as_mut_ptr() as i64,
22023                DIR_BUF_SIZE as i64,
22024            )) as isize;
22025            if nread <= 0 { return core::ptr::null_mut(); }
22026            ds.len = nread as usize;
22027            ds.pos = 0;
22028        }
22029
22030        let ent = ds.buf.as_ptr().add(ds.pos) as *const linux_dirent64;
22031        let ent_ref = &*ent;
22032        if ent_ref.d_reclen as usize == 0 {
22033            ds.len = 0;
22034            return core::ptr::null_mut();
22035        }
22036        ds.pos += ent_ref.d_reclen as usize;
22037        ds.last_off = ent_ref.d_off;
22038
22039        // Return a pointer into this stream's buffer (valid until next call).
22040        return ent as *mut core::ffi::c_void;
22041    }
22042}
22043
22044#[repr(C)]
22045struct DirentCopy {
22046    d_ino: u64,
22047    d_off: i64,
22048    d_reclen: u16,
22049    d_type: u8,
22050    d_name: [core::ffi::c_char; 256],
22051}
22052
22053#[no_mangle]
22054pub 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 {
22055    if dirp.is_null() || entry.is_null() || result.is_null() {
22056        return EINVAL;
22057    }
22058    let ent = readdir(dirp);
22059    if ent.is_null() {
22060        *result = core::ptr::null_mut();
22061        return 0;
22062    }
22063    let reclen = (* (ent as *const linux_dirent64)).d_reclen as usize;
22064    let copy = reclen.min(core::mem::size_of::<DirentCopy>());
22065    core::ptr::copy_nonoverlapping(ent as *const u8, entry as *mut u8, copy);
22066    *result = entry;
22067    0
22068}
22069
22070#[no_mangle]
22071pub unsafe extern "C" fn seekdir(dirp: *mut core::ffi::c_void, loc: i64) {
22072    if dirp.is_null() { return; }
22073    let ds = &mut *(dirp as *mut DirStream);
22074    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, loc, 0);
22075    ds.pos = 0;
22076    ds.len = 0;
22077}
22078
22079#[no_mangle]
22080pub unsafe extern "C" fn telldir(dirp: *mut core::ffi::c_void) -> i64 {
22081    if dirp.is_null() { return -1; }
22082    (*(dirp as *mut DirStream)).last_off
22083}
22084
22085#[no_mangle]
22086pub unsafe extern "C" fn rewinddir(dirp: *mut core::ffi::c_void) {
22087    if dirp.is_null() { return; }
22088    let ds = &mut *(dirp as *mut DirStream);
22089    <Arch as Syscalls>::syscall3(SYS_LSEEK, ds.fd as i64, 0, 0);
22090    ds.pos = 0;
22091    ds.len = 0;
22092    ds.last_off = 0;
22093}
22094
22095#[no_mangle]
22096pub unsafe extern "C" fn dirfd(dirp: *mut core::ffi::c_void) -> i32 {
22097    if dirp.is_null() { ERRNO!() = EINVAL; return -1; }
22098    (*(dirp as *mut DirStream)).fd
22099}
22100
22101// ============================================================
22102// Memory management - real implementations
22103// ============================================================
22104
22105#[no_mangle]
22106pub unsafe extern "C" fn mprotect(addr: *mut u8, len: usize, prot: i32) -> i32 {
22107    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MPROTECT, addr as i64, len as i64, prot as i64)) as i32
22108}
22109
22110#[no_mangle]
22111pub unsafe extern "C" fn msync(addr: *mut u8, len: usize, flags: i32) -> i32 {
22112    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MSYNC, addr as i64, len as i64, flags as i64)) as i32
22113}
22114
22115#[no_mangle]
22116pub unsafe extern "C" fn mlock(addr: *const u8, len: usize) -> i32 {
22117    syscall_ret(<Arch as Syscalls>::syscall2(SYS_MLOCK, addr as i64, len as i64)) as i32
22118}
22119
22120#[no_mangle]
22121pub unsafe extern "C" fn munlock(addr: *const u8, len: usize) -> i32 {
22122    syscall_ret(<Arch as Syscalls>::syscall2(SYS_MUNLOCK, addr as i64, len as i64)) as i32
22123}
22124
22125#[no_mangle]
22126pub unsafe extern "C" fn mlockall(flags: i32) -> i32 {
22127    syscall_ret(<Arch as Syscalls>::syscall1(SYS_MLOCKALL, flags as i64)) as i32
22128}
22129
22130#[no_mangle]
22131pub unsafe extern "C" fn munlockall() -> i32 {
22132    syscall_ret(<Arch as Syscalls>::syscall0(SYS_MUNLOCKALL)) as i32
22133}
22134
22135#[no_mangle]
22136pub unsafe extern "C" fn madvise(addr: *mut u8, len: usize, advice: i32) -> i32 {
22137    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MADVISE, addr as i64, len as i64, advice as i64)) as i32
22138}
22139
22140#[no_mangle]
22141pub unsafe extern "C" fn mincore(addr: *mut u8, len: usize, vec: *mut u8) -> i32 {
22142    syscall_ret(<Arch as Syscalls>::syscall3(SYS_MINCORE, addr as i64, len as i64, vec as i64)) as i32
22143}
22144
22145// ============================================================
22146
22147// ============================================================
22148// Missing math functions
22149// ============================================================
22150
22151#[no_mangle]
22152pub unsafe extern "C" fn drem(x: f64, y: f64) -> f64 {
22153    remainder(x, y)
22154}
22155
22156#[no_mangle]
22157pub unsafe extern "C" fn dremf(x: f32, y: f32) -> f32 {
22158    remainderf(x, y)
22159}
22160
22161#[no_mangle]
22162pub unsafe extern "C" fn pow10(x: f64) -> f64 {
22163    libm::pow(10.0, x)
22164}
22165
22166#[no_mangle]
22167pub unsafe extern "C" fn pow10f(x: f32) -> f32 {
22168    libm::powf(10.0, x)
22169}
22170
22171#[no_mangle]
22172pub unsafe extern "C" fn pow10l(x: f64) -> f64 {
22173    libm::pow(10.0, x)
22174}
22175
22176#[no_mangle]
22177pub unsafe extern "C" fn isless(x: f64, y: f64) -> i32 {
22178    if x.is_nan() || y.is_nan() { 0 } else { (x < y) as i32 }
22179}
22180
22181#[no_mangle]
22182pub unsafe extern "C" fn islessf(x: f32, y: f32) -> i32 {
22183    if x.is_nan() || y.is_nan() { 0 } else { (x < y) as i32 }
22184}
22185
22186#[no_mangle]
22187pub unsafe extern "C" fn lgamma_r(x: f64, signgamp: *mut i32) -> f64 {
22188    lgamma_r_impl(x, signgamp)
22189}
22190
22191#[no_mangle]
22192pub unsafe extern "C" fn lgammaf_r(x: f32, signgamp: *mut i32) -> f32 {
22193    if x.is_nan() {
22194        if !signgamp.is_null() { *signgamp = 1; }
22195        return x;
22196    }
22197    if x == 0.0 {
22198        if !signgamp.is_null() { *signgamp = if x.is_sign_negative() { -1 } else { 1 }; }
22199        feraiseexcept(FE_DIVBYZERO);
22200        return f32::INFINITY;
22201    }
22202    let (r, sign) = libm::lgammaf_r(x);
22203    if !signgamp.is_null() { *signgamp = sign; }
22204    r
22205}
22206
22207#[no_mangle]
22208pub unsafe extern "C" fn lgammal_r(x: f64, signgamp: *mut i32) -> f64 {
22209    lgamma_r(x, signgamp)
22210}
22211
22212// ============================================================
22213// Comparison macros
22214// ============================================================
22215
22216#[no_mangle]
22217pub unsafe extern "C" fn islessequal(x: f64, y: f64) -> i32 {
22218    if x.is_nan() || y.is_nan() { 0 } else { (x <= y) as i32 }
22219}
22220
22221#[no_mangle]
22222pub unsafe extern "C" fn islessequalf(x: f32, y: f32) -> i32 {
22223    if x.is_nan() || y.is_nan() { 0 } else { (x <= y) as i32 }
22224}
22225
22226#[no_mangle]
22227pub unsafe extern "C" fn islessgreater(x: f64, y: f64) -> i32 {
22228    if x.is_nan() || y.is_nan() { 0 } else { (x < y || x > y) as i32 }
22229}
22230
22231#[no_mangle]
22232pub unsafe extern "C" fn islessgreaterf(x: f32, y: f32) -> i32 {
22233    if x.is_nan() || y.is_nan() { 0 } else { (x < y || x > y) as i32 }
22234}
22235
22236#[no_mangle]
22237pub unsafe extern "C" fn isgreater(x: f64, y: f64) -> i32 {
22238    if x.is_nan() || y.is_nan() { 0 } else { (x > y) as i32 }
22239}
22240
22241#[no_mangle]
22242pub unsafe extern "C" fn isgreaterf(x: f32, y: f32) -> i32 {
22243    if x.is_nan() || y.is_nan() { 0 } else { (x > y) as i32 }
22244}
22245
22246#[no_mangle]
22247pub unsafe extern "C" fn isgreaterequal(x: f64, y: f64) -> i32 {
22248    if x.is_nan() || y.is_nan() { 0 } else { (x >= y) as i32 }
22249}
22250
22251#[no_mangle]
22252pub unsafe extern "C" fn isgreaterequalf(x: f32, y: f32) -> i32 {
22253    if x.is_nan() || y.is_nan() { 0 } else { (x >= y) as i32 }
22254}
22255
22256// ============================================================
22257// musl ABI compatibility helpers
22258// ============================================================
22259
22260#[no_mangle]
22261pub unsafe extern "C" fn stpcpy(dest: *mut c_char, src: *const c_char) -> *mut c_char {
22262    let mut d = dest;
22263    let mut s = src;
22264    while *s != 0 {
22265        *d = *s;
22266        d = d.add(1);
22267        s = s.add(1);
22268    }
22269    *d = 0;
22270    d
22271}
22272
22273#[no_mangle]
22274pub unsafe extern "C" fn stpncpy(dest: *mut c_char, src: *const c_char, n: usize) -> *mut c_char {
22275    let mut i = 0;
22276    while i < n && *src.add(i) != 0 {
22277        *dest.add(i) = *src.add(i);
22278        i += 1;
22279    }
22280    let end = dest.add(i);
22281    while i < n {
22282        *dest.add(i) = 0;
22283        i += 1;
22284    }
22285    end
22286}
22287
22288#[no_mangle]
22289pub unsafe extern "C" fn strchrnul(s: *const c_char, c: c_int) -> *mut c_char {
22290    let mut p = s;
22291    while *p != 0 && *p as c_int != c {
22292        p = p.add(1);
22293    }
22294    p as *mut c_char
22295}
22296
22297#[no_mangle]
22298pub unsafe extern "C" fn fstatat(dirfd: c_int, path: *const c_char, buf: *mut Stat, flags: c_int) -> c_int {
22299    let r = sys_newfstatat(dirfd, path, buf as *mut u8, flags);
22300    syscall_ret(r) as c_int
22301}
22302
22303#[no_mangle]
22304pub unsafe extern "C" fn execvpe(
22305    file: *const c_char,
22306    argv: *const *const c_char,
22307    envp: *const *const c_char,
22308) -> c_int {
22309    ERRNO!() = ENOENT;
22310    if file.is_null() || *file == 0 {
22311        return -1;
22312    }
22313    let mut p = file;
22314    while *p != 0 {
22315        if *p == b'/' as c_char {
22316            return execve(file, argv, envp);
22317        }
22318        p = p.add(1);
22319    }
22320    let file_len = crate::strlen(file);
22321    let path = crate::getenv(b"PATH\0".as_ptr() as *const c_char);
22322    let default_path = b"/usr/local/bin:/bin:/usr/bin\0";
22323    let path = if path.is_null() { default_path.as_ptr() as *const c_char } else { path };
22324
22325    let mut seen_eacces = false;
22326    let mut buf = [0 as c_char; PATH_MAX_V];
22327    let mut dir = path;
22328    loop {
22329        let mut end = dir;
22330        while *end != 0 && *end != b':' as c_char { end = end.add(1); }
22331        let dlen = end.offset_from(dir) as usize;
22332        // An empty PATH component means the current directory (no slash).
22333        let need_slash = dlen > 0;
22334        let total = dlen + need_slash as usize + file_len;
22335        if total < buf.len() {
22336            let mut i = 0;
22337            while i < dlen { buf[i] = *dir.add(i); i += 1; }
22338            if need_slash { buf[i] = b'/' as c_char; i += 1; }
22339            let mut j = 0;
22340            while j < file_len { buf[i + j] = *file.add(j); j += 1; }
22341            buf[i + j] = 0;
22342            execve(buf.as_ptr(), argv, envp);
22343            match ERRNO!() {
22344                13 => seen_eacces = true, // EACCES
22345                2 | 20 => {}              // ENOENT, ENOTDIR: try next
22346                _ => return -1,
22347            }
22348        }
22349        if *end == 0 { break; }
22350        dir = end.add(1);
22351    }
22352    ERRNO!() = if seen_eacces { 13 } else { 2 };
22353    -1
22354}
22355
22356// Locale-aware entry points. keel currently has a single global locale,
22357// so these are source/ABI-compatible wrappers around the normal functions.
22358#[no_mangle]
22359pub unsafe extern "C" fn strcoll_l(s1: *const c_char, s2: *const c_char, _loc: locale_t) -> c_int {
22360    strcoll(s1, s2)
22361}
22362
22363#[no_mangle]
22364pub unsafe extern "C" fn strxfrm_l(dest: *mut c_char, src: *const c_char, n: usize, _loc: locale_t) -> usize {
22365    strxfrm(dest, src, n)
22366}
22367
22368#[no_mangle]
22369pub unsafe extern "C" fn strerror_l(errnum: c_int, _loc: locale_t) -> *mut c_char {
22370    strerror(errnum)
22371}
22372
22373#[no_mangle]
22374pub unsafe extern "C" fn strcasecmp_l(s1: *const c_char, s2: *const c_char, _loc: locale_t) -> c_int {
22375    strcasecmp(s1, s2)
22376}
22377
22378#[no_mangle]
22379pub unsafe extern "C" fn strncasecmp_l(s1: *const c_char, s2: *const c_char, n: usize, _loc: locale_t) -> c_int {
22380    strncasecmp(s1, s2, n)
22381}
22382
22383#[no_mangle]
22384pub unsafe extern "C" fn strftime_l(s: *mut c_char, max: usize, fmt: *const c_char, tm: *const tm, _loc: locale_t) -> usize {
22385    strftime(s, max, fmt, tm)
22386}
22387
22388#[no_mangle]
22389pub unsafe extern "C" fn nl_langinfo_l(item: c_int, _loc: locale_t) -> *mut c_char {
22390    nl_langinfo(item)
22391}
22392
22393#[no_mangle]
22394pub unsafe extern "C" fn wcscoll_l(s1: *const u32, s2: *const u32, _loc: locale_t) -> c_int {
22395    wcscoll(s1, s2)
22396}
22397
22398#[no_mangle]
22399pub unsafe extern "C" fn wcsxfrm_l(dst: *mut wchar_t, src: *const wchar_t, n: usize, _loc: locale_t) -> usize {
22400    wcsxfrm(dst, src, n)
22401}
22402
22403#[no_mangle]
22404pub unsafe extern "C" fn wcsftime_l(s: *mut u32, max: usize, fmt: *const u32, tm: *const c_void, _loc: locale_t) -> usize {
22405    wcsftime(s, max, fmt, tm)
22406}
22407
22408#[no_mangle]
22409pub unsafe extern "C" fn wctype_l(name: *const c_char, _loc: locale_t) -> wctype_t {
22410    wctype(name)
22411}
22412
22413#[no_mangle]
22414pub unsafe extern "C" fn wctrans_l(name: *const c_char, _loc: locale_t) -> wctrans_t {
22415    wctrans(name)
22416}
22417
22418#[no_mangle]
22419pub unsafe extern "C" fn towlower_l(c: wint_t, _loc: locale_t) -> wint_t {
22420    towlower(c)
22421}
22422
22423#[no_mangle]
22424pub unsafe extern "C" fn towupper_l(c: wint_t, _loc: locale_t) -> wint_t {
22425    towupper(c)
22426}
22427
22428#[no_mangle]
22429pub unsafe extern "C" fn towctrans_l(c: wint_t, desc: wctrans_t, _loc: locale_t) -> wint_t {
22430    towctrans(c, desc)
22431}
22432
22433#[no_mangle] pub unsafe extern "C" fn iswalnum_l(c: wint_t, _l: locale_t) -> c_int { iswalnum(c) }
22434#[no_mangle] pub unsafe extern "C" fn iswalpha_l(c: wint_t, _l: locale_t) -> c_int { iswalpha(c) }
22435#[no_mangle] pub unsafe extern "C" fn iswblank_l(c: wint_t, _l: locale_t) -> c_int { iswblank(c) }
22436#[no_mangle] pub unsafe extern "C" fn iswcntrl_l(c: wint_t, _l: locale_t) -> c_int { iswcntrl(c) }
22437#[no_mangle] pub unsafe extern "C" fn iswdigit_l(c: wint_t, _l: locale_t) -> c_int { iswdigit(c) }
22438#[no_mangle] pub unsafe extern "C" fn iswgraph_l(c: wint_t, _l: locale_t) -> c_int { iswgraph(c) }
22439#[no_mangle] pub unsafe extern "C" fn iswlower_l(c: wint_t, _l: locale_t) -> c_int { iswlower(c) }
22440#[no_mangle] pub unsafe extern "C" fn iswprint_l(c: wint_t, _l: locale_t) -> c_int { iswprint(c) }
22441#[no_mangle] pub unsafe extern "C" fn iswpunct_l(c: wint_t, _l: locale_t) -> c_int { iswpunct(c) }
22442#[no_mangle] pub unsafe extern "C" fn iswspace_l(c: wint_t, _l: locale_t) -> c_int { iswspace(c) }
22443#[no_mangle] pub unsafe extern "C" fn iswupper_l(c: wint_t, _l: locale_t) -> c_int { iswupper(c) }
22444#[no_mangle] pub unsafe extern "C" fn iswxdigit_l(c: wint_t, _l: locale_t) -> c_int { iswxdigit(c) }
22445#[no_mangle] pub unsafe extern "C" fn iswctype_l(c: wint_t, desc: wctype_t, _l: locale_t) -> c_int { iswctype(c, desc) }
22446
22447// ISO C99 scanf ABI aliases expected by musl binaries.
22448#[no_mangle] pub unsafe extern "C" fn __isoc99_scanf(fmt: *const c_char, args: ...) -> c_int { vfscanf(stdin, fmt, args) }
22449#[no_mangle] pub unsafe extern "C" fn __isoc99_fscanf(f: *mut FILE, fmt: *const c_char, args: ...) -> c_int { vfscanf(f, fmt, args) }
22450#[no_mangle] pub unsafe extern "C" fn __isoc99_sscanf(s: *const c_char, fmt: *const c_char, args: ...) -> c_int { vsscanf(s, fmt, args) }
22451#[no_mangle] pub unsafe extern "C" fn __isoc99_vscanf(fmt: *const c_char, args: VaList) -> c_int { vfscanf(stdin, fmt, args) }
22452#[no_mangle] pub unsafe extern "C" fn __isoc99_vfscanf(f: *mut FILE, fmt: *const c_char, args: VaList) -> c_int { vfscanf(f, fmt, args) }
22453#[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) }
22454#[no_mangle] pub unsafe extern "C" fn __isoc99_wscanf(fmt: *const wchar_t, args: ...) -> c_int { vfwscanf(stdin, fmt, args) }
22455#[no_mangle] pub unsafe extern "C" fn __isoc99_fwscanf(f: *mut FILE, fmt: *const wchar_t, args: ...) -> c_int { vfwscanf(f, fmt, args) }
22456#[no_mangle] pub unsafe extern "C" fn __isoc99_swscanf(s: *const wchar_t, fmt: *const wchar_t, args: ...) -> c_int { vswscanf(s, fmt, args) }
22457#[no_mangle] pub unsafe extern "C" fn __isoc99_vwscanf(fmt: *const wchar_t, args: VaList) -> c_int { vfwscanf(stdin, fmt, args) }
22458#[no_mangle] pub unsafe extern "C" fn __isoc99_vfwscanf(f: *mut FILE, fmt: *const wchar_t, args: VaList) -> c_int { vfwscanf(f, fmt, args) }
22459#[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) }
22460
22461// Unlocked stdio entry points.  keel's stdio does not take FILE locks
22462// internally (see docs/limitations.md), so these are aliases for the normal
22463// entry points.
22464#[no_mangle] pub unsafe extern "C" fn clearerr_unlocked(f: *mut FILE) { clearerr(f) }
22465#[no_mangle] pub unsafe extern "C" fn feof_unlocked(f: *mut FILE) -> c_int { feof(f) }
22466#[no_mangle] pub unsafe extern "C" fn ferror_unlocked(f: *mut FILE) -> c_int { ferror(f) }
22467#[no_mangle] pub unsafe extern "C" fn fileno_unlocked(f: *mut FILE) -> c_int { fileno(f) }
22468#[no_mangle] pub unsafe extern "C" fn fflush_unlocked(f: *mut FILE) -> c_int { fflush(f) }
22469#[no_mangle] pub unsafe extern "C" fn fgetc_unlocked(f: *mut FILE) -> c_int { fgetc(f) }
22470#[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) }
22471#[no_mangle] pub unsafe extern "C" fn fputc_unlocked(c: c_int, f: *mut FILE) -> c_int { fputc(c, f) }
22472#[no_mangle] pub unsafe extern "C" fn fputs_unlocked(s: *const c_char, f: *mut FILE) -> c_int { fputs(s, f) }
22473#[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) }
22474#[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) }
22475#[no_mangle] pub unsafe extern "C" fn fgetwc_unlocked(f: *mut FILE) -> wint_t { fgetwc(f) }
22476#[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) }
22477#[no_mangle] pub unsafe extern "C" fn fputwc_unlocked(c: wchar_t, f: *mut FILE) -> wint_t { fputwc(c, f) }
22478#[no_mangle] pub unsafe extern "C" fn fputws_unlocked(s: *const wchar_t, f: *mut FILE) -> c_int { fputws(s, f) }
22479#[no_mangle] pub unsafe extern "C" fn getwc_unlocked(f: *mut c_void) -> wint_t { getwc(f) }
22480#[no_mangle] pub unsafe extern "C" fn putwc_unlocked(c: u32, f: *mut c_void) -> wint_t { putwc(c, f) }
22481#[no_mangle] pub unsafe extern "C" fn getwchar_unlocked() -> wint_t { getwchar() }
22482#[no_mangle] pub unsafe extern "C" fn putwchar_unlocked(c: wchar_t) -> wint_t { putwchar(c) }
22483#[no_mangle] pub unsafe extern "C" fn fpurge(f: *mut FILE) { clearerr(f) }
22484#[no_mangle] pub unsafe extern "C" fn _IO_getc(f: *mut FILE) -> c_int { getc(f) }
22485#[no_mangle] pub unsafe extern "C" fn _IO_putc(c: c_int, f: *mut FILE) -> c_int { putc(c, f) }
22486#[no_mangle] pub unsafe extern "C" fn _IO_getc_unlocked(f: *mut FILE) -> c_int { getc(f) }
22487#[no_mangle] pub unsafe extern "C" fn _IO_putc_unlocked(c: c_int, f: *mut FILE) -> c_int { putc(c, f) }
22488#[no_mangle] pub unsafe extern "C" fn _IO_feof_unlocked(f: *mut FILE) -> c_int { feof(f) }
22489#[no_mangle] pub unsafe extern "C" fn _IO_ferror_unlocked(f: *mut FILE) -> c_int { ferror(f) }
22490
22491// ABI aliases used by musl and older C libraries.
22492#[no_mangle] pub unsafe extern "C" fn __getauxval(t: c_ulong) -> c_ulong { getauxval(t) }
22493#[no_mangle] pub unsafe extern "C" fn __longjmp(env: *const c_ulong, val: c_int) -> ! { longjmp(env, val) }
22494#[no_mangle] pub unsafe extern "C" fn bsd_signal(sig: c_int, handler: usize) -> usize { signal(sig, handler) }
22495#[no_mangle] pub unsafe extern "C" fn __sysv_signal(sig: c_int, handler: usize) -> usize { signal(sig, handler) }
22496#[no_mangle] pub unsafe extern "C" fn eaccess(path: *const c_char, mode: c_int) -> c_int { access(path, mode) }
22497#[no_mangle] pub unsafe extern "C" fn __xpg_basename(path: *mut c_char) -> *mut c_char { basename(path) }
22498#[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) }
22499#[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) }
22500
22501// ============================================================
22502// Remaining musl ABI entry points
22503// ============================================================
22504
22505#[no_mangle]
22506pub unsafe extern "C" fn cfsetspeed(termios_p: *mut c_void, speed: u32) -> c_int {
22507    let r = cfsetispeed(termios_p, speed);
22508    if r != 0 { return r; }
22509    cfsetospeed(termios_p, speed)
22510}
22511
22512#[no_mangle]
22513pub unsafe extern "C" fn futimesat(dirfd: c_int, path: *const c_char, times: *const timeval) -> c_int {
22514    if times.is_null() {
22515        return utimensat(dirfd, path, core::ptr::null(), 0);
22516    }
22517    let tv = times as *const [timeval; 2];
22518    let mut ts: [timespec; 2] = [
22519        timespec { tv_sec: (*tv)[0].tv_sec, tv_nsec: (*tv)[0].tv_usec * 1000 },
22520        timespec { tv_sec: (*tv)[1].tv_sec, tv_nsec: (*tv)[1].tv_usec * 1000 },
22521    ];
22522    for t in &mut ts {
22523        if t.tv_nsec < 0 || t.tv_nsec >= 1_000_000_000 {
22524            ERRNO!() = EINVAL;
22525            return -1;
22526        }
22527    }
22528    utimensat(dirfd, path, ts.as_ptr(), 0)
22529}
22530
22531#[no_mangle]
22532pub unsafe extern "C" fn membarrier(cmd: c_int, flags: c_int, cpu_id: c_int) -> c_int {
22533    <Arch as Syscalls>::syscall3(SYS_MEMBARRIER, cmd as i64, flags as i64, cpu_id as i64) as c_int
22534}
22535
22536#[no_mangle]
22537pub unsafe extern "C" fn mremap(
22538    old_address: *mut c_void,
22539    old_size: usize,
22540    new_size: usize,
22541    flags: c_int,
22542    mut args: ...
22543) -> *mut c_void {
22544    let new_address = if flags & 2 != 0 { args.next_arg::<*mut c_void>() } else { core::ptr::null_mut() };
22545    let r = <Arch as Syscalls>::syscall5(
22546        SYS_MREMAP,
22547        old_address as i64,
22548        old_size as i64,
22549        new_size as i64,
22550        flags as i64,
22551        new_address as i64,
22552    );
22553    if r < 0 {
22554        ERRNO!() = (-r) as c_int;
22555        return (-1isize) as *mut c_void;
22556    }
22557    r as *mut c_void
22558}
22559
22560#[no_mangle]
22561pub unsafe extern "C" fn ptsname_r(fd: c_int, buf: *mut c_char, buflen: usize) -> c_int {
22562    let name = ptsname(fd);
22563    if name.is_null() { return -1; }
22564    let n = crate::strlen(name);
22565    if n + 1 > buflen {
22566        ERRNO!() = ERANGE;
22567        return ERANGE;
22568    }
22569    core::ptr::copy_nonoverlapping(name, buf, n + 1);
22570    0
22571}
22572
22573#[no_mangle]
22574pub unsafe extern "C" fn posix_getdents(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize {
22575    if flags != 0 {
22576        ERRNO!() = EINVAL;
22577        return -1;
22578    }
22579    let r = <Arch as Syscalls>::syscall3(SYS_GETDENTS64, fd as i64, buf as i64, len as i64);
22580    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
22581}
22582
22583const SYS_RISCV_FLUSH_ICACHE: i64 = 259;
22584const SYS_FCHMODAT2: i64 = 452;
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(SYS_RISCV_FLUSH_ICACHE, 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(), O_WRONLY | O_CREAT | O_APPEND, 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, O_WRONLY | O_CREAT | O_APPEND, 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#[no_mangle]
23390pub unsafe extern "C" fn settimeofday(tv: *const c_void, tz: *const c_void) -> c_int {
23391    let r = <Arch as Syscalls>::syscall2(SYS_SETTIMEOFDAY, tv as i64, tz as i64);
23392    syscall_ret(r) as c_int
23393}
23394
23395#[no_mangle]
23396pub unsafe extern "C" fn stime(t: *const i64) -> c_int {
23397    if t.is_null() { ERRNO!() = EINVAL; return -1; }
23398    let tv = timeval { tv_sec: *t, tv_usec: 0 };
23399    settimeofday(&tv as *const timeval as *const c_void, core::ptr::null())
23400}
23401
23402#[no_mangle]
23403pub unsafe extern "C" fn times(buf: *mut c_void) -> c_long {
23404    let r = <Arch as Syscalls>::syscall1(SYS_TIMES, buf as i64);
23405    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as c_long }
23406}
23407
23408#[no_mangle]
23409pub 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 {
23410    let r = <Arch as Syscalls>::syscall6(SYS_SPLICE, fd_in as i64, off_in as i64, fd_out as i64, off_out as i64, len as i64, flags as i64);
23411    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
23412}
23413
23414#[no_mangle]
23415pub unsafe extern "C" fn tee(fd_in: c_int, fd_out: c_int, len: usize, flags: u32) -> isize {
23416    let r = <Arch as Syscalls>::syscall4(SYS_TEE, fd_in as i64, fd_out as i64, len as i64, flags as i64);
23417    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
23418}
23419
23420#[no_mangle]
23421pub unsafe extern "C" fn statx(dirfd: c_int, path: *const c_char, flags: c_int, mask: u32, buf: *mut c_void) -> c_int {
23422    let r = <Arch as Syscalls>::syscall5(SYS_STATX, dirfd as i64, path as i64, flags as i64, mask as i64, buf as i64);
23423    syscall_ret(r) as c_int
23424}
23425
23426#[no_mangle]
23427pub unsafe extern "C" fn setns(fd: c_int, nstype: c_int) -> c_int {
23428    let r = <Arch as Syscalls>::syscall2(SYS_SETNS, fd as i64, nstype as i64);
23429    syscall_ret(r) as c_int
23430}
23431
23432#[no_mangle]
23433pub unsafe extern "C" fn setfsuid(uid: u32) -> c_int {
23434    <Arch as Syscalls>::syscall1(SYS_SETFSUID, uid as i64) as c_int
23435}
23436
23437#[no_mangle]
23438pub unsafe extern "C" fn setfsgid(gid: u32) -> c_int {
23439    <Arch as Syscalls>::syscall1(SYS_SETFSGID, gid as i64) as c_int
23440}
23441
23442#[no_mangle]
23443pub unsafe extern "C" fn setregid(rgid: u32, egid: u32) -> c_int {
23444    let r = <Arch as Syscalls>::syscall2(SYS_SETREGID, rgid as i64, egid as i64);
23445    syscall_ret(r) as c_int
23446}
23447
23448#[no_mangle]
23449pub 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 {
23450    let r = <Arch as Syscalls>::syscall6(SYS_PROCESS_VM_READV, pid as i64, local as i64, liovcnt as i64, remote as i64, riovcnt as i64, flags as i64);
23451    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
23452}
23453
23454#[no_mangle]
23455pub 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 {
23456    let r = <Arch as Syscalls>::syscall6(SYS_PROCESS_VM_WRITEV, pid as i64, local as i64, liovcnt as i64, remote as i64, riovcnt as i64, flags as i64);
23457    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { r as isize }
23458}
23459
23460#[no_mangle]
23461pub unsafe extern "C" fn tcgetwinsize(fd: c_int, ws: *mut c_void) -> c_int {
23462    if fd < 0 || ws.is_null() { ERRNO!() = EINVAL; return -1; }
23463    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5413, ws as i64);
23464    syscall_ret(r) as c_int
23465}
23466
23467#[no_mangle]
23468pub unsafe extern "C" fn tcsetwinsize(fd: c_int, ws: *const c_void) -> c_int {
23469    if fd < 0 || ws.is_null() { ERRNO!() = EINVAL; return -1; }
23470    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5414, ws as i64);
23471    syscall_ret(r) as c_int
23472}
23473
23474#[no_mangle]
23475pub unsafe extern "C" fn sockatmark(fd: c_int) -> c_int {
23476    let mut at: c_int = 0;
23477    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x8905, &mut at as *mut c_int as i64);
23478    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { at }
23479}
23480
23481#[no_mangle]
23482pub unsafe extern "C" fn isastream(fd: c_int) -> c_int {
23483    let mut buf = [0u8; 64];
23484    let r = <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, 0x5401, buf.as_mut_ptr() as i64);
23485    if r < 0 { ERRNO!() = (-r) as c_int; 0 } else { 1 }
23486}
23487
23488#[no_mangle]
23489pub unsafe extern "C" fn posix_madvise(addr: *mut c_void, len: usize, advice: c_int) -> c_int {
23490    madvise(addr as *mut u8, len, advice)
23491}
23492
23493#[no_mangle]
23494pub unsafe extern "C" fn secure_getenv(name: *const c_char) -> *mut c_char {
23495    if getauxval(23) != 0 { return core::ptr::null_mut(); }
23496    getenv(name)
23497}
23498
23499#[no_mangle]
23500pub unsafe extern "C" fn sigandset(dest: *mut c_ulong, left: *const c_ulong, right: *const c_ulong) -> c_int {
23501    if dest.is_null() || left.is_null() || right.is_null() { return -1; }
23502    *dest = *left & *right;
23503    0
23504}
23505
23506#[no_mangle]
23507pub unsafe extern "C" fn sigorset(dest: *mut c_ulong, left: *const c_ulong, right: *const c_ulong) -> c_int {
23508    if dest.is_null() || left.is_null() || right.is_null() { return -1; }
23509    *dest = *left | *right;
23510    0
23511}
23512
23513#[no_mangle]
23514pub unsafe extern "C" fn sigisemptyset(set: *const c_ulong) -> c_int {
23515    if set.is_null() { return 1; }
23516    (*set == 0) as c_int
23517}
23518
23519#[no_mangle]
23520pub unsafe extern "C" fn sighold(sig: c_int) -> c_int {
23521    let set: c_ulong = 1u64 << (sig - 1) as u32;
23522    sigprocmask(0, &set, core::ptr::null_mut());
23523    0
23524}
23525
23526#[no_mangle]
23527pub unsafe extern "C" fn sigignore(sig: c_int) -> c_int {
23528    let _ = signal(sig, 1);
23529    0
23530}
23531
23532#[no_mangle]
23533pub unsafe extern "C" fn sigrelse(sig: c_int) -> c_int {
23534    let set: c_ulong = 1u64 << (sig - 1) as u32;
23535    sigprocmask(1, &set, core::ptr::null_mut());
23536    0
23537}
23538
23539#[no_mangle]
23540pub unsafe extern "C" fn siginterrupt(sig: c_int, flag: c_int) -> c_int {
23541    let mut sa: sigaction = core::mem::zeroed();
23542    if sigaction(sig, core::ptr::null(), &mut sa) != 0 { return -1; }
23543    if flag != 0 { sa.sa_flags &= !(SA_RESTART as c_int); } else { sa.sa_flags |= SA_RESTART as c_int; }
23544    sigaction(sig, &sa, core::ptr::null_mut())
23545}
23546
23547#[no_mangle]
23548pub unsafe extern "C" fn sigpause(sig: c_int) -> c_int {
23549    let set: c_ulong = 1u64 << (sig - 1) as u32;
23550    sigsuspend(&set)
23551}
23552
23553#[no_mangle]
23554pub unsafe extern "C" fn semtimedop(semid: c_int, sops: *mut c_void, nsops: usize, timeout: *const timespec) -> c_int {
23555    let r = <Arch as Syscalls>::syscall4(SYS_SEMTIMEDOP, semid as i64, sops as i64, nsops as i64, timeout as i64);
23556    syscall_ret(r) as c_int
23557}
23558
23559#[no_mangle]
23560pub unsafe extern "C" fn wait3(status: *mut c_int, options: c_int, rusage: *mut c_void) -> i32 {
23561    wait4(-1, status, options, rusage) as i32
23562}
23563
23564#[no_mangle]
23565pub unsafe extern "C" fn tempnam(dir: *const c_char, pfx: *const c_char) -> *mut c_char {
23566    let mut path = [0 as c_char; 256];
23567    let mut i = 0;
23568    if !dir.is_null() {
23569        while *dir.add(i) != 0 && i < 200 { path[i] = *dir.add(i); i += 1; }
23570        if i > 0 && path[i-1] != b'/' as c_char { path[i] = b'/' as c_char; i += 1; }
23571    } else {
23572        for &c in b"/tmp/" { path[i] = c as c_char; i += 1; }
23573    }
23574    if !pfx.is_null() {
23575        let mut j = 0;
23576        while *pfx.add(j) != 0 && i < 220 { path[i] = *pfx.add(j); i += 1; j += 1; }
23577    }
23578    for &c in b"XXXXXX" { path[i] = c as c_char; i += 1; }
23579    path[i] = 0;
23580    let fd = mkstemp(path.as_mut_ptr());
23581    if fd < 0 { return core::ptr::null_mut(); }
23582    close(fd);
23583    unlink(path.as_ptr());
23584    let n = strlen(path.as_ptr());
23585    let out = malloc(n + 1) as *mut c_char;
23586    if out.is_null() { return core::ptr::null_mut(); }
23587    core::ptr::copy_nonoverlapping(path.as_ptr(), out, n + 1);
23588    out
23589}
23590
23591#[no_mangle]
23592pub unsafe extern "C" fn putwc(c: u32, f: *mut c_void) -> u32 {
23593    fputwc(c as c_int, f as *mut FILE) as u32
23594}
23595
23596#[no_mangle]
23597pub unsafe extern "C" fn __uflow(f: *mut c_void) -> c_int {
23598    fgetc(f as *mut FILE)
23599}
23600
23601#[no_mangle]
23602pub unsafe extern "C" fn __xmknod(_ver: c_int, path: *const c_char, mode: c_uint, dev: u64) -> c_int {
23603    mknod(path, mode, dev)
23604}
23605
23606#[no_mangle]
23607pub unsafe extern "C" fn __xmknodat(_ver: c_int, dirfd: c_int, path: *const c_char, mode: c_uint, dev: u64) -> c_int {
23608    mknodat(dirfd, path, mode, dev)
23609}
23610
23611#[no_mangle]
23612pub 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 {
23613    let r = <Arch as Syscalls>::syscall5(SYS_NAME_TO_HANDLE_AT, dirfd as i64, path as i64, handle as i64, mount_id as i64, flags as i64);
23614    syscall_ret(r) as c_int
23615}
23616
23617#[no_mangle]
23618pub unsafe extern "C" fn open_by_handle_at(mount_fd: c_int, handle: *mut c_void, flags: c_int) -> c_int {
23619    let r = <Arch as Syscalls>::syscall3(SYS_OPEN_BY_HANDLE_AT, mount_fd as i64, handle as i64, flags as i64);
23620    syscall_ret(r) as c_int
23621}
23622
23623#[no_mangle]
23624pub unsafe extern "C" fn dn_skipname(comp: *const u8, eom: *const u8) -> c_int {
23625    let len = match (eom as usize).checked_sub(comp as usize) {
23626        Some(n) => n,
23627        None => return -1,
23628    };
23629    let msg = match InBuf::new(comp, len) {
23630        Some(msg) => msg,
23631        None => return -1,
23632    };
23633    match dns_skip_name(&msg, 0) {
23634        Some(n) if n <= c_int::MAX as usize => n as c_int,
23635        _ => -1,
23636    }
23637}
23638
23639#[no_mangle]
23640pub 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 {
23641    if exp.is_null() || dst.is_null() || dstsiz <= 0 { return -1; }
23642    let mut o = 0usize;
23643    let mut p = exp;
23644    loop {
23645        let start = p;
23646        while *p != 0 && *p != b'.' as c_char { p = p.add(1); }
23647        let l = p as usize - start as usize;
23648        if l > 63 || o + l + 2 > dstsiz as usize { return -1; }
23649        *dst.add(o) = l as u8; o += 1;
23650        core::ptr::copy_nonoverlapping(start as *const u8, dst.add(o), l);
23651        o += l;
23652        if *p == 0 { break; }
23653        p = p.add(1);
23654    }
23655    if o + 1 > dstsiz as usize { return -1; }
23656    *dst.add(o) = 0;
23657    (o + 1) as c_int
23658}
23659
23660// ============================================================
23661// Shadow database
23662// ============================================================
23663
23664#[repr(C)]
23665#[derive(Copy, Clone)]
23666pub struct Spwd {
23667    pub sp_namp: *mut c_char,
23668    pub sp_pwdp: *mut c_char,
23669    pub sp_lstchg: c_long,
23670    pub sp_min: c_long,
23671    pub sp_max: c_long,
23672    pub sp_warn: c_long,
23673    pub sp_inact: c_long,
23674    pub sp_expire: c_long,
23675    pub sp_flag: c_ulong,
23676}
23677
23678static mut SPWD_ENT: Spwd = Spwd {
23679    sp_namp: core::ptr::null_mut(), sp_pwdp: core::ptr::null_mut(),
23680    sp_lstchg: 0, sp_min: 0, sp_max: 0, sp_warn: 0, sp_inact: 0,
23681    sp_expire: 0, sp_flag: 0,
23682};
23683static mut SPWD_BUF: *mut c_char = core::ptr::null_mut();
23684static mut SPWD_BUF_CAP: usize = 0;
23685static mut SPWD_LINE: *mut c_char = core::ptr::null_mut();
23686static mut SPWD_LINE_CAP: usize = 0;
23687static mut SPWD_FILE: *mut FILE = core::ptr::null_mut();
23688
23689unsafe fn ensure_spwd_buf(need: usize) -> bool {
23690    if SPWD_BUF_CAP >= need {
23691        return true;
23692    }
23693    let mut cap = if SPWD_BUF_CAP == 0 { 1024 } else { SPWD_BUF_CAP };
23694    while cap < need {
23695        cap = match cap.checked_mul(2) {
23696            Some(v) => v,
23697            None => return false,
23698        };
23699    }
23700    let grown = crate::realloc(SPWD_BUF as *mut c_void, cap) as *mut c_char;
23701    if grown.is_null() {
23702        ERRNO!() = ENOMEM;
23703        return false;
23704    }
23705    SPWD_BUF = grown;
23706    SPWD_BUF_CAP = cap;
23707    true
23708}
23709
23710/// Read one line from `f` with getline and parse it into the static entry.
23711/// Lines that do not have all nine shadow fields are skipped.
23712unsafe fn spwd_next(f: *mut FILE) -> *mut Spwd {
23713    loop {
23714        let n = crate::getline(&raw mut SPWD_LINE, &raw mut SPWD_LINE_CAP, f);
23715        if n < 0 {
23716            return core::ptr::null_mut();
23717        }
23718        let len = n as usize;
23719        if len > 0 && *SPWD_LINE.add(len - 1) == b'\n' as c_char {
23720            *SPWD_LINE.add(len - 1) = 0;
23721        }
23722        if !ensure_spwd_buf(len + 1) {
23723            return core::ptr::null_mut();
23724        }
23725        if parse_spwd(SPWD_LINE, &raw mut SPWD_ENT, SPWD_BUF, SPWD_BUF_CAP) {
23726            return &raw mut SPWD_ENT;
23727        }
23728    }
23729}
23730
23731unsafe fn parse_spwd(line: *const c_char, ent: *mut Spwd, buf: *mut c_char, buflen: usize) -> bool {
23732    let mut fields: [*mut c_char; 9] = [core::ptr::null_mut(); 9];
23733    let n = match split_colon_fields(line, buf, buflen, &mut fields) {
23734        Some(n) => n,
23735        None => return false,
23736    };
23737    if n < 9 { return false; }
23738    (*ent).sp_namp = fields[0];
23739    (*ent).sp_pwdp = fields[1];
23740    (*ent).sp_lstchg = crate::strtol(fields[2], core::ptr::null_mut(), 10) as c_long;
23741    (*ent).sp_min = crate::strtol(fields[3], core::ptr::null_mut(), 10) as c_long;
23742    (*ent).sp_max = crate::strtol(fields[4], core::ptr::null_mut(), 10) as c_long;
23743    (*ent).sp_warn = crate::strtol(fields[5], core::ptr::null_mut(), 10) as c_long;
23744    (*ent).sp_inact = crate::strtol(fields[6], core::ptr::null_mut(), 10) as c_long;
23745    (*ent).sp_expire = crate::strtol(fields[7], core::ptr::null_mut(), 10) as c_long;
23746    (*ent).sp_flag = crate::strtoul(fields[8], core::ptr::null_mut(), 10) as c_ulong;
23747    true
23748}
23749
23750#[no_mangle]
23751pub unsafe extern "C" fn setspent() {
23752    endspent();
23753    SPWD_FILE = crate::fopen(b"/etc/shadow\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
23754}
23755
23756#[no_mangle]
23757pub unsafe extern "C" fn endspent() {
23758    if !SPWD_FILE.is_null() { crate::fclose(SPWD_FILE); SPWD_FILE = core::ptr::null_mut(); }
23759}
23760
23761#[no_mangle]
23762pub unsafe extern "C" fn getspent() -> *mut Spwd {
23763    if SPWD_FILE.is_null() { setspent(); if SPWD_FILE.is_null() { return core::ptr::null_mut(); } }
23764    spwd_next(SPWD_FILE)
23765}
23766
23767#[no_mangle]
23768pub unsafe extern "C" fn fgetspent(f: *mut FILE) -> *mut Spwd {
23769    if f.is_null() { return core::ptr::null_mut(); }
23770    spwd_next(f)
23771}
23772
23773#[no_mangle]
23774pub unsafe extern "C" fn getspnam(name: *const c_char) -> *mut Spwd {
23775    if name.is_null() { return core::ptr::null_mut(); }
23776    setspent();
23777    loop {
23778        let sp = getspent();
23779        if sp.is_null() { break; }
23780        if crate::strcmp((*sp).sp_namp as *const u8, name as *const u8) == 0 { endspent(); return sp; }
23781    }
23782    endspent();
23783    core::ptr::null_mut()
23784}
23785
23786unsafe fn getsp_r_inner(
23787    name: *const c_char,
23788    sp: *mut Spwd,
23789    buf: *mut c_char,
23790    buflen: usize,
23791    result: *mut *mut Spwd,
23792) -> c_int {
23793    if name.is_null() || sp.is_null() || buf.is_null() || result.is_null() {
23794        return EINVAL;
23795    }
23796    *result = core::ptr::null_mut();
23797    let f = crate::fopen(b"/etc/shadow\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
23798    if f.is_null() { return ERRNO!(); }
23799    let mut line: *mut c_char = core::ptr::null_mut();
23800    let mut cap: usize = 0;
23801    let mut err = 0;
23802    loop {
23803        let n = crate::getline(&raw mut line, &raw mut cap, f);
23804        if n < 0 { break; }
23805        let mut len = n as usize;
23806        if len > 0 && *line.add(len - 1) == b'\n' as c_char {
23807            *line.add(len - 1) = 0;
23808            len -= 1;
23809        }
23810        if len + 1 > buflen {
23811            err = ERANGE;
23812            break;
23813        }
23814        if parse_spwd(line, sp, buf, buflen) {
23815            if crate::strcmp((*sp).sp_namp as *const u8, name as *const u8) == 0 {
23816                *result = sp;
23817                break;
23818            }
23819        }
23820    }
23821    crate::free(line as *mut c_void);
23822    crate::fclose(f);
23823    err
23824}
23825
23826#[no_mangle]
23827pub 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 {
23828    getsp_r_inner(name, sp, buf, buflen, result)
23829}
23830
23831#[no_mangle]
23832pub unsafe extern "C" fn putspent(sp: *const Spwd, f: *mut FILE) -> c_int {
23833    if sp.is_null() || f.is_null() { return -1; }
23834    crate::fprintf(f, b"%s:%s:%ld:%ld:%ld:%ld:%ld:%ld:%lu\\n\0".as_ptr() as *const c_char,
23835        (*sp).sp_namp, (*sp).sp_pwdp, (*sp).sp_lstchg, (*sp).sp_min, (*sp).sp_max,
23836        (*sp).sp_warn, (*sp).sp_inact, (*sp).sp_expire, (*sp).sp_flag)
23837}
23838
23839#[no_mangle]
23840pub unsafe extern "C" fn getgrouplist(user: *const c_char, group: u32, groups: *mut u32, ngroups: *mut i32) -> c_int {
23841    if user.is_null() || groups.is_null() || ngroups.is_null() { return -1; }
23842    if *ngroups < 0 { return -1; }
23843    let max = *ngroups as usize;
23844    let mut n = 0usize;
23845    if n < max { *groups.add(n) = group; }
23846    n += 1;
23847    setgrent();
23848    loop {
23849        let g = getgrent();
23850        if g.is_null() { break; }
23851        if (*g).gr_gid == group { continue; }
23852        let mut found = false;
23853        let mut i = 0;
23854        while !(*(*g).gr_mem.add(i)).is_null() {
23855            if crate::strcmp(*(*g).gr_mem.add(i) as *const u8, user as *const u8) == 0 {
23856                found = true;
23857                break;
23858            }
23859            i += 1;
23860        }
23861        if found {
23862            if n < max { *groups.add(n) = (*g).gr_gid; }
23863            n += 1;
23864        }
23865    }
23866    endgrent();
23867    if n > max { *ngroups = n as i32; return -1; }
23868    *ngroups = n as i32;
23869    n as c_int
23870}