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(any(target_arch = "riscv64", target_arch = "loongarch64"))]
23#[repr(C)]
24#[derive(Copy, Clone)]
25pub struct f128 {
26    lo: u64,
27    hi: u64,
28}
29
30// powerpc64 uses the IBM double-double format: two doubles, high part first.
31// Passing it as a two-f64 aggregate reproduces the ELFv2 register pair.
32#[cfg(target_arch = "powerpc64")]
33#[repr(C)]
34#[derive(Copy, Clone)]
35pub struct f128 {
36    hi: f64,
37    lo: f64,
38}
39
40#[cfg(any(
41    target_arch = "aarch64",
42    target_arch = "riscv64",
43    target_arch = "loongarch64"
44))]
45#[inline]
46fn f128_from_bits(bits: u128) -> f128 {
47    unsafe { core::mem::transmute::<u128, f128>(bits) }
48}
49
50#[cfg(any(
51    target_arch = "aarch64",
52    target_arch = "riscv64",
53    target_arch = "loongarch64"
54))]
55#[inline]
56fn f128_to_bits(x: f128) -> u128 {
57    unsafe { core::mem::transmute::<f128, u128>(x) }
58}
59
60#[cfg(any(
61    target_arch = "aarch64",
62    target_arch = "riscv64",
63    target_arch = "loongarch64"
64))]
65fn f128_is_nan(x: f128) -> bool {
66    let bits = f128_to_bits(x);
67    ((bits >> 112) & 0x7fff) == 0x7fff && (bits & ((1u128 << 112) - 1)) != 0
68}
69
70#[cfg(target_arch = "powerpc64")]
71fn f128_is_nan(x: f128) -> bool {
72    x.hi.is_nan() || x.lo.is_nan()
73}
74
75#[cfg(any(
76    target_arch = "aarch64",
77    target_arch = "riscv64",
78    target_arch = "loongarch64"
79))]
80fn f128_to_f64(x: f128) -> f64 {
81    let bits = f128_to_bits(x);
82    let sign = (bits >> 127) as u64;
83    let exp = ((bits >> 112) & 0x7fff) as i32;
84    let frac = bits & ((1u128 << 112) - 1);
85    let signbit = sign << 63;
86    if exp == 0x7fff {
87        let m = if frac == 0 {
88            0x7ff0_0000_0000_0000
89        } else {
90            0x7ff8_0000_0000_0000
91        };
92        return f64::from_bits(signbit | m);
93    }
94    if exp == 0 {
95        return f64::from_bits(signbit);
96    }
97    let e = exp - 16383;
98    if e > 1023 {
99        return f64::from_bits(signbit | 0x7ff0_0000_0000_0000);
100    }
101    if e < -1074 {
102        return f64::from_bits(signbit);
103    }
104    let sig = (1u128 << 112) | frac;
105    if e >= -1022 {
106        let mut m = (sig >> 60) as u64;
107        let rem = sig & ((1u128 << 60) - 1);
108        let half = 1u128 << 59;
109        if rem > half || (rem == half && (m & 1) != 0) {
110            m += 1;
111        }
112        let mut ef = (e + 1023) as u64;
113        if m == (1u64 << 53) {
114            m >>= 1;
115            ef += 1;
116        }
117        if ef >= 0x7ff {
118            return f64::from_bits(signbit | 0x7ff0_0000_0000_0000);
119        }
120        return f64::from_bits(signbit | (ef << 52) | (m & ((1u64 << 52) - 1)));
121    }
122    let rshift = (-(e + 962)) as u32;
123    let mut m = (sig >> rshift) as u64;
124    let rem = sig & ((1u128 << rshift) - 1);
125    let half = 1u128 << (rshift - 1);
126    if rem > half || (rem == half && (m & 1) != 0) {
127        m += 1;
128    }
129    if m >= (1u64 << 52) {
130        return f64::from_bits(signbit | (1u64 << 52));
131    }
132    f64::from_bits(signbit | m)
133}
134
135#[cfg(target_arch = "powerpc64")]
136fn f128_to_f64(x: f128) -> f64 {
137    x.hi + x.lo
138}
139
140#[cfg(target_arch = "powerpc64")]
141unsafe fn valist_read_f128(args: &mut VaList<'_>) -> f128 {
142    // IBM double-double occupies two consecutive FPR save slots.
143    let hi = args.next_arg::<f64>();
144    let lo = args.next_arg::<f64>();
145    f128 { hi, lo }
146}
147
148#[cfg(target_arch = "riscv64")]
149unsafe fn valist_read_f128(args: &mut VaList<'_>) -> f128 {
150    // RISC-V va_list is an opaque pointer to the next argument. A 16-byte
151    // variable argument is 16-byte aligned and 16 bytes long.
152    let pp = args as *mut VaList<'_> as *mut *const u8;
153    let p = ((*pp as usize) + 15) & !15usize;
154    let bits = core::ptr::read_unaligned(p as *const u128);
155    *pp = (p + 16) as *const u8;
156    f128_from_bits(bits)
157}
158
159#[cfg(target_arch = "aarch64")]
160#[repr(C)]
161struct Aarch64VaList {
162    stack: *const u8,
163    gr_top: *const u8,
164    vr_top: *const u8,
165    gr_offs: i32,
166    vr_offs: i32,
167}
168
169#[cfg(target_arch = "aarch64")]
170unsafe fn valist_read_f128(args: &mut VaList<'_>) -> f128 {
171    let p = args as *mut VaList<'_> as *mut Aarch64VaList;
172    let off = (*p).vr_offs;
173    let addr = if off == 0 {
174        let a = (*p).stack;
175        (*p).stack = a.add(16);
176        a
177    } else {
178        let a = (*p).vr_top.offset(off as isize);
179        (*p).vr_offs = off + 16;
180        a
181    };
182    f128_from_bits(core::ptr::read_unaligned(addr as *const u128))
183}
184
185#[cfg(target_arch = "powerpc64")]
186fn f64_to_f128(v: f64) -> f128 {
187    f128 { hi: v, lo: 0.0 }
188}
189
190#[cfg(any(
191    target_arch = "aarch64",
192    target_arch = "riscv64",
193    target_arch = "loongarch64"
194))]
195fn f64_to_f128(v: f64) -> f128 {
196    let bits = v.to_bits();
197    let sign = (bits >> 63) as u128;
198    let exp = ((bits >> 52) & 0x7ff) as i32;
199    let frac = bits & ((1u64 << 52) - 1);
200    if exp == 0x7ff {
201        let m = if frac == 0 {
202            0
203        } else {
204            ((frac as u128) << 60) | (1u128 << 111)
205        };
206        return f128_from_bits((sign << 127) | (0x7fff_u128 << 112) | m);
207    }
208    if exp == 0 {
209        if frac == 0 {
210            return f128_from_bits(sign << 127);
211        }
212        let msb = 63 - frac.leading_zeros() as i32; // 0..51
213        let e = msb - 1074;
214        let f = ((frac as u128) << (112 - msb as u32)) & ((1u128 << 112) - 1);
215        return f128_from_bits((sign << 127) | (((e + 16383) as u128) << 112) | f);
216    }
217    let e = exp - 1023;
218    let f = (frac as u128) << 60;
219    f128_from_bits((sign << 127) | (((e + 16383) as u128) << 112) | f)
220}
221
222use core::ptr::null_mut;
223use core::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, AtomicU32, AtomicUsize, Ordering};
224
225macro_rules! ERRNO {
226    () => {
227        *errno_ptr()
228    };
229}
230
231// h_errno shares the TCB with errno: 0x30 is errno, 0x34 is the free slot
232// before the vDSO getrandom state at 0x38.  The exported `h_errno` symbol is
233// the fallback for static programs and threads without a TCB, matching musl.
234macro_rules! H_ERRNO {
235    () => {
236        *h_errno_ptr()
237    };
238}
239
240include!("encoding_tables.rs");
241mod math {
242    #[allow(unused_imports)]
243    use super::*;
244
245    include!("math_helpers.rs");
246    include!("math_bitmanip.rs");
247    include!("math_sqrtfmod.rs");
248    include!("math_trig.rs");
249    include!("math_exp.rs");
250    include!("math_lgamma.rs");
251    include!("math_tgamma.rs");
252    include!("math_bessel.rs");
253    include!("math_log.rs");
254    include!("math_pow.rs");
255    include!("math_hypot.rs");
256    include!("math_hyperbolic.rs");
257    include!("math_invtrig.rs");
258    include!("math_lrint.rs");
259    include!("math_long_double.rs");
260    include!("math_complex.rs");
261    include!("math_extra.rs");
262}
263pub use math::*;
264include!("alloc.rs");
265include!("string_fast.rs");
266include!("vdso.rs");
267include!("iconv_iso8859.rs");
268include!("arch.rs");
269
270include!("errno.rs");
271// ============================================================
272// Constants
273// ============================================================
274
275const PROT_READ: i32 = 1;
276const PROT_WRITE: i32 = 2;
277const MAP_SHARED: i32 = 0x01;
278const MAP_PRIVATE: i32 = 0x02;
279const MAP_ANONYMOUS: i32 = 0x20;
280
281// ============================================================
282// Syscall wrappers (raw, no_std)
283// ============================================================
284
285#[inline]
286unsafe fn sys_write(fd: i64, buf: *const u8, count: usize) -> i64 {
287    <Arch as Syscalls>::syscall3(SYS_WRITE, fd as i64, buf as i64, count as i64)
288}
289
290#[inline]
291unsafe fn sys_read(fd: i64, buf: *mut u8, count: usize) -> i64 {
292    <Arch as Syscalls>::syscall3(SYS_READ, fd as i64, buf as i64, count as i64)
293}
294
295#[inline]
296unsafe fn sys_open(path: *const u8, flags: i64, mode: i64) -> i64 {
297    <Arch as Syscalls>::syscall4(
298        SYS_OPENAT,
299        AT_FDCWD as i64,
300        path as i64,
301        flags as i64,
302        mode as i64,
303    )
304}
305
306#[inline]
307unsafe fn sys_close(fd: i64) -> i64 {
308    <Arch as Syscalls>::syscall1(SYS_CLOSE, fd as i64)
309}
310
311#[inline]
312unsafe fn sys_lseek(fd: i64, offset: i64, whence: i64) -> i64 {
313    <Arch as Syscalls>::syscall3(SYS_LSEEK, fd as i64, offset as i64, whence as i64)
314}
315
316unsafe fn sys_mmap(
317    addr: *mut u8,
318    length: usize,
319    prot: i32,
320    flags: i32,
321    fd: i32,
322    offset: i64,
323) -> *mut u8 {
324    let result = <Arch as Syscalls>::syscall6(
325        SYS_MMAP,
326        addr as i64,
327        length as i64,
328        prot as i64,
329        flags as i64,
330        fd as i64,
331        offset,
332    );
333    if result < 0 && result > -crate::SYSCALL_ERR_MAX {
334        ERRNO!() = (-result) as c_int;
335        return MMAP_FAILED;
336    }
337    result as *mut u8
338}
339
340unsafe fn sys_munmap(addr: *mut u8, length: usize) -> i64 {
341    <Arch as Syscalls>::syscall2(SYS_MUNMAP, addr as i64, length as i64)
342}
343
344include!("string_more.rs");
345include!("types.rs");
346// ============================================================
347// ctype.h
348// ============================================================
349
350const CT_UPPER: u8 = 1 << 0;
351const CT_LOWER: u8 = 1 << 1;
352const CT_DIGIT: u8 = 1 << 2;
353const CT_SPACE: u8 = 1 << 3;
354const CT_PUNCT: u8 = 1 << 4;
355const CT_CNTRL: u8 = 1 << 5;
356const CT_BLANK: u8 = 1 << 6;
357const CT_XDIGIT: u8 = 1 << 7;
358
359const CT_TABLE: [u8; 128] = {
360    let mut t = [0u8; 128];
361    let mut i = 0;
362    while i < 128 {
363        let c = i as u8;
364        let mut flags = 0u8;
365        if c >= b'A' && c <= b'Z' {
366            flags |= CT_UPPER;
367        }
368        if c >= b'a' && c <= b'z' {
369            flags |= CT_LOWER;
370        }
371        if c >= b'0' && c <= b'9' {
372            flags |= CT_DIGIT;
373        }
374        if c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == b'\x0c' || c == b'\x0b' {
375            flags |= CT_SPACE;
376        }
377        if (c >= b'!' && c <= b'/')
378            || (c >= b':' && c <= b'@')
379            || (c >= b'[' && c <= b'`')
380            || (c >= b'{' && c <= b'~')
381        {
382            flags |= CT_PUNCT;
383        }
384        if c < 0x20 || c == 0x7f {
385            flags |= CT_CNTRL;
386        }
387        if c == b' ' || c == b'\t' {
388            flags |= CT_BLANK;
389        }
390        if (c >= b'0' && c <= b'9') || (c >= b'A' && c <= b'F') || (c >= b'a' && c <= b'f') {
391            flags |= CT_XDIGIT;
392        }
393        t[i] = flags;
394        i += 1;
395    }
396    t
397};
398
399#[inline]
400fn ct_flags(c: c_int) -> u8 {
401    if c < 0 || c > 127 {
402        0
403    } else {
404        CT_TABLE[c as usize]
405    }
406}
407
408#[no_mangle]
409pub extern "C" fn isalnum(c: c_int) -> c_int {
410    (ct_flags(c) & (CT_UPPER | CT_LOWER | CT_DIGIT) != 0) as c_int
411}
412
413#[no_mangle]
414pub extern "C" fn isalpha(c: c_int) -> c_int {
415    (ct_flags(c) & (CT_UPPER | CT_LOWER) != 0) as c_int
416}
417
418#[no_mangle]
419pub extern "C" fn isascii(c: c_int) -> c_int {
420    ((c as u32) <= 127) as c_int
421}
422
423#[no_mangle]
424pub extern "C" fn isblank(c: c_int) -> c_int {
425    (ct_flags(c) & CT_BLANK != 0) as c_int
426}
427
428#[no_mangle]
429pub extern "C" fn iscntrl(c: c_int) -> c_int {
430    (ct_flags(c) & CT_CNTRL != 0) as c_int
431}
432
433#[no_mangle]
434pub extern "C" fn isdigit(c: c_int) -> c_int {
435    (ct_flags(c) & CT_DIGIT != 0) as c_int
436}
437
438#[no_mangle]
439pub extern "C" fn isgraph(c: c_int) -> c_int {
440    (ct_flags(c) & (CT_UPPER | CT_LOWER | CT_DIGIT | CT_PUNCT) != 0) as c_int
441}
442
443#[no_mangle]
444pub extern "C" fn islower(c: c_int) -> c_int {
445    (ct_flags(c) & CT_LOWER != 0) as c_int
446}
447
448#[no_mangle]
449pub extern "C" fn isprint(c: c_int) -> c_int {
450    let flags = ct_flags(c);
451    (flags & (CT_UPPER | CT_LOWER | CT_DIGIT | CT_PUNCT | CT_BLANK) != 0) as c_int
452}
453
454#[no_mangle]
455pub extern "C" fn ispunct(c: c_int) -> c_int {
456    (ct_flags(c) & CT_PUNCT != 0) as c_int
457}
458
459#[no_mangle]
460pub extern "C" fn isspace(c: c_int) -> c_int {
461    (ct_flags(c) & CT_SPACE != 0) as c_int
462}
463
464#[no_mangle]
465pub extern "C" fn isupper(c: c_int) -> c_int {
466    (ct_flags(c) & CT_UPPER != 0) as c_int
467}
468
469#[no_mangle]
470pub extern "C" fn isxdigit(c: c_int) -> c_int {
471    (ct_flags(c) & CT_XDIGIT != 0) as c_int
472}
473
474#[no_mangle]
475pub extern "C" fn tolower(c: c_int) -> c_int {
476    if (ct_flags(c) & CT_UPPER) != 0 {
477        c + (b'a' as c_int - b'A' as c_int)
478    } else {
479        c
480    }
481}
482
483#[no_mangle]
484pub extern "C" fn toupper(c: c_int) -> c_int {
485    if (ct_flags(c) & CT_LOWER) != 0 {
486        c - (b'a' as c_int - b'A' as c_int)
487    } else {
488        c
489    }
490}
491
492include!("stdlib_num.rs");
493// ============================================================
494// Syscall wrappers as public C ABI
495// ============================================================
496
497#[no_mangle]
498pub unsafe extern "C" fn write(fd: c_int, buf: *const c_void, count: SizeT) -> SSizeT {
499    syscall_ret(sys_write(fd as i64, buf as *const u8, count)) as SSizeT
500}
501
502#[no_mangle]
503pub unsafe extern "C" fn read(fd: c_int, buf: *mut c_void, count: SizeT) -> SSizeT {
504    syscall_ret(sys_read(fd as i64, buf as *mut u8, count)) as SSizeT
505}
506
507#[no_mangle]
508pub unsafe extern "C" fn open(path: *const c_char, flags: c_int, mode: c_int) -> c_int {
509    syscall_ret(sys_open(path as *const u8, flags as i64, mode as i64)) as c_int
510}
511
512#[no_mangle]
513pub unsafe extern "C" fn close(fd: c_int) -> c_int {
514    syscall_ret(sys_close(fd as i64)) as c_int
515}
516
517#[no_mangle]
518pub unsafe extern "C" fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64 {
519    syscall_ret(sys_lseek(fd as i64, offset, whence as i64))
520}
521
522// ============================================================
523// Additional syscall wrappers for stdio
524// ============================================================
525
526const O_RDONLY: i32 = 0;
527const O_WRONLY: i32 = 1;
528const O_RDWR: i32 = 2;
529const O_CREAT: i32 = 64;
530const O_TRUNC: i32 = 512;
531const O_APPEND: i32 = 1024;
532const O_EXCL: i32 = 128;
533const O_NONBLOCK: i32 = 2048;
534const O_NOFOLLOW: i32 = if cfg!(any(target_arch = "aarch64", target_arch = "powerpc64")) {
535    0o100000
536} else {
537    0o400000
538};
539const O_DIRECTORY: i32 = if cfg!(any(target_arch = "aarch64", target_arch = "powerpc64")) {
540    0o40000
541} else {
542    0o200000
543};
544const O_NOCTTY: i32 = 0o400;
545const O_PATH: i32 = 0o10000000;
546const O_CLOEXEC: i32 = 0x80000;
547
548const F_GETFD: i32 = 1;
549const F_GETFL: i32 = 3;
550const F_GETOWN: i32 = 9;
551const F_GETSIG: i32 = 11;
552const F_GETLEASE: i32 = 1025;
553const F_GETPIPE_SZ: i32 = 1032;
554const F_GET_SEALS: i32 = 1034;
555const F_SETFD: i32 = 2;
556const F_SETFL: i32 = 4;
557const F_GETLK: i32 = 5;
558const F_SETLK: i32 = 6;
559const F_SETLKW: i32 = 7;
560const F_DUPFD: i32 = 0;
561const F_DUPFD_CLOEXEC: i32 = 1030;
562const FD_CLOEXEC: i32 = 1;
563
564const TIOCGWINSZ: u32 = 0x5413;
565
566#[repr(C)]
567struct winsize {
568    ws_row: u16,
569    ws_col: u16,
570    ws_xpixel: u16,
571    ws_ypixel: u16,
572}
573
574#[inline]
575unsafe fn sys_pipe2(fds: *mut c_int, flags: i32) -> i64 {
576    <Arch as Syscalls>::syscall2(SYS_PIPE2, fds as i64, flags as i64)
577}
578
579#[inline]
580unsafe fn sys_dup3(oldfd: i32, newfd: i32, flags: i32) -> i64 {
581    <Arch as Syscalls>::syscall3(SYS_DUP3, oldfd as i64, newfd as i64, flags as i64)
582}
583
584#[inline]
585unsafe fn sys_fcntl(fd: i32, cmd: i32, arg: i64) -> i64 {
586    <Arch as Syscalls>::syscall3(SYS_FCNTL, fd as i64, cmd as i64, arg as i64)
587}
588
589#[inline]
590unsafe fn sys_ioctl(fd: c_int, request: u32, arg: *mut u8) -> i64 {
591    <Arch as Syscalls>::syscall3(SYS_IOCTL, fd as i64, request as i64, arg as i64)
592}
593
594#[inline]
595unsafe fn sys_unlinkat(dirfd: i32, path: *const u8, flags: i32) -> i64 {
596    <Arch as Syscalls>::syscall3(SYS_UNLINKAT, dirfd as i64, path as i64, flags as i64)
597}
598
599#[inline]
600unsafe fn sys_renameat2(
601    olddirfd: i32,
602    oldpath: *const u8,
603    newdirfd: i32,
604    newpath: *const u8,
605    flags: u32,
606) -> i64 {
607    <Arch as Syscalls>::syscall5(
608        SYS_RENAMEAT2,
609        olddirfd as i64,
610        oldpath as i64,
611        newdirfd as i64,
612        newpath as i64,
613        flags as i64,
614    )
615}
616
617include!("stdio.rs");
618include!("printf.rs");
619include!("scanf.rs");
620include!("stdio_misc.rs");
621// ============================================================
622// Allocator basics
623// ============================================================
624
625const MMAP_FAILED: *mut u8 = !0usize as *mut u8;
626const PAGE: usize = 4096;
627
628// ============================================================
629// Process: exit / _exit / _Exit
630// ============================================================
631
632#[no_mangle]
633pub unsafe extern "C" fn _exit(code: c_int) -> ! {
634    sys_exit_group(code)
635}
636
637#[inline]
638unsafe fn sys_exit_group(code: c_int) -> ! {
639    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT_GROUP, code as i64)
640}
641
642#[inline]
643unsafe fn sys_exit_thread(code: c_int) -> ! {
644    <Arch as Syscalls>::syscall_noreturn1(SYS_EXIT, code as i64)
645}
646
647#[no_mangle]
648pub unsafe extern "C" fn _Exit(code: c_int) -> ! {
649    _exit(code);
650}
651
652#[no_mangle]
653pub unsafe extern "C" fn exit(code: c_int) -> ! {
654    fflush(core::ptr::null_mut());
655    __funcs_on_exit();
656    _exit(code);
657}
658
659#[no_mangle]
660pub unsafe extern "C" fn abort() -> ! {
661    raise(6); // SIGABRT
662    _exit(128 + 6);
663}
664
665// The 128-bit targets and powerpc64 access the stack canary through the
666// global __stack_chk_guard symbol (GOT- or TOC-based for PIE).  Export it so
667// the dynamic linker can resolve it, and seed it from AT_RANDOM at startup.
668#[no_mangle]
669pub static mut __stack_chk_guard: usize = 0;
670
671#[no_mangle]
672pub unsafe extern "C" fn __stack_chk_fail() -> ! {
673    const MSG: &[u8] = b"*** stack smashing detected ***: terminated\n";
674    let _ = sys_write(2, MSG.as_ptr(), MSG.len());
675    abort();
676}
677
678#[no_mangle]
679pub unsafe extern "C" fn __stack_chk_fail_local() -> ! {
680    __stack_chk_fail()
681}
682
683include!("qsort.rs");
684include!("atexit.rs");
685include!("env.rs");
686include!("random.rs");
687include!("system.rs");
688// ============================================================
689// errno: strerror / strerror_r / environ alias
690// ============================================================
691
692// static error string table indexed by errno
693static ERR_STRS: [&[u8]; 134] = [
694    b"Success\0",                                           // 0
695    b"Operation not permitted\0",                           // 1
696    b"No such file or directory\0",                         // 2
697    b"No such process\0",                                   // 3
698    b"Interrupted system call\0",                           // 4
699    b"Input/output error\0",                                // 5
700    b"No such device or address\0",                         // 6
701    b"Argument list too long\0",                            // 7
702    b"Exec format error\0",                                 // 8
703    b"Bad file descriptor\0",                               // 9
704    b"No child processes\0",                                // 10
705    b"Resource temporarily unavailable\0",                  // 11
706    b"Cannot allocate memory\0",                            // 12
707    b"Permission denied\0",                                 // 13
708    b"Bad address\0",                                       // 14
709    b"Block device required\0",                             // 15
710    b"Device or resource busy\0",                           // 16
711    b"File exists\0",                                       // 17
712    b"Invalid cross-device link\0",                         // 18
713    b"No such device\0",                                    // 19
714    b"Not a directory\0",                                   // 20
715    b"Is a directory\0",                                    // 21
716    b"Invalid argument\0",                                  // 22
717    b"Too many open files in system\0",                     // 23
718    b"Too many open files\0",                               // 24
719    b"Inappropriate ioctl for device\0",                    // 25
720    b"Text file busy\0",                                    // 26
721    b"File too large\0",                                    // 27
722    b"No space left on device\0",                           // 28
723    b"Illegal seek\0",                                      // 29
724    b"Read-only file system\0",                             // 30
725    b"Too many links\0",                                    // 31
726    b"Broken pipe\0",                                       // 32
727    b"Numerical argument out of domain\0",                  // 33
728    b"Numerical result out of range\0",                     // 34
729    b"Resource deadlock avoided\0",                         // 35
730    b"File name too long\0",                                // 36
731    b"No locks available\0",                                // 37
732    b"Function not implemented\0",                          // 38
733    b"Directory not empty\0",                               // 39
734    b"Too many levels of symbolic links\0",                 // 40
735    b"Unknown error 41\0",                                  // 41
736    b"No message of desired type\0",                        // 42
737    b"Identifier removed\0",                                // 43
738    b"Channel number out of range\0",                       // 44
739    b"Level 2 not synchronized\0",                          // 45
740    b"Level 3 halted\0",                                    // 46
741    b"Level 3 reset\0",                                     // 47
742    b"Link number out of range\0",                          // 48
743    b"Protocol driver not attached\0",                      // 49
744    b"No CSI structure available\0",                        // 50
745    b"Level 2 halted\0",                                    // 51
746    b"Invalid exchange\0",                                  // 52
747    b"Invalid request descriptor\0",                        // 53
748    b"Exchange full\0",                                     // 54
749    b"No anode\0",                                          // 55
750    b"Invalid request code\0",                              // 56
751    b"Invalid slot\0",                                      // 57
752    b"Unknown error 58\0",                                  // 58
753    b"Bad font file format\0",                              // 59
754    b"Device not a stream\0",                               // 60
755    b"No data available\0",                                 // 61
756    b"Timer expired\0",                                     // 62
757    b"Out of streams resources\0",                          // 63
758    b"Machine is not on the network\0",                     // 64
759    b"Package not installed\0",                             // 65
760    b"Object is remote\0",                                  // 66
761    b"Link has been severed\0",                             // 67
762    b"Advertise error\0",                                   // 68
763    b"Srmount error\0",                                     // 69
764    b"Communication error on send\0",                       // 70
765    b"Protocol error\0",                                    // 71
766    b"Multihop attempted\0",                                // 72
767    b"RFS specific error\0",                                // 73
768    b"Bad message\0",                                       // 74
769    b"Value too large for defined data type\0",             // 75
770    b"Name not unique on network\0",                        // 76
771    b"File descriptor in bad state\0",                      // 77
772    b"Remote address changed\0",                            // 78
773    b"Can not access a needed shared library\0",            // 79
774    b"Accessing a corrupted shared library\0",              // 80
775    b".lib section in a.out corrupted\0",                   // 81
776    b"Attempting to link in too many shared libraries\0",   // 82
777    b"Cannot exec a shared library directly\0",             // 83
778    b"Invalid or incomplete multibyte or wide character\0", // 84
779    b"Interrupted system call should be restarted\0",       // 85
780    b"Streams pipe error\0",                                // 86
781    b"Too many users\0",                                    // 87
782    b"Socket operation on non-socket\0",                    // 88
783    b"Destination address required\0",                      // 89
784    b"Message too long\0",                                  // 90
785    b"Protocol wrong type for socket\0",                    // 91
786    b"Protocol not available\0",                            // 92
787    b"Protocol not supported\0",                            // 93
788    b"Socket type not supported\0",                         // 94
789    b"Operation not supported\0",                           // 95
790    b"Protocol family not supported\0",                     // 96
791    b"Address family not supported by protocol\0",          // 97
792    b"Address already in use\0",                            // 98
793    b"Cannot assign requested address\0",                   // 99
794    b"Network is down\0",                                   // 100
795    b"Network is unreachable\0",                            // 101
796    b"Network dropped connection on reset\0",               // 102
797    b"Software caused connection abort\0",                  // 103
798    b"Connection reset by peer\0",                          // 104
799    b"No buffer space available\0",                         // 105
800    b"Transport endpoint is already connected\0",           // 106
801    b"Transport endpoint is not connected\0",               // 107
802    b"Cannot send after transport endpoint shutdown\0",     // 108
803    b"Too many references: cannot splice\0",                // 109
804    b"Connection timed out\0",                              // 110
805    b"Connection refused\0",                                // 111
806    b"Host is down\0",                                      // 112
807    b"No route to host\0",                                  // 113
808    b"Operation already in progress\0",                     // 114
809    b"Operation now in progress\0",                         // 115
810    b"Stale file handle\0",                                 // 116
811    b"Structure needs cleaning\0",                          // 117
812    b"Not a XENIX named type file\0",                       // 118
813    b"No XENIX semaphores available\0",                     // 119
814    b"Is a named type file\0",                              // 120
815    b"Remote I/O error\0",                                  // 121
816    b"Quota exceeded\0",                                    // 122
817    b"No medium found\0",                                   // 123
818    b"Wrong medium type\0",                                 // 124
819    b"Operation canceled\0",                                // 125
820    b"Required key not available\0",                        // 126
821    b"Key has expired\0",                                   // 127
822    b"Key has been revoked\0",                              // 128
823    b"Key was rejected by service\0",                       // 129
824    b"Owner died\0",                                        // 130
825    b"State not recoverable\0",                             // 131
826    b"Operation not possible due to RF-kill\0",             // 132
827    b"Memory page has hardware error\0",                    // 133
828];
829
830#[no_mangle]
831pub unsafe extern "C" fn strerror(errnum: c_int) -> *mut c_char {
832    if errnum < 0 || errnum as usize >= ERR_STRS.len() {
833        // static buf for unknown errors
834        static mut UNKNOWN_BUF: [c_char; 64] = [0; 64];
835        let prefix = b"Unknown error \0";
836        let mut i = 0;
837        while prefix[i] != 0 {
838            UNKNOWN_BUF[i] = prefix[i] as c_char;
839            i += 1;
840        }
841        let (buf, len) = format_u64(errnum.unsigned_abs() as u64);
842        for j in 0..len {
843            UNKNOWN_BUF[i] = buf[20 - len + j] as c_char;
844            i += 1;
845        }
846        UNKNOWN_BUF[i] = 0;
847        return core::ptr::addr_of_mut!(UNKNOWN_BUF).cast::<c_char>();
848    }
849    ERR_STRS[errnum as usize].as_ptr() as *mut c_char
850}
851
852#[no_mangle]
853pub unsafe extern "C" fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: usize) -> c_int {
854    let s = strerror(errnum);
855    let slen = strlen(s as *const c_char);
856    if slen >= buflen {
857        if buflen > 0 {
858            core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, buflen - 1);
859            *buf.add(buflen - 1) = 0;
860        }
861        return 34; // ERANGE
862    }
863    core::ptr::copy_nonoverlapping(s as *const u8, buf as *mut u8, slen + 1);
864    0
865}
866
867// Alias for programs that declare `extern char **environ`.
868#[no_mangle]
869pub static mut environ: *mut *mut c_char = core::ptr::null_mut();
870
871// keep environ in sync with __environ
872unsafe fn sync_environ() {
873    environ = __environ;
874}
875
876include!("unistd_ext.rs");
877include!("libgen.rs");
878include!("inet.rs");
879include!("strtod.rs");
880include!("stdio_mem.rs");
881// ============================================================
882// Stat (for ftok)
883// ============================================================
884
885#[repr(C)]
886struct kernel_stat64 {
887    st_dev: u64,
888    st_ino: u64,
889    st_nlink: u64,
890    st_mode: u32,
891    st_uid: u32,
892    st_gid: u32,
893    __pad0: c_int,
894    st_rdev: u64,
895    st_size: i64,
896    st_blksize: i64,
897    st_blocks: i64,
898    st_atime: i64,
899    st_atime_nsec: i64,
900    st_mtime: i64,
901    st_mtime_nsec: i64,
902    st_ctime: i64,
903    st_ctime_nsec: i64,
904    __unused: [i64; 3],
905}
906
907// sys_stat = 4 on x86_64
908#[inline]
909unsafe fn sys_stat(path: *const u8, statbuf: *mut kernel_stat64) -> i64 {
910    <Arch as Syscalls>::syscall4(
911        SYS_NEWFSTATAT,
912        AT_FDCWD as i64,
913        path as i64,
914        statbuf as i64,
915        0,
916    )
917}
918
919include!("search.rs");
920include!("mntent.rs");
921include!("sysvipc.rs");
922// ============================================================
923// regex.h
924// ============================================================
925
926// musl defines regoff_t as _Addr (long on every Linux target), not int.
927type regoff_t = c_long;
928
929#[repr(C)]
930pub struct regex_t {
931    pub re_nsub: usize,
932    pub __opaque: *mut c_void,
933    pub __padding: [*mut c_void; 4],
934    pub __nsub2: usize,
935    pub __padding2: c_char,
936}
937
938#[repr(C)]
939pub struct regmatch_t {
940    pub rm_so: regoff_t,
941    pub rm_eo: regoff_t,
942}
943
944include!("regex.rs");
945include!("tz.rs");
946
947// The dynamic loader is part of libc, mirroring musl's single-file design.
948// It is compiled as a module so its private syscall/string helpers do not
949// collide with the libc namespace; its exported entry points remain global.
950#[allow(dead_code, deref_nullptr)]
951mod ldso;
952
953include!("wchar_misc.rs");
954include!("sys_misc.rs");
955include!("compat_syscalls.rs");