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