Skip to main content

c/
compat_extra.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// Real implementations for the remaining POSIX/GNU compatibility surface:
5// AIO, mqueue attributes, pthread introspection, spawn attributes, stdio
6// internals, and assorted legacy calls.
7
8// ============================================================
9// AIO (synchronous completion)
10// ============================================================
11
12#[repr(C)]
13pub struct Aiocb {
14    pub aio_fildes: c_int,
15    pub aio_lio_opcode: c_int,
16    pub aio_reqprio: c_int,
17    __pad: c_int,
18    pub aio_buf: *mut c_void,
19    pub aio_nbytes: usize,
20    pub aio_sigevent: [u8; 64],
21    pub aio_offset: i64,
22}
23
24const _: [(); 104] = [(); core::mem::size_of::<Aiocb>()];
25
26#[derive(Copy, Clone)]
27struct AioSlot {
28    cb: *mut Aiocb,
29    ret: isize,
30    err: c_int,
31    active: bool,
32    next: *mut AioSlot,
33    prev: *mut AioSlot,
34}
35
36// Completion records are allocated on demand and recycled through a free
37// list, mirroring musl's dynamic AIO bookkeeping.
38static mut AIO_HEAD: *mut AioSlot = core::ptr::null_mut();
39static mut AIO_FREE: *mut AioSlot = core::ptr::null_mut();
40static AIO_LOCK: AtomicI32 = AtomicI32::new(0);
41
42unsafe fn aio_lock() {
43    while AIO_LOCK
44        .compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed)
45        .is_err()
46    {
47        core::hint::spin_loop();
48    }
49}
50
51unsafe fn aio_unlock() {
52    AIO_LOCK.store(0, Ordering::Release);
53}
54
55unsafe fn aio_alloc() -> *mut AioSlot {
56    let slot = if AIO_FREE.is_null() {
57        crate::malloc(core::mem::size_of::<AioSlot>()) as *mut AioSlot
58    } else {
59        let slot = AIO_FREE;
60        AIO_FREE = (*slot).next;
61        slot
62    };
63    if !slot.is_null() {
64        (*slot).cb = core::ptr::null_mut();
65        (*slot).ret = 0;
66        (*slot).err = 0;
67        (*slot).active = false;
68        (*slot).next = core::ptr::null_mut();
69        (*slot).prev = core::ptr::null_mut();
70    }
71    slot
72}
73
74unsafe fn aio_get(cb: *mut Aiocb) -> *mut AioSlot {
75    let mut slot = AIO_HEAD;
76    while !slot.is_null() {
77        if (*slot).cb == cb {
78            return slot;
79        }
80        slot = (*slot).next;
81    }
82    let slot = aio_alloc();
83    if slot.is_null() {
84        return core::ptr::null_mut();
85    }
86    (*slot).cb = cb;
87    (*slot).next = AIO_HEAD;
88    if !AIO_HEAD.is_null() {
89        (*AIO_HEAD).prev = slot;
90    }
91    AIO_HEAD = slot;
92    slot
93}
94
95unsafe fn aio_find(cb: *const Aiocb) -> *mut AioSlot {
96    let mut slot = AIO_HEAD;
97    while !slot.is_null() {
98        if (*slot).cb == cb as *mut Aiocb && (*slot).active {
99            return slot;
100        }
101        slot = (*slot).next;
102    }
103    core::ptr::null_mut()
104}
105
106unsafe fn aio_unlink(slot: *mut AioSlot) {
107    let prev = (*slot).prev;
108    let next = (*slot).next;
109    if prev.is_null() {
110        AIO_HEAD = next;
111    } else {
112        (*prev).next = next;
113    }
114    if !next.is_null() {
115        (*next).prev = prev;
116    }
117    (*slot).prev = core::ptr::null_mut();
118    (*slot).next = core::ptr::null_mut();
119}
120
121unsafe fn aio_finish(cb: *mut Aiocb, ret: isize, err: c_int) -> bool {
122    aio_lock();
123    let slot = aio_get(cb);
124    if slot.is_null() {
125        aio_unlock();
126        return false;
127    }
128    (*slot).ret = ret;
129    (*slot).err = err;
130    (*slot).active = true;
131    aio_unlock();
132    true
133}
134
135#[no_mangle]
136pub unsafe extern "C" fn aio_read(aiocbp: *mut Aiocb) -> c_int {
137    if aiocbp.is_null() { ERRNO!() = EINVAL; return -1; }
138    let r = crate::pread(
139        (*aiocbp).aio_fildes,
140        (*aiocbp).aio_buf,
141        (*aiocbp).aio_nbytes,
142        (*aiocbp).aio_offset,
143    );
144    let ok = if r < 0 {
145        aio_finish(aiocbp, -1, ERRNO!())
146    } else {
147        aio_finish(aiocbp, r, 0)
148    };
149    if !ok { ERRNO!() = EAGAIN; return -1; }
150    0
151}
152
153#[no_mangle]
154pub unsafe extern "C" fn aio_write(aiocbp: *mut Aiocb) -> c_int {
155    if aiocbp.is_null() { ERRNO!() = EINVAL; return -1; }
156    let r = crate::pwrite(
157        (*aiocbp).aio_fildes,
158        (*aiocbp).aio_buf as *const u8,
159        (*aiocbp).aio_nbytes,
160        (*aiocbp).aio_offset,
161    );
162    let ok = if r < 0 {
163        aio_finish(aiocbp, -1, ERRNO!())
164    } else {
165        aio_finish(aiocbp, r, 0)
166    };
167    if !ok { ERRNO!() = EAGAIN; return -1; }
168    0
169}
170
171const O_DSYNC_V: c_int = 0o10000;
172const O_SYNC_V: c_int = 0o4010000;
173const AIO_ALLDONE_V: c_int = 2;
174const LIO_READ_V: c_int = 0;
175const LIO_WRITE_V: c_int = 1;
176const LIO_NOP_V: c_int = 2;
177
178#[no_mangle]
179pub unsafe extern "C" fn aio_fsync(op: c_int, aiocbp: *mut Aiocb) -> c_int {
180    if aiocbp.is_null() { ERRNO!() = EINVAL; return -1; }
181    let r = if op == O_DSYNC_V {
182        crate::fdatasync((*aiocbp).aio_fildes)
183    } else if op == O_SYNC_V {
184        crate::fsync((*aiocbp).aio_fildes)
185    } else {
186        ERRNO!() = EINVAL;
187        return -1;
188    };
189    let ok = if r < 0 {
190        aio_finish(aiocbp, -1, ERRNO!())
191    } else {
192        aio_finish(aiocbp, 0, 0)
193    };
194    if !ok { ERRNO!() = EAGAIN; return -1; }
195    0
196}
197
198#[no_mangle]
199pub unsafe extern "C" fn aio_error(aiocbp: *const Aiocb) -> c_int {
200    if aiocbp.is_null() { return EINVAL; }
201    aio_lock();
202    let slot = aio_find(aiocbp);
203    let err = if slot.is_null() { EINVAL } else { (*slot).err };
204    aio_unlock();
205    err
206}
207
208#[no_mangle]
209pub unsafe extern "C" fn aio_return(aiocbp: *mut Aiocb) -> isize {
210    if aiocbp.is_null() { ERRNO!() = EINVAL; return -1; }
211    aio_lock();
212    let slot = aio_find(aiocbp);
213    if slot.is_null() {
214        aio_unlock();
215        ERRNO!() = EINVAL;
216        return -1;
217    }
218    let ret = (*slot).ret;
219    (*slot).active = false;
220    (*slot).cb = core::ptr::null_mut();
221    (*slot).ret = 0;
222    (*slot).err = 0;
223    aio_unlink(slot);
224    (*slot).next = AIO_FREE;
225    AIO_FREE = slot;
226    aio_unlock();
227    ret
228}
229
230#[no_mangle]
231pub unsafe extern "C" fn aio_cancel(_fd: c_int, _aiocbp: *mut Aiocb) -> c_int {
232    // keel services AIO synchronously, so by the time the caller can cancel
233    // the request it has already completed.
234    AIO_ALLDONE_V
235}
236
237#[no_mangle]
238pub unsafe extern "C" fn aio_suspend(
239    aiocb_list: *const *const Aiocb,
240    nent: c_int,
241    _timeout: *const timespec,
242) -> c_int {
243    if nent <= 0 || aiocb_list.is_null() { ERRNO!() = EINVAL; return -1; }
244    // Every request completes synchronously, so all of them are already done.
245    aio_lock();
246    for i in 0..nent as usize {
247        let cb = *aiocb_list.add(i);
248        if cb.is_null() { continue; }
249        if aio_find(cb).is_null() {
250            aio_unlock();
251            ERRNO!() = EINVAL;
252            return -1;
253        }
254    }
255    aio_unlock();
256    0
257}
258
259#[repr(C)]
260#[derive(Copy, Clone)]
261pub struct SigEvent {
262    pub sigev_value: usize,
263    pub sigev_signo: c_int,
264    pub sigev_notify: c_int,
265    pub sigev_un: [u8; 48],
266}
267
268const SIGEV_SIGNAL_V: c_int = 0;
269const SIGEV_NONE_V: c_int = 1;
270const SIGEV_THREAD_V: c_int = 2;
271
272unsafe fn aio_notify(sev: *const SigEvent) {
273    if sev.is_null() { return; }
274    match (*sev).sigev_notify {
275        SIGEV_SIGNAL_V => {
276            crate::sigqueue(crate::getpid(), (*sev).sigev_signo, (*sev).sigev_value as *mut c_void);
277        }
278        SIGEV_THREAD_V => {
279            let fnptr = core::ptr::read_unaligned((*sev).sigev_un.as_ptr().add(0) as *const usize);
280            if fnptr != 0 {
281                let f: unsafe extern "C" fn(usize) = core::mem::transmute(fnptr);
282                f((*sev).sigev_value);
283            }
284        }
285        _ => {}
286    }
287}
288
289#[no_mangle]
290pub unsafe extern "C" fn lio_listio(
291    mode: c_int,
292    aiocb_list: *const *mut Aiocb,
293    nent: c_int,
294    sevp: *mut SigEvent,
295) -> c_int {
296    if nent < 0 || aiocb_list.is_null() { ERRNO!() = EINVAL; return -1; }
297    let mut ok = 0;
298    for i in 0..nent as usize {
299        let cb = *aiocb_list.add(i);
300        if cb.is_null() { continue; }
301        let r = match (*cb).aio_lio_opcode {
302            LIO_READ_V => aio_read(cb),
303            LIO_WRITE_V => aio_write(cb),
304            LIO_NOP_V => 0,
305            _ => {
306                ERRNO!() = EINVAL;
307                return -1;
308            }
309        };
310        if r == 0 { ok += 1; }
311    }
312    if mode == 1 && !sevp.is_null() {
313        aio_notify(sevp);
314    }
315    if ok == 0 && nent > 0 { -1 } else { 0 }
316}
317
318// ============================================================
319// pthread introspection
320// ============================================================
321
322static mut PTHREAD_DEFAULT_STACK: usize = STACK_SIZE;
323static mut PTHREAD_DEFAULT_GUARD: usize = 4096;
324static mut PTHREAD_CONCURRENCY: c_int = 0;
325
326/// Find the mapping that contains `addr` by reading the tail of
327/// /proc/self/maps. Used for the main thread, whose stack was set up by the
328/// loader and is not tracked in a `Thread` slot.
329unsafe fn mapping_containing(addr: usize) -> Option<(usize, usize)> {
330    let fd = crate::open(b"/proc/self/maps\0".as_ptr() as *const core::ffi::c_char, 0, 0);
331    if fd < 0 {
332        return None;
333    }
334    let size: i64 = crate::lseek(fd, 0, 2);
335    let want: i64 = if size > 16384 { 16384 } else { size };
336    let start = if size > want { size - want } else { 0 };
337    if crate::lseek(fd, start, 0) < 0 {
338        crate::close(fd);
339        return None;
340    }
341    let mut buf = [0u8; 16384];
342    let mut len = 0usize;
343    while len < buf.len() {
344        let n = crate::read(
345            fd,
346            buf.as_mut_ptr().add(len) as *mut core::ffi::c_void,
347            buf.len() - len,
348        );
349        if n <= 0 {
350            break;
351        }
352        len += n as usize;
353    }
354    crate::close(fd);
355
356    let mut result = None;
357    let mut line_start = 0usize;
358    while line_start < len {
359        let mut line_end = line_start;
360        while line_end < len && buf[line_end] != b'\n' {
361            line_end += 1;
362        }
363        let line = &buf[line_start..line_end];
364        if let Some(dash) = line.iter().position(|&c| c == b'-') {
365            let mut lo = 0usize;
366            let mut ok = true;
367            for &c in &line[..dash] {
368                if c.is_ascii_digit() {
369                    lo = lo * 16 + (c - b'0') as usize;
370                } else if (b'a'..=b'f').contains(&c) {
371                    lo = lo * 16 + (c - b'a' + 10) as usize;
372                } else {
373                    ok = false;
374                    break;
375                }
376            }
377            if ok && !line[..dash].is_empty() {
378                let mut hi = 0usize;
379                let mut i = dash + 1;
380                while i < line.len() {
381                    let c = line[i];
382                    if c.is_ascii_digit() {
383                        hi = hi * 16 + (c - b'0') as usize;
384                    } else if (b'a'..=b'f').contains(&c) {
385                        hi = hi * 16 + (c - b'a' + 10) as usize;
386                    } else {
387                        break;
388                    }
389                    i += 1;
390                }
391                if i > dash + 1 && lo <= addr && addr < hi {
392                    result = Some((lo, hi - lo));
393                }
394            }
395        }
396        line_start = line_end + 1;
397    }
398    result
399}
400
401#[no_mangle]
402pub unsafe extern "C" fn pthread_getattr_np(thread: PthreadT, attr: *mut pthread_attr_t) -> c_int {
403    if attr.is_null() || thread == 0 { return EINVAL; }
404    let slot = thread as *mut Thread;
405    core::ptr::write_bytes(attr, 0, 1);
406    let mut stack_base = (*slot).stack as usize;
407    let mut stack_size = if (*slot).stack_size > 0 { (*slot).stack_size } else { PTHREAD_DEFAULT_STACK };
408    if stack_base == 0 {
409        // Main thread: the loader allocated its stack, so ask the kernel which
410        // mapping holds the current stack pointer. Returning 0 here makes
411        // runtimes such as V8 conclude they are running on a foreign stack.
412        let sp: usize;
413        #[cfg(target_arch = "x86_64")]
414        core::arch::asm!("mov {}, rsp", out(reg) sp, options(nomem, nostack));
415        #[cfg(target_arch = "aarch64")]
416        core::arch::asm!("mov {}, sp", out(reg) sp, options(nomem, nostack));
417        #[cfg(target_arch = "riscv64")]
418        core::arch::asm!("mv {}, sp", out(reg) sp, options(nomem, nostack));
419        if let Some((base, size)) = mapping_containing(sp) {
420            stack_base = base;
421            stack_size = size;
422        } else {
423            stack_base = sp & !0xfff;
424            stack_size = 4096;
425        }
426    }
427    *((*attr).__i.as_mut_ptr() as *mut usize) = stack_size;
428    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = PTHREAD_DEFAULT_GUARD;
429    *((*attr).__i.as_mut_ptr().add(4) as *mut *mut c_void) =
430        (stack_base + stack_size) as *mut c_void;
431    (*attr).__i[6] = if (*slot).detach_state == DT_DETACHED { 1 } else { 0 };
432    (*attr).__i[7] = 0;
433    0
434}
435
436#[no_mangle]
437pub unsafe extern "C" fn pthread_getattr_default_np(attr: *mut pthread_attr_t) -> c_int {
438    if attr.is_null() { return EINVAL; }
439    core::ptr::write_bytes(attr, 0, 1);
440    *((*attr).__i.as_mut_ptr() as *mut usize) = PTHREAD_DEFAULT_STACK;
441    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = PTHREAD_DEFAULT_GUARD;
442    (*attr).__i[6] = 0;
443    (*attr).__i[7] = 1;
444    0
445}
446
447#[no_mangle]
448pub unsafe extern "C" fn pthread_setattr_default_np(attr: *const pthread_attr_t) -> c_int {
449    if attr.is_null() { return EINVAL; }
450    let stack = *((*attr).__i.as_ptr() as *const usize);
451    let guard = *((*attr).__i.as_ptr().add(2) as *const usize);
452    // Reject attributes that cannot be made defaults.
453    if (*attr).__i[6] != 0 { return EINVAL; }
454    if stack > 0 {
455        if stack < 16384 { return EINVAL; }
456        PTHREAD_DEFAULT_STACK = stack;
457    }
458    if guard > 0 { PTHREAD_DEFAULT_GUARD = guard; }
459    0
460}
461
462#[no_mangle]
463pub unsafe extern "C" fn pthread_getconcurrency() -> c_int {
464    PTHREAD_CONCURRENCY
465}
466
467#[no_mangle]
468pub unsafe extern "C" fn pthread_setconcurrency(level: c_int) -> c_int {
469    if level < 0 { return EINVAL; }
470    PTHREAD_CONCURRENCY = level;
471    0
472}
473
474#[no_mangle]
475pub unsafe extern "C" fn pthread_getcpuclockid(thread: PthreadT, clockid: *mut i32) -> c_int {
476    if thread == 0 || clockid.is_null() { return EINVAL; }
477    let slot = thread as *mut Thread;
478    let tid = (*slot).tid as i64;
479    *clockid = (((-tid - 1) * 8 + 6) & 0xffffffff) as i32;
480    0
481}
482
483#[no_mangle]
484pub unsafe extern "C" fn pthread_setname_np(thread: PthreadT, name: *const c_char) -> c_int {
485    if thread == 0 || name.is_null() { return EINVAL; }
486    if crate::strnlen(name as *const u8, 16) > 15 { return 34; }
487    let slot = thread as *mut Thread;
488    if slot == pthread_self() as *mut Thread {
489        return if crate::prctl(15, name as c_long) < 0 { ERRNO!() } else { 0 };
490    }
491    let mut path = [0 as c_char; 48];
492    let mut o = 0usize;
493    for &c in b"/proc/self/task/" { path[o] = c as c_char; o += 1; }
494    let mut tid = (*slot).tid as u32;
495    let mut digits = [0u8; 10];
496    let mut d = 0usize;
497    if tid == 0 { digits[0] = b'0'; d = 1; }
498    while tid > 0 { digits[d] = b'0' + (tid % 10) as u8; tid /= 10; d += 1; }
499    while d > 0 { d -= 1; path[o] = digits[d] as c_char; o += 1; }
500    for &c in b"/comm\0" { path[o] = c as c_char; o += 1; }
501    let fd = crate::open(path.as_ptr(), 1, 0);
502    if fd < 0 { return ERRNO!(); }
503    let n = crate::strlen(name);
504    let w = crate::write(fd, name as *const c_void, n);
505    crate::close(fd);
506    if w < 0 { ERRNO!() } else { 0 }
507}
508
509#[no_mangle]
510pub unsafe extern "C" fn pthread_getname_np(thread: PthreadT, name: *mut c_char, len: usize) -> c_int {
511    if thread == 0 || name.is_null() { return EINVAL; }
512    if len < 16 { return 34; }
513    let slot = thread as *mut Thread;
514    if slot == pthread_self() as *mut Thread {
515        return if crate::prctl(16, name as c_long) < 0 { ERRNO!() } else { 0 };
516    }
517    let mut path = [0 as c_char; 48];
518    let mut o = 0usize;
519    for &c in b"/proc/self/task/" { path[o] = c as c_char; o += 1; }
520    let mut tid = (*slot).tid as u32;
521    let mut digits = [0u8; 10];
522    let mut d = 0usize;
523    if tid == 0 { digits[0] = b'0'; d = 1; }
524    while tid > 0 { digits[d] = b'0' + (tid % 10) as u8; tid /= 10; d += 1; }
525    while d > 0 { d -= 1; path[o] = digits[d] as c_char; o += 1; }
526    for &c in b"/comm\0" { path[o] = c as c_char; o += 1; }
527    let fd = crate::open(path.as_ptr(), 0, 0);
528    if fd < 0 { return ERRNO!(); }
529    let n = crate::read(fd, name as *mut c_void, len);
530    crate::close(fd);
531    if n < 0 { return ERRNO!(); }
532    let mut l = n as usize;
533    if l > 0 && *name.add(l - 1) == b'\n' as c_char { l -= 1; }
534    *name.add(l) = 0;
535    0
536}
537
538#[no_mangle]
539pub unsafe extern "C" fn pthread_getschedparam(thread: PthreadT, policy: *mut c_int, param: *mut sched_param) -> c_int {
540    if thread == 0 || policy.is_null() || param.is_null() { return EINVAL; }
541    let tid = (*(thread as *mut Thread)).tid;
542    *policy = crate::sched_getscheduler(tid);
543    crate::sched_getparam(tid, param as *mut c_void)
544}
545
546#[no_mangle]
547pub unsafe extern "C" fn pthread_setschedparam(thread: PthreadT, policy: c_int, param: *const sched_param) -> c_int {
548    if thread == 0 || param.is_null() { return EINVAL; }
549    let tid = (*(thread as *mut Thread)).tid;
550    crate::sched_setscheduler(tid, policy, param as *const c_void)
551}
552
553#[no_mangle]
554pub unsafe extern "C" fn pthread_setschedprio(thread: PthreadT, prio: c_int) -> c_int {
555    if thread == 0 { return EINVAL; }
556    let tid = (*(thread as *mut Thread)).tid;
557    let p = sched_param { sched_priority: prio };
558    crate::sched_setparam(tid, &p as *const sched_param as *const c_void)
559}
560
561#[no_mangle]
562pub unsafe extern "C" fn pthread_mutex_getprioceiling(mutex: *const pthread_mutex_t, ceiling: *mut c_int) -> c_int {
563    if mutex.is_null() || ceiling.is_null() { return EINVAL; }
564    *ceiling = 0;
565    0
566}
567
568#[no_mangle]
569pub unsafe extern "C" fn pthread_mutex_setprioceiling(mutex: *mut pthread_mutex_t, ceiling: c_int, old: *mut c_int) -> c_int {
570    if mutex.is_null() { return EINVAL; }
571    if !old.is_null() { *old = 0; }
572    let _ = ceiling;
573    0
574}
575
576// ============================================================
577// posix_spawn attributes and file actions
578// ============================================================
579
580
581#[repr(C)]
582pub struct posix_spawn_file_actions_t {
583    __pad0: [c_int; 2],
584    __actions: *mut c_void,
585    __pad: [c_int; 16],
586}
587
588#[repr(C)]
589#[derive(Copy, Clone)]
590pub struct posix_spawnattr_t {
591    __flags: c_int,
592    __pgrp: c_int,
593    __def: [c_ulong; 16],
594    __mask: [c_ulong; 16],
595    __prio: c_int,
596    __pol: c_int,
597    __fn: *mut c_void,
598    __pad: [u8; 64 - core::mem::size_of::<*mut c_void>()],
599}
600
601#[repr(C)]
602struct SpawnAction {
603    next: *mut SpawnAction,
604    kind: c_int,
605    fd: c_int,
606    newfd: c_int,
607    oflag: c_int,
608    mode: u32,
609    path: *mut c_char,
610    path_owned: bool,
611}
612
613static mut SPAWN_DEFAULT_ATTR: posix_spawnattr_t = posix_spawnattr_t {
614    __flags: 0,
615    __pgrp: 0,
616    __def: [0; 16],
617    __mask: [0; 16],
618    __prio: 0,
619    __pol: 0,
620    __fn: core::ptr::null_mut(),
621    __pad: [0; 64 - core::mem::size_of::<*mut c_void>()],
622};
623
624unsafe fn spawn_actions(fa: *const posix_spawn_file_actions_t) -> *mut SpawnAction {
625    (*fa).__actions as *mut SpawnAction
626}
627
628unsafe fn spawn_action_add(
629    fa: *mut posix_spawn_file_actions_t,
630    kind: c_int,
631    fd: c_int,
632    newfd: c_int,
633    oflag: c_int,
634    mode: u32,
635    path: *const c_char,
636) -> c_int {
637    let node = crate::calloc(1, core::mem::size_of::<SpawnAction>()) as *mut SpawnAction;
638    if node.is_null() { return ENOMEM; }
639    (*node).kind = kind;
640    (*node).fd = fd;
641    (*node).newfd = newfd;
642    (*node).oflag = oflag;
643    (*node).mode = mode;
644    (*node).next = core::ptr::null_mut();
645    if !path.is_null() {
646        let n = crate::strlen(path);
647        let p = crate::malloc(n + 1) as *mut c_char;
648        if p.is_null() { crate::free(node as *mut c_void); return ENOMEM; }
649        core::ptr::copy_nonoverlapping(path, p, n + 1);
650        (*node).path = p;
651        (*node).path_owned = true;
652    }
653    if (*fa).__actions.is_null() {
654        (*fa).__actions = node as *mut c_void;
655    } else {
656        let mut tail = (*fa).__actions as *mut SpawnAction;
657        while !(*tail).next.is_null() { tail = (*tail).next; }
658        (*tail).next = node;
659    }
660    0
661}
662
663#[no_mangle]
664pub unsafe extern "C" fn posix_spawn_file_actions_init(fa: *mut posix_spawn_file_actions_t) -> c_int {
665    if fa.is_null() { return EINVAL; }
666    core::ptr::write_bytes(fa, 0, 1);
667    0
668}
669
670#[no_mangle]
671pub unsafe extern "C" fn posix_spawn_file_actions_destroy(fa: *mut posix_spawn_file_actions_t) -> c_int {
672    if fa.is_null() { return EINVAL; }
673    let mut p = spawn_actions(fa);
674    while !p.is_null() {
675        let next = (*p).next;
676        if (*p).path_owned && !(*p).path.is_null() { crate::free((*p).path as *mut c_void); }
677        crate::free(p as *mut c_void);
678        p = next;
679    }
680    (*fa).__actions = core::ptr::null_mut();
681    0
682}
683
684#[no_mangle]
685pub unsafe extern "C" fn posix_spawn_file_actions_addclose(fa: *mut posix_spawn_file_actions_t, fd: c_int) -> c_int {
686    if fa.is_null() || fd < 0 { return EINVAL; }
687    spawn_action_add(fa, 0, fd, 0, 0, 0, core::ptr::null())
688}
689
690#[no_mangle]
691pub unsafe extern "C" fn posix_spawn_file_actions_adddup2(fa: *mut posix_spawn_file_actions_t, fd: c_int, newfd: c_int) -> c_int {
692    if fa.is_null() || fd < 0 || newfd < 0 { return EINVAL; }
693    spawn_action_add(fa, 1, fd, newfd, 0, 0, core::ptr::null())
694}
695
696#[no_mangle]
697pub unsafe extern "C" fn posix_spawn_file_actions_addopen(
698    fa: *mut posix_spawn_file_actions_t,
699    fd: c_int,
700    path: *const c_char,
701    oflag: c_int,
702    mode: u32,
703) -> c_int {
704    if fa.is_null() || fd < 0 || path.is_null() { return EINVAL; }
705    spawn_action_add(fa, 2, fd, 0, oflag, mode, path)
706}
707
708#[no_mangle]
709pub unsafe extern "C" fn posix_spawn_file_actions_addchdir_np(fa: *mut posix_spawn_file_actions_t, path: *const c_char) -> c_int {
710    if fa.is_null() || path.is_null() { return EINVAL; }
711    spawn_action_add(fa, 3, 0, 0, 0, 0, path)
712}
713
714#[no_mangle]
715pub unsafe extern "C" fn posix_spawn_file_actions_addfchdir_np(fa: *mut posix_spawn_file_actions_t, fd: c_int) -> c_int {
716    if fa.is_null() || fd < 0 { return EINVAL; }
717    spawn_action_add(fa, 4, fd, 0, 0, 0, core::ptr::null())
718}
719
720unsafe fn spawn_apply_actions(fa: *const posix_spawn_file_actions_t) {
721    if fa.is_null() { return; }
722    let mut p = spawn_actions(fa);
723    while !p.is_null() {
724        match (*p).kind {
725            0 => { crate::close((*p).fd); }
726            1 => { crate::dup2((*p).fd, (*p).newfd); }
727            2 => {
728                let fd = crate::open((*p).path, (*p).oflag, (*p).mode as c_int);
729                if fd >= 0 && fd != (*p).fd {
730                    crate::dup2(fd, (*p).fd);
731                    crate::close(fd);
732                }
733            }
734            3 => { crate::chdir((*p).path); }
735            4 => { crate::fchdir((*p).fd); }
736            _ => {}
737        }
738        p = (*p).next;
739    }
740}
741
742unsafe fn spawn_apply_attr(attr: *const posix_spawnattr_t) {
743    if attr.is_null() { return; }
744    let flags = (*attr).__flags;
745    if flags & 1 != 0 {
746        if crate::geteuid() == 0 {
747            crate::setgid(crate::getgid());
748            crate::setuid(crate::getuid());
749        }
750    }
751    if flags & 2 != 0 { crate::setpgid(0, (*attr).__pgrp); }
752    if flags & 4 != 0 {
753        for sig in 1..65 {
754            let idx = (sig - 1) / 64;
755            let bit = (sig - 1) % 64;
756            if idx < 16 && ((*attr).__def[idx] >> bit) & 1 != 0 {
757                crate::signal(sig as c_int, 0);
758            }
759        }
760    }
761    if flags & 8 != 0 {
762        crate::sigprocmask(2, (*attr).__mask.as_ptr() as *const SigSetT, core::ptr::null_mut());
763    }
764    if flags & 16 != 0 {
765        let p = sched_param { sched_priority: (*attr).__prio };
766        crate::sched_setparam(0, &p as *const sched_param as *const c_void);
767    }
768    if flags & 32 != 0 {
769        let p = sched_param { sched_priority: (*attr).__prio };
770        crate::sched_setscheduler(0, (*attr).__pol, &p as *const sched_param as *const c_void);
771    }
772}
773
774#[no_mangle]
775pub unsafe extern "C" fn posix_spawnattr_init(attr: *mut posix_spawnattr_t) -> c_int {
776    if attr.is_null() { return EINVAL; }
777    *attr = SPAWN_DEFAULT_ATTR;
778    0
779}
780
781#[no_mangle]
782pub unsafe extern "C" fn posix_spawnattr_destroy(attr: *mut posix_spawnattr_t) -> c_int {
783    if attr.is_null() { return EINVAL; }
784    0
785}
786
787#[no_mangle]
788pub unsafe extern "C" fn posix_spawnattr_getflags(attr: *const posix_spawnattr_t, flags: *mut i16) -> c_int {
789    if attr.is_null() || flags.is_null() { return EINVAL; }
790    *flags = (*attr).__flags as i16;
791    0
792}
793
794#[no_mangle]
795pub unsafe extern "C" fn posix_spawnattr_setflags(attr: *mut posix_spawnattr_t, flags: i16) -> c_int {
796    if attr.is_null() { return EINVAL; }
797    if (flags as c_int) & !0x7f != 0 { return EINVAL; }
798    (*attr).__flags = flags as c_int;
799    0
800}
801
802#[no_mangle]
803pub unsafe extern "C" fn posix_spawnattr_getpgroup(attr: *const posix_spawnattr_t, pgroup: *mut c_int) -> c_int {
804    if attr.is_null() || pgroup.is_null() { return EINVAL; }
805    *pgroup = (*attr).__pgrp;
806    0
807}
808
809#[no_mangle]
810pub unsafe extern "C" fn posix_spawnattr_setpgroup(attr: *mut posix_spawnattr_t, pgroup: c_int) -> c_int {
811    if attr.is_null() { return EINVAL; }
812    (*attr).__pgrp = pgroup;
813    0
814}
815
816#[no_mangle]
817pub unsafe extern "C" fn posix_spawnattr_getschedparam(attr: *const posix_spawnattr_t, param: *mut sched_param) -> c_int {
818    if attr.is_null() || param.is_null() { return EINVAL; }
819    (*param).sched_priority = (*attr).__prio;
820    0
821}
822
823#[no_mangle]
824pub unsafe extern "C" fn posix_spawnattr_setschedparam(attr: *mut posix_spawnattr_t, param: *const sched_param) -> c_int {
825    if attr.is_null() || param.is_null() { return EINVAL; }
826    (*attr).__prio = (*param).sched_priority;
827    0
828}
829
830#[no_mangle]
831pub unsafe extern "C" fn posix_spawnattr_getschedpolicy(attr: *const posix_spawnattr_t, policy: *mut c_int) -> c_int {
832    if attr.is_null() || policy.is_null() { return EINVAL; }
833    *policy = (*attr).__pol;
834    0
835}
836
837#[no_mangle]
838pub unsafe extern "C" fn posix_spawnattr_setschedpolicy(attr: *mut posix_spawnattr_t, policy: c_int) -> c_int {
839    if attr.is_null() { return EINVAL; }
840    (*attr).__pol = policy;
841    0
842}
843
844#[no_mangle]
845pub unsafe extern "C" fn posix_spawnattr_getsigdefault(attr: *const posix_spawnattr_t, set: *mut SigSetT) -> c_int {
846    if attr.is_null() || set.is_null() { return EINVAL; }
847    *set = (*attr).__def[0];
848    0
849}
850
851#[no_mangle]
852pub unsafe extern "C" fn posix_spawnattr_setsigdefault(attr: *mut posix_spawnattr_t, set: *const SigSetT) -> c_int {
853    if attr.is_null() || set.is_null() { return EINVAL; }
854    (*attr).__def = [0; 16];
855    (*attr).__def[0] = *set;
856    0
857}
858
859#[no_mangle]
860pub unsafe extern "C" fn posix_spawnattr_getsigmask(attr: *const posix_spawnattr_t, set: *mut SigSetT) -> c_int {
861    if attr.is_null() || set.is_null() { return EINVAL; }
862    *set = (*attr).__mask[0];
863    0
864}
865
866#[no_mangle]
867pub unsafe extern "C" fn posix_spawnattr_setsigmask(attr: *mut posix_spawnattr_t, set: *const SigSetT) -> c_int {
868    if attr.is_null() || set.is_null() { return EINVAL; }
869    (*attr).__mask = [0; 16];
870    (*attr).__mask[0] = *set;
871    0
872}
873
874// ============================================================
875// stdio internals
876// ============================================================
877
878#[no_mangle]
879pub unsafe extern "C" fn __fbufsize(f: *mut FILE) -> usize {
880    if f.is_null() { return 0; }
881    (*f).buf_size
882}
883
884#[no_mangle]
885pub unsafe extern "C" fn __flbf(f: *mut FILE) -> c_int {
886    if f.is_null() { return 0; }
887    if (*f).lbf >= 0 { 1 } else { 0 }
888}
889
890#[no_mangle]
891pub unsafe extern "C" fn __fpending(f: *mut FILE) -> usize {
892    if f.is_null() || (*f).wend.is_null() { return 0; }
893    (*f).wpos as usize - (*f).wbase as usize
894}
895
896#[no_mangle]
897pub unsafe extern "C" fn __fpurge(f: *mut FILE) {
898    if f.is_null() { return; }
899    (*f).wpos = core::ptr::null_mut();
900    (*f).wbase = core::ptr::null_mut();
901    (*f).wend = core::ptr::null_mut();
902    (*f).rpos = core::ptr::null_mut();
903    (*f).rend = core::ptr::null_mut();
904}
905
906#[no_mangle]
907pub unsafe extern "C" fn __freadable(f: *mut FILE) -> c_int {
908    if f.is_null() { return 0; }
909    if (*f).flags & F_NORD == 0 { 1 } else { 0 }
910}
911
912#[no_mangle]
913pub unsafe extern "C" fn __freadahead(f: *mut FILE) -> usize {
914    if f.is_null() || (*f).rend.is_null() { return 0; }
915    (*f).rend as usize - (*f).rpos as usize
916}
917
918#[no_mangle]
919pub unsafe extern "C" fn __freading(f: *mut FILE) -> c_int {
920    if f.is_null() { return 0; }
921    if (*f).flags & F_NOWR != 0 || !(*f).rend.is_null() { 1 } else { 0 }
922}
923
924#[no_mangle]
925pub unsafe extern "C" fn __freadptr(f: *mut FILE, sizep: *mut usize) -> *const c_char {
926    if f.is_null() || sizep.is_null() { return core::ptr::null(); }
927    if (*f).rpos == (*f).rend { *sizep = 0; return core::ptr::null(); }
928    *sizep = (*f).rend as usize - (*f).rpos as usize;
929    (*f).rpos as *const c_char
930}
931
932#[no_mangle]
933pub unsafe extern "C" fn __freadptrinc(f: *mut FILE, inc: usize) {
934    if f.is_null() || (*f).rpos.is_null() { return; }
935    let left = (*f).rend as usize - (*f).rpos as usize;
936    let step = if inc > left { left } else { inc };
937    (*f).rpos = (*f).rpos.add(step);
938}
939
940#[no_mangle]
941pub unsafe extern "C" fn __fsetlocking(_f: *mut FILE, _type: c_int) -> c_int {
942    1
943}
944
945#[no_mangle]
946pub unsafe extern "C" fn __fwritable(f: *mut FILE) -> c_int {
947    if f.is_null() { return 0; }
948    if (*f).flags & F_NOWR == 0 { 1 } else { 0 }
949}
950
951#[no_mangle]
952pub unsafe extern "C" fn __fwriting(f: *mut FILE) -> c_int {
953    if f.is_null() { return 0; }
954    if (*f).flags & F_NORD != 0 || !(*f).wend.is_null() { 1 } else { 0 }
955}
956
957#[no_mangle]
958pub unsafe extern "C" fn __fseterr(f: *mut FILE) {
959    if !f.is_null() { (*f).flags |= F_ERR; }
960}
961
962#[no_mangle]
963pub unsafe extern "C" fn __fputwc_unlocked(c: wchar_t, f: *mut FILE) -> wint_t {
964    crate::fputwc(c, f)
965}
966
967// ============================================================
968// Miscellaneous legacy calls
969// ============================================================
970
971#[no_mangle]
972pub unsafe extern "C" fn sigqueue(pid: c_int, sig: c_int, value: *mut c_void) -> c_int {
973    let mut si = [0u8; 128];
974    *(si.as_mut_ptr() as *mut c_int) = sig;
975    *(si.as_mut_ptr().add(8) as *mut c_int) = -1; // SI_QUEUE
976    *(si.as_mut_ptr().add(16) as *mut c_int) = crate::getpid();
977    *(si.as_mut_ptr().add(20) as *mut u32) = crate::getuid();
978    *(si.as_mut_ptr().add(24) as *mut *mut c_void) = value;
979    let r = <Arch as Syscalls>::syscall3(SYS_RT_SIGQUEUEINFO, pid as i64, sig as i64, si.as_ptr() as i64);
980    if r < 0 { ERRNO!() = (-r) as c_int; -1 } else { 0 }
981}
982
983#[no_mangle]
984pub unsafe extern "C" fn timespec_get(ts: *mut timespec, base: c_int) -> c_int {
985    if base != 1 || ts.is_null() { return 0; }
986    if crate::clock_gettime(0, ts) != 0 { return 0; }
987    base
988}
989
990#[no_mangle]
991pub unsafe extern "C" fn ualarm(usecs: u32, interval: u32) -> u32 {
992    #[repr(C)]
993    struct ITV {
994        sec: i64,
995        usec: i64,
996    }
997    let mut new: [ITV; 2] = [
998        ITV { sec: (interval / 1_000_000) as i64, usec: (interval % 1_000_000) as i64 },
999        ITV { sec: (usecs / 1_000_000) as i64, usec: (usecs % 1_000_000) as i64 },
1000    ];
1001    let mut old: [ITV; 2] = [ITV { sec: 0, usec: 0 }, ITV { sec: 0, usec: 0 }];
1002    if crate::setitimer(0, new.as_mut_ptr() as *const c_void, old.as_mut_ptr() as *mut c_void) != 0 {
1003        return u32::MAX;
1004    }
1005    (old[0].sec as u32) * 1_000_000 + old[0].usec as u32
1006}
1007
1008static mut LCKPWDF_FD: c_int = -1;
1009
1010#[repr(C)]
1011#[derive(Copy, Clone)]
1012struct FlockT {
1013    l_type: i16,
1014    l_whence: i16,
1015    l_start: i64,
1016    l_len: i64,
1017    l_pid: i32,
1018    __pad: i32,
1019}
1020
1021#[no_mangle]
1022pub unsafe extern "C" fn lckpwdf() -> c_int {
1023    if LCKPWDF_FD >= 0 { return 0; }
1024    let fd = crate::open(
1025        b"/etc/.pwd.lock\0".as_ptr() as *const c_char,
1026        1 | 0x40 | 0x80000,
1027        0o600,
1028    );
1029    if fd < 0 { return -1; }
1030    let fl = FlockT { l_type: 1, l_whence: 0, l_start: 0, l_len: 0, l_pid: 0, __pad: 0 };
1031    if crate::fcntl(fd, 7, &fl as *const FlockT as *mut c_void) != 0 {
1032        crate::close(fd);
1033        return -1;
1034    }
1035    LCKPWDF_FD = fd;
1036    0
1037}
1038
1039#[no_mangle]
1040pub unsafe extern "C" fn ulckpwdf() -> c_int {
1041    if LCKPWDF_FD < 0 { return -1; }
1042    let fd = LCKPWDF_FD;
1043    LCKPWDF_FD = -1;
1044    crate::close(fd);
1045    0
1046}
1047
1048#[no_mangle]
1049pub unsafe extern "C" fn malloc_usable_size(ptr: *mut u8) -> usize {
1050    crate::alloc_usable_size(ptr)
1051}
1052
1053#[no_mangle]
1054pub unsafe extern "C" fn __wcsftime_l(
1055    s: *mut wchar_t,
1056    max: usize,
1057    fmt: *const wchar_t,
1058    tm: *const c_void,
1059    _loc: locale_t,
1060) -> usize {
1061    crate::wcsftime(s as *mut u32, max, fmt as *const u32, tm)
1062}
1063
1064#[no_mangle]
1065pub unsafe extern "C" fn __wctype_l(name: *const c_char, _loc: locale_t) -> wctype_t {
1066    crate::wctype(name)
1067}
1068
1069#[no_mangle]
1070pub unsafe extern "C" fn __wctrans_l(name: *const c_char, _loc: locale_t) -> wctrans_t {
1071    crate::wctrans(name)
1072}
1073
1074#[no_mangle]
1075pub unsafe extern "C" fn __fgetwc_unlocked(f: *mut FILE) -> wint_t {
1076    crate::fgetwc(f)
1077}
1078
1079#[no_mangle]
1080pub unsafe extern "C" fn _flushlbf() {
1081    crate::fflush(core::ptr::null_mut());
1082}