Skip to main content

c/
stdio.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// FILE / stdio (buffered, musl-compatible layout)
6// ============================================================
7
8const UNGET: usize = 8;
9const F_PERM: u32 = 1;
10const F_NORD: u32 = 4;
11const F_NOWR: u32 = 8;
12const F_EOF: u32 = 16;
13const F_ERR: u32 = 32;
14const F_SVB: u32 = 64;
15const F_APP: u32 = 128;
16
17const BUFSIZ: usize = 1024;
18
19const _IOFBF: c_int = 0;
20const _IOLBF: c_int = 1;
21const _IONBF: c_int = 2;
22
23const SEEK_SET: c_int = 0;
24const SEEK_CUR: c_int = 1;
25const SEEK_END: c_int = 2;
26
27// Buffered FILE using musl's 64-bit layout.
28#[repr(C)]
29pub struct FILE {
30    flags: c_uint,
31    rpos: *mut u8,
32    rend: *mut u8,
33    close: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
34    wend: *mut u8,
35    wpos: *mut u8,
36    mustbezero_1: *mut u8,
37    wbase: *mut u8,
38    read_fn: Option<unsafe extern "C" fn(*mut FILE, *mut u8, usize) -> usize>,
39    write_fn: Option<unsafe extern "C" fn(*mut FILE, *const u8, usize) -> usize>,
40    seek_fn: Option<unsafe extern "C" fn(*mut FILE, i64, c_int) -> i64>,
41    buf: *mut u8,
42    buf_size: usize,
43    prev: *mut FILE,
44    next: *mut FILE,
45    fd: c_int,
46    pipe_pid: c_int,
47    lockcount: c_long,
48    mode: c_int,
49    lock: c_int,
50    lbf: c_int,
51    cookie: *mut c_void,
52    off: i64,
53    getln_buf: *mut c_char,
54    mustbezero_2: *mut c_void,
55    shend: *mut u8,
56    shlim: i64,
57    shcnt: i64,
58    ungotten: [c_int; UNGET],
59    ungotten_count: c_int,
60    _eof: c_int,
61    _err: c_int,
62}
63
64static mut STDIN_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
65static mut STDOUT_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
66static mut STDERR_BUF: [u8; BUFSIZ] = [0; BUFSIZ];
67
68static mut STDIN_FILE: FILE = FILE {
69    flags: 0, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
70    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
71    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
72    read_fn: None, write_fn: None, seek_fn: None,
73    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
74    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
75    fd: 0, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
76    cookie: core::ptr::null_mut(), off: 0,
77    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
78    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
79    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
80};
81static mut STDOUT_FILE: FILE = FILE {
82    flags: F_NOWR as u32 + F_SVB as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
83    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
84    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
85    read_fn: None, write_fn: None, seek_fn: None,
86    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
87    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
88    fd: 1, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
89    cookie: core::ptr::null_mut(), off: 0,
90    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
91    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
92    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
93};
94static mut STDERR_FILE: FILE = FILE {
95    flags: F_NOWR as u32, rpos: core::ptr::null_mut(), rend: core::ptr::null_mut(),
96    close: None, wend: core::ptr::null_mut(), wpos: core::ptr::null_mut(),
97    mustbezero_1: core::ptr::null_mut(), wbase: core::ptr::null_mut(),
98    read_fn: None, write_fn: None, seek_fn: None,
99    buf: core::ptr::null_mut(), buf_size: BUFSIZ,
100    prev: core::ptr::null_mut(), next: core::ptr::null_mut(),
101    fd: 2, pipe_pid: 0, lockcount: 0, mode: 0, lock: 0, lbf: -1,
102    cookie: core::ptr::null_mut(), off: 0,
103    getln_buf: core::ptr::null_mut(), mustbezero_2: core::ptr::null_mut(),
104    shend: core::ptr::null_mut(), shlim: 0, shcnt: 0,
105    ungotten: [0; UNGET], ungotten_count: 0, _eof: 0, _err: 0,
106};
107
108#[no_mangle]
109pub static mut stdin: *mut FILE = &raw mut STDIN_FILE as *mut FILE;
110#[no_mangle]
111pub static mut stdout: *mut FILE = &raw mut STDOUT_FILE as *mut FILE;
112#[no_mangle]
113pub static mut stderr: *mut FILE = &raw mut STDERR_FILE as *mut FILE;
114
115// All open streams, so fflush(NULL) can flush everything and fclose can
116// unlink/free dynamically allocated FILEs.
117static mut OFL_HEAD: *mut FILE = core::ptr::null_mut();
118
119unsafe fn ofl_add(f: *mut FILE) {
120    (*f).prev = core::ptr::null_mut();
121    (*f).next = OFL_HEAD;
122    if !OFL_HEAD.is_null() {
123        (*OFL_HEAD).prev = f;
124    }
125    OFL_HEAD = f;
126}
127
128unsafe fn ofl_remove(f: *mut FILE) {
129    let prev = (*f).prev;
130    let next = (*f).next;
131    if prev.is_null() {
132        OFL_HEAD = next;
133    } else {
134        (*prev).next = next;
135    }
136    if !next.is_null() {
137        (*next).prev = prev;
138    }
139    (*f).prev = core::ptr::null_mut();
140    (*f).next = core::ptr::null_mut();
141}
142
143// ============================================================
144// FILE helpers
145// ============================================================
146
147unsafe fn __stdio_init() {
148    STDIN_FILE.buf = core::ptr::addr_of_mut!(STDIN_BUF) as *mut u8;
149    STDIN_FILE.buf_size = BUFSIZ;
150    STDIN_FILE.read_fn = Some(__stdio_read);
151    STDIN_FILE.write_fn = Some(__stdio_write);
152    STDIN_FILE.seek_fn = Some(__stdio_seek);
153    STDOUT_FILE.buf = core::ptr::addr_of_mut!(STDOUT_BUF) as *mut u8;
154    STDOUT_FILE.buf_size = BUFSIZ;
155    STDOUT_FILE.lbf = b'\n' as c_int;
156    STDOUT_FILE.read_fn = Some(__stdio_read);
157    STDOUT_FILE.write_fn = Some(__stdio_write);
158    STDOUT_FILE.seek_fn = Some(__stdio_seek);
159    STDERR_FILE.buf = core::ptr::addr_of_mut!(STDERR_BUF) as *mut u8;
160    STDERR_FILE.buf_size = BUFSIZ;
161    STDERR_FILE.read_fn = Some(__stdio_read);
162    STDERR_FILE.write_fn = Some(__stdio_write);
163    STDERR_FILE.seek_fn = Some(__stdio_seek);
164    STDIN_FILE.flags |= F_PERM;
165    STDOUT_FILE.flags |= F_PERM;
166    STDERR_FILE.flags |= F_PERM;
167    STDIN_FILE.close = Some(__stdio_close);
168    STDOUT_FILE.close = Some(__stdio_close);
169    STDERR_FILE.close = Some(__stdio_close);
170    ofl_add(&raw mut STDIN_FILE as *mut FILE);
171    ofl_add(&raw mut STDOUT_FILE as *mut FILE);
172    ofl_add(&raw mut STDERR_FILE as *mut FILE);
173}
174
175unsafe fn buf_ptr(f: *mut FILE) -> *mut u8 {
176    (f as *mut u8).add(core::mem::size_of::<FILE>())
177}
178
179unsafe extern "C" fn __stdio_read(f: *mut FILE, buf: *mut u8, len: usize) -> usize {
180    let n = sys_read((*f).fd as i64, buf, len);
181    if n <= 0 {
182        if n == 0 { (*f).flags |= F_EOF; } else { (*f).flags |= F_ERR; (*f)._err = 1; }
183        return 0;
184    }
185    n as usize
186}
187
188unsafe extern "C" fn __stdio_write(f: *mut FILE, buf: *const u8, len: usize) -> usize {
189    let l = (*f).wpos as usize - (*f).wbase as usize;
190    let mut iov = [
191        ((*f).wbase as *const u8, l),
192        (buf, len),
193    ];
194    if iov[0].1 == 0 { iov = [iov[1], (core::ptr::null(), 0)]; }
195    if (*f).flags & F_APP != 0 {
196        let _ = sys_lseek((*f).fd as i64, 0, SEEK_END as i64);
197    }
198    let mut rem = iov[0].1 + iov[1].1;
199    let mut idx = 0usize;
200    while rem > 0 {
201        let ptr = iov[idx].0;
202        let cnt = iov[idx].1;
203        if cnt == 0 { idx += 1; continue; }
204        let n = sys_write((*f).fd as i64, ptr, cnt);
205        if n <= 0 {
206            (*f).wpos = core::ptr::null_mut();
207            (*f).wbase = core::ptr::null_mut();
208            (*f).wend = core::ptr::null_mut();
209            (*f).flags |= F_ERR;
210            return if iov[idx].0 == buf { 0 } else { len };
211        }
212        rem -= n as usize;
213        iov[idx].0 = iov[idx].0.add(n as usize);
214        iov[idx].1 -= n as usize;
215        if iov[idx].1 == 0 { idx += 1; }
216    }
217    (*f).wend = (*f).buf.add((*f).buf_size);
218    (*f).wbase = (*f).buf;
219    (*f).wpos = (*f).buf;
220    len
221}
222
223unsafe extern "C" fn __stdio_seek(f: *mut FILE, off: i64, whence: c_int) -> i64 {
224    sys_lseek((*f).fd as i64, off, whence as i64)
225}
226
227unsafe fn init_file(
228    f: *mut FILE,
229    fd: c_int,
230    mode: *const c_char,
231    close_fn: Option<unsafe extern "C" fn(*mut FILE) -> c_int>,
232    buf_area: *mut u8,
233    buf_sz: usize,
234) {
235    core::ptr::write_bytes(f as *mut u8, 0, core::mem::size_of::<FILE>());
236    (*f).fd = fd;
237    (*f).close = close_fn;
238    (*f).lock = 0;
239    (*f).lbf = -1;
240    (*f).buf = buf_area;
241    (*f).buf_size = buf_sz;
242    (*f).read_fn = Some(__stdio_read);
243    (*f).write_fn = Some(__stdio_write);
244    (*f).seek_fn = Some(__stdio_seek);
245    let m = *mode;
246    let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
247    if m == b'r' as c_char && !has_plus {
248        (*f).flags = F_NORD;
249    } else if !has_plus {
250        (*f).flags = F_NOWR;
251    }
252    ofl_add(f);
253}
254
255unsafe extern "C" fn __stdio_close(f: *mut FILE) -> c_int {
256    sys_close((*f).fd as i64);
257    0
258}
259
260unsafe fn fmodeflags(mode: *const c_char) -> c_int {
261    let mut flags: c_int;
262    let m = *mode;
263    if !strchr(mode as *const u8, b'+' as c_int).is_null() {
264        flags = O_RDWR;
265    } else if m == b'r' as c_char {
266        flags = O_RDONLY;
267    } else {
268        flags = O_WRONLY;
269    }
270    if !strchr(mode as *const u8, b'x' as c_int).is_null() { flags |= O_EXCL; }
271    if !strchr(mode as *const u8, b'e' as c_int).is_null() { flags |= O_CLOEXEC; }
272    if m != b'r' as c_char { flags |= O_CREAT; }
273    if m == b'w' as c_char { flags |= O_TRUNC; }
274    if m == b'a' as c_char { flags |= O_APPEND; }
275    flags
276}
277
278const O_ACCMODE: c_int = O_RDONLY | O_WRONLY | O_RDWR;
279
280unsafe fn flush_buf(f: *mut FILE) -> c_int {
281    if (*f).wpos == (*f).wbase {
282        if !(*f).wpos.is_null() {
283            (*f).wend = (*f).buf.add((*f).buf_size);
284            (*f).wpos = (*f).wbase;
285        }
286        return 0;
287    }
288    if let Some(wfunc) = (*f).write_fn {
289        let ret = wfunc(f, core::ptr::null(), 0);
290        if ret == 0 && (*f).wpos.is_null() { return -1; }
291        return 0;
292    }
293    (*f).flags |= F_ERR;
294    -1
295}
296
297// ============================================================
298// fopen / fdopen / freopen / fclose
299// ============================================================
300
301#[no_mangle]
302pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE {
303    if filename.is_null() || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
304    let m = *mode;
305    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
306        ERRNO!() = EINVAL; return core::ptr::null_mut();
307    }
308    let flags = fmodeflags(mode);
309    let fd = sys_open(filename as *const u8, flags as i64, 0o666);
310    if fd < 0 { ERRNO!() = (-fd) as c_int; return core::ptr::null_mut(); }
311    let f = fdopen(fd as c_int, mode);
312    if f.is_null() {
313        sys_close(fd);
314    }
315    f
316}
317
318#[no_mangle]
319pub unsafe extern "C" fn fdopen(fd: c_int, mode: *const c_char) -> *mut FILE {
320    if fd < 0 || mode.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
321    let m = *mode;
322    if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
323        ERRNO!() = EINVAL; return core::ptr::null_mut();
324    }
325    let f = calloc(1, core::mem::size_of::<FILE>() + UNGET + BUFSIZ) as *mut FILE;
326    if f.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
327    let buf = buf_ptr(f);
328    init_file(f, fd, mode, Some(__stdio_close), buf, BUFSIZ);
329    if !strchr(mode as *const u8, b'a' as c_int).is_null() { (*f).flags |= F_APP; }
330    if !strchr(mode as *const u8, b'e' as c_int).is_null() { sys_fcntl(fd, F_SETFD, FD_CLOEXEC as i64); }
331    if (*f).flags & F_NOWR == 0 {
332        let mut ws: winsize = core::mem::zeroed();
333        if sys_ioctl(fd, TIOCGWINSZ, &mut ws as *mut winsize as *mut u8) == 0 {
334            (*f).lbf = b'\n' as c_int;
335        }
336    }
337    f
338}
339
340#[no_mangle]
341pub unsafe extern "C" fn freopen(
342    filename: *const c_char, mode: *const c_char, f: *mut FILE,
343) -> *mut FILE {
344    fflush(f);
345    if (*f).pipe_pid > 0 { let _ = __stdio_close(f); }
346    if filename.is_null() {
347        let m = *mode;
348        if m != b'r' as c_char && m != b'w' as c_char && m != b'a' as c_char {
349            ERRNO!() = EINVAL;
350            return core::ptr::null_mut();
351        }
352        let flags = fmodeflags(mode);
353        let mut fl = flags & !(O_CREAT | O_EXCL | O_CLOEXEC);
354        if (*f).flags & F_APP != 0 { fl = (fl & !O_ACCMODE) | O_WRONLY | O_APPEND; }
355        if sys_fcntl((*f).fd, F_SETFL, fl as i64) < 0 { return core::ptr::null_mut(); }
356        let has_plus = !strchr(mode as *const u8, b'+' as c_int).is_null();
357        if has_plus {
358            (*f).flags &= !(F_NORD | F_NOWR);
359        } else if *mode == b'r' as c_char {
360            (*f).flags = ((*f).flags & !F_NOWR) | F_NORD;
361        } else {
362            (*f).flags = ((*f).flags & !F_NORD) | F_NOWR;
363        }
364        return f;
365    }
366    let new_f = fopen(filename, mode);
367    if new_f.is_null() { let _ = __stdio_close(f); return core::ptr::null_mut(); }
368    if (*new_f).fd == (*f).fd {
369        (*new_f).fd = -1;
370    } else {
371        sys_dup3((*new_f).fd, (*f).fd, 0);
372        let _ = __stdio_close(new_f);
373    }
374    (*f).flags = (*new_f).flags;
375    (*f).rpos = core::ptr::null_mut();
376    (*f).rend = core::ptr::null_mut();
377    (*f).wpos = core::ptr::null_mut();
378    (*f).wbase = core::ptr::null_mut();
379    (*f).wend = core::ptr::null_mut();
380    (*f).lbf = (*new_f).lbf;
381    (*f).pipe_pid = 0;
382    ofl_remove(new_f);
383    free(new_f as *mut c_void);
384    f
385}
386
387#[no_mangle]
388pub unsafe extern "C" fn fclose(f: *mut FILE) -> c_int {
389    if f.is_null() {
390        ERRNO!() = EINVAL;
391        return -1;
392    }
393    let r = fflush(f);
394    let close_r = if let Some(close_fn) = (*f).close { close_fn(f) } else { 0 };
395    let permanent = (*f).flags & F_PERM != 0;
396    let allocated_buf = if (*f).flags & F_SVB != 0 { (*f).buf } else { core::ptr::null_mut() };
397    let getln = (*f).getln_buf;
398    ofl_remove(f);
399    if !permanent {
400        if !allocated_buf.is_null() { free(allocated_buf as *mut c_void); }
401        if !getln.is_null() { free(getln as *mut c_void); }
402        free(f as *mut c_void);
403    }
404    if r != 0 || close_r != 0 { -1 } else { 0 }
405}
406
407// ============================================================
408// setvbuf / setbuf / setbuffer / fflush
409// ============================================================
410
411#[no_mangle]
412pub unsafe extern "C" fn setvbuf(f: *mut FILE, buf: *mut c_char, mode: c_int, size: usize) -> c_int {
413    if f.is_null() || (mode != _IOFBF && mode != _IOLBF && mode != _IONBF) {
414        ERRNO!() = EINVAL;
415        return -1;
416    }
417    fflush(f);
418    (*f).rpos = core::ptr::null_mut();
419    (*f).rend = core::ptr::null_mut();
420    (*f).wpos = core::ptr::null_mut();
421    (*f).wbase = core::ptr::null_mut();
422    (*f).wend = core::ptr::null_mut();
423    if mode == _IONBF {
424        (*f).buf = core::ptr::null_mut();
425        (*f).buf_size = 0;
426    } else {
427        let wanted = if size == 0 { BUFSIZ } else { size };
428        let actual = if buf.is_null() {
429            let p = malloc(wanted) as *mut c_char;
430            if p.is_null() {
431                ERRNO!() = ENOMEM;
432                return -1;
433            }
434            (*f).flags |= F_SVB;
435            p
436        } else {
437            (*f).flags &= !F_SVB;
438            buf
439        };
440        (*f).buf = actual as *mut u8;
441        (*f).buf_size = wanted;
442    }
443    (*f).lbf = if mode == _IOLBF { b'\n' as c_int } else { -1 };
444    0
445}
446
447#[no_mangle]
448pub unsafe extern "C" fn setbuf(f: *mut FILE, buf: *mut c_char) {
449    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
450    else { setvbuf(f, buf, _IOFBF, BUFSIZ); }
451}
452
453#[no_mangle]
454pub unsafe extern "C" fn setbuffer(f: *mut FILE, buf: *mut c_char, size: usize) {
455    if buf.is_null() { setvbuf(f, core::ptr::null_mut(), _IONBF, 0); }
456    else { setvbuf(f, buf, _IOFBF, size); }
457}
458
459#[no_mangle]
460pub unsafe extern "C" fn fflush(f: *mut FILE) -> c_int {
461    if f.is_null() {
462        let mut r = 0;
463        let mut cur = OFL_HEAD;
464        while !cur.is_null() {
465            let next = (*cur).next;
466            if !(*cur).wpos.is_null() && (*cur).wpos != (*cur).wbase {
467                if flush_buf(cur) != 0 { r = -1; }
468            }
469            cur = next;
470        }
471        return r;
472    }
473    if !(*f).wpos.is_null() && (*f).wpos != (*f).wbase {
474        return flush_buf(f);
475    }
476    0
477}
478
479// ============================================================
480// fwide / feof / ferror / clearerr / fileno
481// ============================================================
482
483#[no_mangle]
484pub unsafe extern "C" fn fwide(_f: *mut FILE, mode: c_int) -> c_int { mode }
485
486#[no_mangle]
487pub unsafe extern "C" fn feof(f: *mut FILE) -> c_int { if (*f)._eof != 0 { 1 } else { 0 } }
488
489#[no_mangle]
490pub unsafe extern "C" fn ferror(f: *mut FILE) -> c_int { if (*f)._err != 0 { 1 } else { 0 } }
491
492#[no_mangle]
493pub unsafe extern "C" fn clearerr(f: *mut FILE) { (*f)._eof = 0; (*f)._err = 0; }
494
495#[no_mangle]
496pub unsafe extern "C" fn fileno(f: *mut FILE) -> c_int { (*f).fd }
497
498// ============================================================
499// fseek / ftell / rewind / fseeko / ftello / fgetpos / fsetpos
500// ============================================================
501
502#[no_mangle]
503pub unsafe extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int {
504    fseeko(stream, offset as i64, whence)
505}
506
507#[no_mangle]
508pub unsafe extern "C" fn ftell(stream: *mut FILE) -> c_long {
509    ftello(stream) as c_long
510}
511
512#[no_mangle]
513pub unsafe extern "C" fn rewind(stream: *mut FILE) {
514    fseek(stream, 0, SEEK_SET);
515    (*stream)._eof = 0;
516    (*stream)._err = 0;
517}
518
519#[no_mangle]
520pub unsafe extern "C" fn fseeko(stream: *mut FILE, offset: i64, whence: c_int) -> c_int {
521    if whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END {
522        ERRNO!() = EINVAL;
523        return -1;
524    }
525    let f = &mut *stream;
526    let mut adj_offset = offset;
527    if whence == SEEK_CUR {
528        if !f.rpos.is_null() {
529            let buffered = f.rend as i64 - f.rpos as i64;
530            if adj_offset < i64::MIN + buffered {
531                ERRNO!() = EOVERFLOW;
532                return -1;
533            }
534            adj_offset -= buffered;
535        }
536        if adj_offset < i64::MIN + f.ungotten_count as i64 {
537            ERRNO!() = EOVERFLOW;
538            return -1;
539        }
540        adj_offset -= f.ungotten_count as i64;
541    }
542    if !f.wpos.is_null() && f.wpos != f.wbase {
543        if flush_buf(stream) != 0 { return -1; }
544    }
545    f.wpos = core::ptr::null_mut();
546    f.wbase = core::ptr::null_mut();
547    f.wend = core::ptr::null_mut();
548    if let Some(sfunc) = f.seek_fn {
549        let r = sfunc(stream, adj_offset, whence);
550        if r < 0 { return -1; }
551    } else {
552        ERRNO!() = EINVAL;
553        return -1;
554    }
555    f.rpos = core::ptr::null_mut();
556    f.rend = core::ptr::null_mut();
557    f._eof = 0;
558    f.ungotten_count = 0;
559    0
560}
561
562#[no_mangle]
563pub unsafe extern "C" fn ftello(stream: *mut FILE) -> i64 {
564    let f = &mut *stream;
565    if f.flags & F_APP != 0 && !f.wpos.is_null() && f.wpos != f.wbase {
566        if fflush(stream) != 0 { return -1; }
567    }
568    let sfunc = match f.seek_fn { Some(s) => s, None => return -1 };
569    let pos = sfunc(stream, 0,
570        if (f.flags & F_APP) != 0 && !f.wpos.is_null() && f.wpos != f.wbase { SEEK_END } else { SEEK_CUR });
571    if pos < 0 { return -1; }
572    let mut pos = pos;
573    if !f.rpos.is_null() {
574        pos += f.rpos as i64 - f.rend as i64;
575    } else if !f.wbase.is_null() {
576        let buffered = f.wpos as i64 - f.wbase as i64;
577        if buffered > i64::MAX - pos {
578            ERRNO!() = EOVERFLOW;
579            return -1;
580        }
581        pos += buffered;
582    }
583    pos - f.ungotten_count as i64
584}
585
586#[no_mangle]
587pub unsafe extern "C" fn fgetpos(stream: *mut FILE, pos: *mut i64) -> c_int {
588    let off = ftello(stream);
589    if off < 0 { return -1; }
590    *pos = off;
591    0
592}
593
594#[no_mangle]
595pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const i64) -> c_int {
596    fseeko(stream, *pos, SEEK_SET)
597}
598
599// ============================================================
600// fgetc / getc / getchar / ungetc
601// ============================================================
602
603#[no_mangle]
604pub unsafe extern "C" fn fgetc(stream: *mut FILE) -> c_int {
605    let f = &mut *stream;
606    if f.ungotten_count > 0 {
607        f.ungotten_count -= 1;
608        return f.ungotten[f.ungotten_count as usize];
609    }
610    if !f.rpos.is_null() && f.rpos < f.rend {
611        let c = *f.rpos;
612        f.rpos = f.rpos.add(1);
613        return c as c_int;
614    }
615    if f._eof != 0 { return -1; }
616    if let Some(rfunc) = f.read_fn {
617        // Fill the stdio buffer in one read. Reading one byte per syscall is
618        // not only slow, it is wrong for procfs files that only return their
619        // contents on the first read: a second one-byte read sees EOF.
620        if !f.buf.is_null() && f.buf_size > 1 {
621            let n = rfunc(stream, f.buf, f.buf_size);
622            if n == 0 {
623                if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
624                return -1;
625            }
626            f.rpos = f.buf;
627            f.rend = f.buf.add(n);
628            let c = *f.rpos;
629            f.rpos = f.rpos.add(1);
630            return c as c_int;
631        }
632        let mut buf = [0u8; 1];
633        let n = rfunc(stream, buf.as_mut_ptr(), 1);
634        if n == 0 {
635            if f.flags & F_ERR != 0 { f._err = 1; } else { f._eof = 1; }
636            return -1;
637        }
638        buf[0] as c_int
639    } else {
640        f._eof = 1;
641        -1
642    }
643}
644
645#[no_mangle]
646pub unsafe extern "C" fn getc(stream: *mut FILE) -> c_int { fgetc(stream) }
647
648#[no_mangle]
649pub unsafe extern "C" fn getchar() -> c_int { fgetc(stdin) }
650
651#[no_mangle]
652pub unsafe extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int {
653    if c == -1 { return -1; }
654    let f = &mut *stream;
655    if f.ungotten_count >= UNGET as c_int { return -1; }
656    f.ungotten[f.ungotten_count as usize] = c;
657    f.ungotten_count += 1;
658    f._eof = 0;
659    c
660}
661
662// ============================================================
663// fgets / fread
664// ============================================================
665
666unsafe fn fgets_common(s: *mut c_char, max: usize, stream: *mut FILE, keep_newline: bool) -> *mut c_char {
667    let mut i = 0usize;
668    while i < max {
669        let c = fgetc(stream);
670        if c == -1 {
671            if i == 0 { return null_mut(); }
672            break;
673        }
674        if c == b'\n' as c_int && !keep_newline { break; }
675        *s.add(i) = c as c_char;
676        i += 1;
677        if c == b'\n' as c_int { break; }
678    }
679    *s.add(i) = 0;
680    s
681}
682
683#[no_mangle]
684pub unsafe extern "C" fn fgets(s: *mut c_char, n: c_int, stream: *mut FILE) -> *mut c_char {
685    if n <= 0 { return null_mut(); }
686    fgets_common(s, (n - 1) as usize, stream, true)
687}
688
689// gets() was removed from C11 and POSIX.1-2008; it remains an unbounded
690// convenience wrapper for legacy callers.
691#[no_mangle]
692pub unsafe extern "C" fn gets(s: *mut c_char) -> *mut c_char {
693    fgets_common(s, usize::MAX, stdin, false)
694}
695
696#[no_mangle]
697pub unsafe extern "C" fn fopen64(filename: *const c_char, mode: *const c_char) -> *mut FILE {
698    fopen(filename, mode)
699}
700
701// perror(): minimal implementation printing "msg: errno\n".
702const PERROR_BUF_SIZE: usize = 64;
703static mut PERROR_BUF: [u8; PERROR_BUF_SIZE] = [0; PERROR_BUF_SIZE];
704
705#[no_mangle]
706pub unsafe extern "C" fn perror(msg: *const c_char) {
707    let fd = (*stderr).fd;
708    if !msg.is_null() && *msg != 0 {
709        let len = strlen(msg as *const c_char);
710        write_str(fd, msg as *const u8, len);
711        write_str(fd, b": ".as_ptr(), 2);
712    }
713    let e = ERRNO!();
714    let text = strerror(e) as *const u8;
715    write_str(fd, text, strlen(text as *const c_char));
716    write_str(fd, b"\n".as_ptr(), 1);
717}
718
719#[no_mangle]
720pub unsafe extern "C" fn fread(
721    ptr: *mut c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
722) -> SizeT {
723    if size == 0 || nmemb == 0 { return 0; }
724    let total = match size.checked_mul(nmemb) {
725        Some(v) => v,
726        None => { ERRNO!() = EINVAL; return 0; }
727    };
728    let mut rd = 0usize;
729    while rd < total {
730        let c = fgetc(stream);
731        if c == -1 { break; }
732        *(ptr as *mut u8).add(rd) = c as u8;
733        rd += 1;
734    }
735    rd / size
736}
737
738// ============================================================
739// puts / fputs / fputc / putc / putchar / fwrite
740// ============================================================
741
742unsafe fn write_str(fd: c_int, s: *const u8, len: usize) {
743    let mut written = 0usize;
744    while written < len {
745        let n = sys_write(fd as i64, s.add(written), len - written);
746        if n <= 0 { break; }
747        written += n as usize;
748    }
749}
750
751#[no_mangle]
752pub unsafe extern "C" fn __overflow(f: *mut FILE, c: c_int) -> c_int {
753    if (*f).wpos.is_null() {
754        (*f).wbase = (*f).buf;
755        (*f).wpos = (*f).buf;
756        (*f).wend = (*f).buf.add((*f).buf_size);
757    }
758    if flush_buf(f) == -1 { return -1; }
759    if (*f).wpos >= (*f).wend {
760        if let Some(wfunc) = (*f).write_fn {
761            let byte = c as u8;
762            let ret = wfunc(f, &byte as *const u8, 1);
763            if ret == 0 { return -1; }
764        }
765        return c;
766    }
767    *(*f).wpos = c as u8;
768    (*f).wpos = (*f).wpos.add(1);
769    if c == (*f).lbf || (*f).wpos >= (*f).wend { let _ = flush_buf(f); }
770    c
771}
772
773#[no_mangle]
774pub unsafe extern "C" fn puts(s: *const c_char) -> c_int {
775    let len = strlen(s as *const c_char);
776    let _ = fwrite(s as *const c_void, 1, len, stdout);
777    let _ = fwrite(b"\n".as_ptr() as *const c_void, 1, 1, stdout);
778    let f = &mut *stdout;
779    if f.lbf >= 0 { let _ = flush_buf(stdout); }
780    (len + 1) as c_int
781}
782
783#[no_mangle]
784pub unsafe extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int {
785    let len = strlen(s as *const c_char);
786    fwrite(s as *const c_void, 1, len, stream) as c_int
787}
788
789#[no_mangle]
790pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int {
791    let f = &mut *stream;
792    if f.wpos.is_null() || f.wpos >= f.wend {
793        if __overflow(f, c) == -1 { return -1; }
794        return c;
795    }
796    *f.wpos = c as u8;
797    f.wpos = f.wpos.add(1);
798    if c == f.lbf || f.wpos >= f.wend { let _ = flush_buf(f); }
799    c
800}
801
802#[no_mangle]
803pub unsafe extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int { fputc(c, stream) }
804
805#[no_mangle]
806pub unsafe extern "C" fn putchar(c: c_int) -> c_int { fputc(c, stdout) }
807
808#[no_mangle]
809pub unsafe extern "C" fn fwrite(
810    ptr: *const c_void, size: SizeT, nmemb: SizeT, stream: *mut FILE,
811) -> SizeT {
812    if size == 0 || nmemb == 0 { return 0; }
813    let total = match size.checked_mul(nmemb) {
814        Some(v) => v,
815        None => { ERRNO!() = EINVAL; return 0; }
816    };
817    let f = &mut *stream;
818    if f.buf_size == 0 {
819        if let Some(wfunc) = f.write_fn {
820            let ret = wfunc(stream, ptr as *const u8, total);
821            if ret < total { f._err = 1; f.flags |= F_ERR; }
822            return ret / size;
823        }
824        f._err = 1;
825        f.flags |= F_ERR;
826        return 0;
827    }
828    if f.wpos.is_null() {
829        f.wbase = f.buf;
830        f.wpos = f.buf;
831        f.wend = f.buf.add(f.buf_size);
832    }
833    let mut remaining = total;
834    let mut src = ptr as *const u8;
835    while remaining > 0 {
836        let space = f.wend as usize - f.wpos as usize;
837        if space == 0 {
838            if flush_buf(f as *mut FILE) == -1 { break; }
839            continue;
840        }
841        let n = if remaining < space { remaining } else { space };
842        core::ptr::copy_nonoverlapping(src, f.wpos, n);
843        f.wpos = f.wpos.add(n);
844        src = src.add(n);
845        remaining -= n;
846        if f.wpos >= f.wend { let _ = flush_buf(f as *mut FILE); }
847    }
848    if f.lbf >= 0 { let _ = flush_buf(f as *mut FILE); }
849    (total - remaining) / size
850}
851