From f9250ca8493ef8c98dade8d9dcc769f3e34307bb Mon Sep 17 00:00:00 2001 From: Shac Ron Date: Tue, 16 May 2023 16:30:02 -0700 Subject: [PATCH] Don't assert on attempting to write a file opened RO When lfs_file_write() is called on a file opened as read-only, it soon encounters an assertion in lfs_file_rawwrite() that is unhappy with this state. Instead of aborting, return an error and allow the client to handle it properly. This matches the behavior of write(2), which sets errno to EBADF in this case. --- lfs.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lfs.c b/lfs.c index d2f3b5e9..9cf48189 100644 --- a/lfs.c +++ b/lfs.c @@ -5863,7 +5863,12 @@ lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file, (void*)lfs, (void*)file, buffer, size); LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file)); - lfs_ssize_t res = lfs_file_rawwrite(lfs, file, buffer, size); + lfs_ssize_t res; + if ((file->flags & LFS_O_WRONLY) == 0) { + res = LFS_ERR_BADF; + } else { + res = lfs_file_rawwrite(lfs, file, buffer, size); + } LFS_TRACE("lfs_file_write -> %"PRId32, res); LFS_UNLOCK(lfs->cfg);