Skip to content

Commit

Permalink
Fix fputs to detect errors properly. (#100)
Browse files Browse the repository at this point in the history
In particular, this fixes writing `""`, when no bytes are written
and it's not an error.
  • Loading branch information
sunfishcode authored Dec 20, 2023
1 parent 4782df5 commit 8e440b6
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion c-scape/src/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ unsafe extern "C" fn fputs(s: *const c_char, file: *mut libc::FILE) -> c_int {
//libc!(libc::fputs(s, file));

let len = libc::strlen(s);
if fwrite(s.cast(), 1, len, file) == 0 {
if fwrite(s.cast(), 1, len, file) != len {
libc::EOF
} else {
0
Expand Down Expand Up @@ -970,3 +970,31 @@ unsafe extern "C" fn perror(user_message: *const c_char) {
);
}
}

#[test]
fn test_fputs() {
use core::ptr::null_mut;
use rustix::cstr;
unsafe {
let mut buf = [0u8; 8];
let fd = libc::memfd_create(cstr!("test").as_ptr(), 0);
assert_ne!(fd, -1);
let file = fdopen(fd, cstr!("w").as_ptr());
assert_ne!(file, null_mut());

assert!(fputs(cstr!("").as_ptr(), file) >= 0);
assert!(fflush(file) == 0);
assert_eq!(libc::pread(fd, buf.as_mut_ptr().cast(), buf.len(), 0), 0);
assert_eq!(buf, [0u8; 8]);

assert!(fputs(cstr!("hi").as_ptr(), file) >= 0);
assert!(fflush(file) == 0);
assert_eq!(libc::pread(fd, buf.as_mut_ptr().cast(), buf.len(), 0), 2);
assert_eq!(&buf, b"hi\0\0\0\0\0\0");

assert!(fputs(cstr!("hello\n").as_ptr(), file) >= 0);
assert!(fflush(file) == 0);
assert_eq!(libc::pread(fd, buf.as_mut_ptr().cast(), buf.len(), 2), 6);
assert_eq!(&buf, b"hello\n\0\0");
}
}

0 comments on commit 8e440b6

Please sign in to comment.