tools: kwboot: Replace fstat()+st_size by lseek()+SEEK_END

fstat()'s st_size works only for regular files. lseek() with SEEK_END works
also for block or MTD devices. This replacement allows kwboot to load
kwbimage from /dev/mtd0 for booting another device over /dev/ttyS0.

Signed-off-by: Pali Rohár <pali@kernel.org>
Reviewed-by: Marek Behún <marek.behun@nic.cz>
This commit is contained in:
Pali Rohár 2022-04-06 15:18:59 +02:00 committed by Stefan Roese
parent 8b3d7ecdfe
commit a339d6c464

View File

@ -1591,8 +1591,8 @@ static void *
kwboot_read_image(const char *path, size_t *size, size_t reserve) kwboot_read_image(const char *path, size_t *size, size_t reserve)
{ {
int rc, fd; int rc, fd;
struct stat st;
void *img; void *img;
off_t len;
off_t tot; off_t tot;
rc = -1; rc = -1;
@ -1602,31 +1602,34 @@ kwboot_read_image(const char *path, size_t *size, size_t reserve)
if (fd < 0) if (fd < 0)
goto out; goto out;
rc = fstat(fd, &st); len = lseek(fd, 0, SEEK_END);
if (rc) if (len == (off_t)-1)
goto out; goto out;
img = malloc(st.st_size + reserve); if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
goto out;
img = malloc(len + reserve);
if (!img) if (!img)
goto out; goto out;
tot = 0; tot = 0;
while (tot < st.st_size) { while (tot < len) {
ssize_t rd = read(fd, img + tot, st.st_size - tot); ssize_t rd = read(fd, img + tot, len - tot);
if (rd < 0) if (rd < 0)
goto out; goto out;
tot += rd; tot += rd;
if (!rd && tot < st.st_size) { if (!rd && tot < len) {
errno = EIO; errno = EIO;
goto out; goto out;
} }
} }
rc = 0; rc = 0;
*size = st.st_size; *size = len;
out: out:
if (rc && img) { if (rc && img) {
free(img); free(img);