Skip to main content

stdbuf/
libstdbuf.rs

1// This file is part of the uutils coreutils package.
2//
3// For the full copyright and license information, please view the LICENSE
4// file that was distributed with this source code.
5
6// spell-checker:ignore (ToDO) getreent reent IOFBF IOLBF IONBF setvbuf stderrp stdinp stdoutp fdopen
7
8use core::ffi::{c_char, c_int};
9use ctor::ctor;
10use libc::{_IOFBF, _IOLBF, _IONBF, FILE, fileno, size_t};
11use std::io::{Write, stderr};
12use std::{env, ptr};
13
14// This runs automatically when the library is loaded via LD_PRELOAD
15#[ctor(unsafe)]
16fn init() {
17    unsafe { __stdbuf() };
18}
19
20/// # Safety
21/// This function is unsafe because it calls a C API
22#[unsafe(no_mangle)]
23pub unsafe extern "C" fn __stdbuf_get_stdin() -> *mut FILE {
24    #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
25    {
26        unsafe extern "C" {
27            static mut __stdinp: *mut FILE;
28        }
29        unsafe { __stdinp }
30    }
31
32    #[cfg(target_os = "openbsd")]
33    {
34        unsafe extern "C" {
35            static mut __stdin: *mut FILE;
36        }
37        unsafe { __stdin }
38    }
39
40    #[cfg(target_os = "netbsd")]
41    {
42        unsafe { libc::fdopen(0, c"r".as_ptr()) }
43    }
44
45    #[cfg(target_os = "cygwin")]
46    {
47        // _getreent()->_std{in,out,err}
48        // see:
49        // echo '#include <stdio.h>\nstd{in,out,err}' | gcc -E -xc - -std=c23 | tail -n1
50        // echo '#include <stdio.h>' | grep -E -xc - -std=c23 | grep 'struct _reent' -A91 | grep 580 -A91 | tail -n+2
51
52        #[repr(C)]
53        struct _reent {
54            _errno: c_int,
55            _stdin: *mut FILE,
56            _stdout: *mut FILE,
57            _stderr: *mut FILE,
58            // other stuff
59        }
60
61        unsafe extern "C" {
62            fn __getreent() -> *mut _reent;
63        }
64
65        unsafe { (*__getreent())._stdin }
66    }
67
68    #[cfg(not(any(
69        target_vendor = "apple",
70        target_os = "freebsd",
71        target_os = "netbsd",
72        target_os = "openbsd",
73        target_os = "cygwin"
74    )))]
75    {
76        unsafe extern "C" {
77            static mut stdin: *mut FILE;
78        }
79        unsafe { stdin }
80    }
81}
82
83/// # Safety
84/// This function is unsafe because it calls a C API
85#[unsafe(no_mangle)]
86pub unsafe extern "C" fn __stdbuf_get_stdout() -> *mut FILE {
87    #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
88    {
89        unsafe extern "C" {
90            static mut __stdoutp: *mut FILE;
91        }
92        unsafe { __stdoutp }
93    }
94
95    #[cfg(target_os = "openbsd")]
96    {
97        unsafe extern "C" {
98            static mut __stdout: *mut FILE;
99        }
100        unsafe { __stdout }
101    }
102
103    #[cfg(target_os = "netbsd")]
104    {
105        unsafe { libc::fdopen(1, c"w".as_ptr()) }
106    }
107
108    #[cfg(target_os = "cygwin")]
109    {
110        // _getreent()->_std{in,out,err}
111        // see:
112        // echo '#include <stdio.h>\nstd{in,out,err}' | gcc -E -xc - -std=c23 | tail -n1
113        // echo '#include <stdio.h>' | grep -E -xc - -std=c23 | grep 'struct _reent' -A91 | grep 580 -A91 | tail -n+2
114
115        #[repr(C)]
116        struct _reent {
117            _errno: c_int,
118            _stdin: *mut FILE,
119            _stdout: *mut FILE,
120            _stderr: *mut FILE,
121            // other stuff
122        }
123
124        unsafe extern "C" {
125            fn __getreent() -> *mut _reent;
126        }
127
128        unsafe { (*__getreent())._stdout }
129    }
130
131    #[cfg(not(any(
132        target_vendor = "apple",
133        target_os = "freebsd",
134        target_os = "netbsd",
135        target_os = "openbsd",
136        target_os = "cygwin"
137    )))]
138    {
139        unsafe extern "C" {
140            static mut stdout: *mut FILE;
141        }
142        unsafe { stdout }
143    }
144}
145
146/// # Safety
147/// This function is unsafe because it calls a C API
148#[unsafe(no_mangle)]
149pub unsafe extern "C" fn __stdbuf_get_stderr() -> *mut FILE {
150    #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
151    {
152        unsafe extern "C" {
153            static mut __stderrp: *mut FILE;
154        }
155        unsafe { __stderrp }
156    }
157
158    #[cfg(target_os = "openbsd")]
159    {
160        unsafe extern "C" {
161            static mut __stderr: *mut FILE;
162        }
163        unsafe { __stderr }
164    }
165
166    #[cfg(target_os = "netbsd")]
167    {
168        unsafe { libc::fdopen(2, c"w".as_ptr()) }
169    }
170
171    #[cfg(target_os = "cygwin")]
172    {
173        // _getreent()->_std{in,out,err}
174        // see:
175        // echo '#include <stdio.h>\nstd{in,out,err}' | gcc -E -xc - -std=c23 | tail -n1
176        // echo '#include <stdio.h>' | grep -E -xc - -std=c23 | grep 'struct _reent' -A91 | grep 580 -A91 | tail -n+2
177
178        #[repr(C)]
179        struct _reent {
180            _errno: c_int,
181            _stdin: *mut FILE,
182            _stdout: *mut FILE,
183            _stderr: *mut FILE,
184            // other stuff
185        }
186
187        unsafe extern "C" {
188            fn __getreent() -> *mut _reent;
189        }
190
191        unsafe { (*__getreent())._stderr }
192    }
193
194    #[cfg(not(any(
195        target_vendor = "apple",
196        target_os = "freebsd",
197        target_os = "netbsd",
198        target_os = "openbsd",
199        target_os = "cygwin"
200    )))]
201    {
202        unsafe extern "C" {
203            static mut stderr: *mut FILE;
204        }
205        unsafe { stderr }
206    }
207}
208
209fn set_buffer(stream: *mut FILE, value: &str) {
210    let (mode, size): (c_int, size_t) = match value {
211        "0" => (_IONBF, 0_usize),
212        "L" => (_IOLBF, 0_usize),
213        input => {
214            let Ok(buff_size) = input.parse::<usize>() else {
215                let _ = writeln!(stderr(), "failed to allocate a {value} byte stdio buffer");
216                std::process::exit(1);
217            };
218            (_IOFBF, buff_size as size_t)
219        }
220    };
221    let res: c_int;
222    unsafe {
223        let buffer: *mut c_char = ptr::null_mut();
224        assert!(buffer.is_null());
225        res = libc::setvbuf(stream, buffer, mode, size);
226    }
227    if res != 0 {
228        let _ = writeln!(
229            stderr(),
230            "could not set buffering of {} to mode {mode}",
231            unsafe { fileno(stream) }
232        );
233    }
234}
235
236/// # Safety
237/// This function is intended to be called automatically when the library is loaded via `LD_PRELOAD`.
238/// It assumes that the standard streams are valid and that calling setvbuf on them is safe.
239/// The caller must ensure this function is only called in a compatible runtime environment.
240#[unsafe(no_mangle)]
241pub unsafe extern "C" fn __stdbuf() {
242    if let Ok(val) = env::var("_STDBUF_E") {
243        set_buffer(unsafe { __stdbuf_get_stderr() }, &val);
244    }
245    if let Ok(val) = env::var("_STDBUF_I") {
246        set_buffer(unsafe { __stdbuf_get_stdin() }, &val);
247    }
248    if let Ok(val) = env::var("_STDBUF_O") {
249        set_buffer(unsafe { __stdbuf_get_stdout() }, &val);
250    }
251}
252
253#[cfg(all(test, unix))]
254mod tests {
255    use super::*;
256
257    // Each getter must return its own stream, not another one.
258    #[test]
259    fn test_stream_getters_return_matching_streams() {
260        unsafe {
261            assert_eq!(fileno(__stdbuf_get_stdin()), libc::STDIN_FILENO);
262            assert_eq!(fileno(__stdbuf_get_stdout()), libc::STDOUT_FILENO);
263            assert_eq!(fileno(__stdbuf_get_stderr()), libc::STDERR_FILENO);
264        }
265    }
266}