Skip to content

Commit

Permalink
tools: kwboot: Replace fstat()+st_size by lseek()+SEEK_END
Browse files Browse the repository at this point in the history
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 <[email protected]>
Reviewed-by: Marek Behún <[email protected]>
  • Loading branch information
pali authored and stroese committed Apr 21, 2022
1 parent 8b3d7ec commit a339d6c
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions tools/kwboot.c
Original file line number Diff line number Diff line change
Expand Up @@ -1591,8 +1591,8 @@ static void *
kwboot_read_image(const char *path, size_t *size, size_t reserve)
{
int rc, fd;
struct stat st;
void *img;
off_t len;
off_t tot;

rc = -1;
Expand All @@ -1602,31 +1602,34 @@ kwboot_read_image(const char *path, size_t *size, size_t reserve)
if (fd < 0)
goto out;

rc = fstat(fd, &st);
if (rc)
len = lseek(fd, 0, SEEK_END);
if (len == (off_t)-1)
goto out;

if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
goto out;

img = malloc(st.st_size + reserve);
img = malloc(len + reserve);
if (!img)
goto out;

tot = 0;
while (tot < st.st_size) {
ssize_t rd = read(fd, img + tot, st.st_size - tot);
while (tot < len) {
ssize_t rd = read(fd, img + tot, len - tot);

if (rd < 0)
goto out;

tot += rd;

if (!rd && tot < st.st_size) {
if (!rd && tot < len) {
errno = EIO;
goto out;
}
}

rc = 0;
*size = st.st_size;
*size = len;
out:
if (rc && img) {
free(img);
Expand Down

0 comments on commit a339d6c

Please sign in to comment.