Skip to content

Commit

Permalink
bsd-user: Handle short reads in mmap_h_gt_g
Browse files Browse the repository at this point in the history
In particular, if an image has a large bss, we can hit EOF before reading
all bytes of the mapping.  Mirror the similar change to linux-user.

Signed-off-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-Id: <[email protected]>
  • Loading branch information
rth7680 committed Aug 20, 2024
1 parent a4ad4a9 commit 5b73b24
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions bsd-user/mmap.c
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,40 @@ int target_mprotect(abi_ulong start, abi_ulong len, int prot)
return ret;
}

/*
* Perform a pread on behalf of target_mmap. We can reach EOF, we can be
* interrupted by signals, and in general there's no good error return path.
* If @zero, zero the rest of the block at EOF.
* Return true on success.
*/
static bool mmap_pread(int fd, void *p, size_t len, off_t offset, bool zero)
{
while (1) {
ssize_t r = pread(fd, p, len, offset);

if (likely(r == len)) {
/* Complete */
return true;
}
if (r == 0) {
/* EOF */
if (zero) {
memset(p, 0, len);
}
return true;
}
if (r > 0) {
/* Short read */
p += r;
len -= r;
offset += r;
} else if (errno != EINTR) {
/* Error */
return false;
}
}
}

/*
* map an incomplete host page
*
Expand Down Expand Up @@ -190,7 +224,7 @@ static int mmap_frag(abi_ulong real_start,
mprotect(host_start, qemu_host_page_size, prot1 | PROT_WRITE);

/* read the corresponding file data */
if (pread(fd, g2h_untagged(start), end - start, offset) == -1) {
if (!mmap_pread(fd, g2h_untagged(start), end - start, offset, true)) {
return -1;
}

Expand Down Expand Up @@ -565,7 +599,7 @@ abi_long target_mmap(abi_ulong start, abi_ulong len, int prot,
-1, 0);
if (retaddr == -1)
goto fail;
if (pread(fd, g2h_untagged(start), len, offset) == -1) {
if (!mmap_pread(fd, g2h_untagged(start), len, offset, false)) {
goto fail;
}
if (!(prot & PROT_WRITE)) {
Expand Down

0 comments on commit 5b73b24

Please sign in to comment.