Skip to content

Commit

Permalink
Merge pull request #5160 from yagehu/yagehu/append-seek
Browse files Browse the repository at this point in the history
Fix fd with append flag can't seek correctly
  • Loading branch information
syrusakbary authored Oct 22, 2024
2 parents 8e5f50f + 2e7ec56 commit b94206b
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 5 deletions.
3 changes: 0 additions & 3 deletions lib/wasix/src/syscalls/wasi/fd_seek.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,6 @@ pub(crate) fn fd_seek_internal(
if !fd_entry.rights.contains(Rights::FD_SEEK) {
return Ok(Err(Errno::Access));
}
if fd_entry.flags.contains(Fdflags::APPEND) {
return Ok(Ok(fd_entry.offset.load(Ordering::Acquire)));
}

// TODO: handle case if fd is a dir?
let new_offset = match whence {
Expand Down
7 changes: 7 additions & 0 deletions lib/wasix/src/syscalls/wasi/fd_write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ pub(crate) fn fd_write_internal<M: MemorySize>(
should_update_cursor: bool,
should_snapshot: bool,
) -> Result<Result<usize, Errno>, WasiError> {
let mut offset = offset;
let mut env = ctx.data();
let state = env.state.clone();

Expand Down Expand Up @@ -160,6 +161,12 @@ pub(crate) fn fd_write_internal<M: MemorySize>(
async {
let mut handle = handle.write().unwrap();
if !is_stdio {
if fd_entry.flags.contains(Fdflags::APPEND) {
// `fdflags::append` means we need to seek to the end before writing.
offset = handle.size();
fd_entry.offset.store(offset, Ordering::Release);
}

handle
.seek(std::io::SeekFrom::Start(offset))
.await
Expand Down
15 changes: 15 additions & 0 deletions tests/wasi-fyi/fd_seek_append.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use std::io::{Seek as _, SeekFrom};

fn main() {
let offset = 100u64;
let mut f = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open("/fyi/fs_seek_append.dir/file")
.unwrap();
let new_offset = f.seek(SeekFrom::Start(offset)).unwrap();

assert_eq!(offset, new_offset);
}
5 changes: 3 additions & 2 deletions tests/wasi-fyi/fs_seek_append_mode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ fn main() {
// file offset must be 1 now
write!(file, "{}", "a").unwrap();

// rewind should not work on file in append mode
// since the offset must always be at the end of the file
// rewind should not work on file in append mode.
// It changes the offset, which is immediately set to the end of the file
// with a write.
let _ = file.rewind();

// file offset must be 2 now
Expand Down
Empty file.

0 comments on commit b94206b

Please sign in to comment.