Fix the return value from wasi-common's fd_readdir.

`fd_readdir` returns a "bufused" value, which indicates the number of
bytes read into the buffer. WASI libc expects this value to be equal
to the size of the buffer if the end of the directory has not yet
been scanned.

Previously, wasi-common's `fd_readdir` was writing as many complete
entries as it could fit and then stopping, but this meant it was
returning size less than the buffer size even when the directory had
more entries. This patch makes it continue writing up until the end
of the buffer, and return that number of bytes, to let WASI libc
know that there's more to be read.

Fixes #2493.
This commit is contained in:
Dan Gohman
2020-12-09 16:49:59 -08:00
parent 9ccef597c2
commit c3f0471ff2
2 changed files with 91 additions and 15 deletions

View File

@@ -7,6 +7,7 @@ use crate::{path, sched, Error, Result, WasiCtx};
use std::convert::TryInto;
use std::io::{self, SeekFrom};
use std::ops::Deref;
use std::cmp::min;
use tracing::{debug, trace};
use wiggle::{GuestPtr, GuestSliceMut};
@@ -304,15 +305,32 @@ impl<'a> WasiSnapshotPreview1 for WasiCtx {
let name_raw = name.as_bytes();
let name_len = name_raw.len().try_into()?;
let offset = dirent_len.checked_add(name_len).ok_or(Error::Overflow)?;
if (buf_len - bufused) < offset {
break;
} else {
buf.as_array(dirent_len).copy_from_slice(&dirent_raw)?;
buf = buf.add(dirent_len)?;
buf.as_array(name_len).copy_from_slice(name_raw)?;
buf = buf.add(name_len)?;
bufused += offset;
// Copy as many bytes of the dirent as we can, up to the end of the buffer.
let dirent_copy_len = min(dirent_len, buf_len - bufused);
buf.as_array(dirent_copy_len).copy_from_slice(&dirent_raw[..dirent_copy_len as usize])?;
// If the dirent struct wasn't copied entirely, return that we
// filled the buffer, which tells libc that we're not at EOF.
if dirent_copy_len < dirent_len {
return Ok(buf_len);
}
buf = buf.add(dirent_copy_len)?;
// Copy as many bytes of the name as we can, up to the end of the buffer.
let name_copy_len = min(name_len, buf_len - bufused);
buf.as_array(name_copy_len).copy_from_slice(&name_raw[..name_copy_len as usize])?;
// If the dirent struct wasn't copied entirely, return that we
// filled the buffer, which tells libc that we're not at EOF.
if name_copy_len < name_len {
return Ok(buf_len);
}
buf = buf.add(name_copy_len)?;
bufused += offset;
}
Ok(bufused)