From aeeb6e23c34adcbe13ed4be8902620368eee0b56 Mon Sep 17 00:00:00 2001 From: Kuan-Wei Chiu Date: Fri, 22 Dec 2023 20:13:46 +0800 Subject: [PATCH 1/2] Fix syscall_write error handling The current implementation of syscall_write lacks proper error handling, potentially returning 0 even when an error occurs. This fix introduces a check for fwrite errors and updates the return value to -1 in case of an error. --- src/syscall.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/syscall.c b/src/syscall.c index b59cfe08..e15ec255 100644 --- a/src/syscall.c +++ b/src/syscall.c @@ -96,8 +96,10 @@ static void syscall_write(riscv_t *rv) memory_read(s->mem, tmp, buffer + total_write, PREALLOC_SIZE); if (!map_at_end(s->fd_map, &it)) { /* write out the data */ - size_t written = - fwrite(tmp, 1, PREALLOC_SIZE, map_iter_value(&it, FILE *)); + FILE *handle = map_iter_value(&it, FILE *); + size_t written = fwrite(tmp, 1, PREALLOC_SIZE, handle); + if (written != PREALLOC_SIZE && ferror(handle)) + goto error_handler; total_write += written; count -= PREALLOC_SIZE; } else @@ -106,7 +108,10 @@ static void syscall_write(riscv_t *rv) memory_read(s->mem, tmp, buffer + total_write, count); if (!map_at_end(s->fd_map, &it)) { /* write out the data */ - size_t written = fwrite(tmp, 1, count, map_iter_value(&it, FILE *)); + FILE *handle = map_iter_value(&it, FILE *); + size_t written = fwrite(tmp, 1, count, handle); + if (written != count && ferror(handle)) + goto error_handler; total_write += written; } else goto error_handler; From 331e7c4f67dd482aa21f0b9a5c48d9efdb5c3bcb Mon Sep 17 00:00:00 2001 From: Kuan-Wei Chiu Date: Fri, 22 Dec 2023 20:18:45 +0800 Subject: [PATCH 2/2] Fix syscall_close error handling The current implementation of syscall_close lacks proper error handling, potentially returning 0 even when an error occurs. This fix introduces a check for fclose errors and updates the return value to -1 in case of an error. --- src/syscall.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/syscall.c b/src/syscall.c index e15ec255..1714fe7e 100644 --- a/src/syscall.c +++ b/src/syscall.c @@ -216,7 +216,11 @@ static void syscall_close(riscv_t *rv) map_iter_t it; map_find(s->fd_map, &it, &fd); if (!map_at_end(s->fd_map, &it)) { - fclose(map_iter_value(&it, FILE *)); + if (fclose(map_iter_value(&it, FILE *))) { + /* error */ + rv_set_reg(rv, rv_reg_a0, -1); + return; + } map_erase(s->fd_map, &it); /* success */