From 328c1706cf959d0d1188b77191677d8705007e85 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Sat, 24 May 2025 23:45:28 -0500 Subject: [PATCH] Fixed buffer overflow when file caches are different sizes This was a simple oversight, we weren't checking recipient file caches when broadcasting sync! Fixed by limiting the synced cache to the last n bytes that fit in the recipient's cache. This is a bit more complicated than first n bytes, but more intuitive/likely to be relevant to the recipient file. Adds a bit of code/stack. In theory this shouldn't really affect the stack, but lfsr_file_sync is a sensitive function on the stack hot-path: code stack ctx before: 37220 2288 636 after: 37260 (+0.1%) 2296 (+0.3%) 636 (+0.0%) --- lfs.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lfs.c b/lfs.c index 2437b0fe..c400710b 100644 --- a/lfs.c +++ b/lfs.c @@ -13309,15 +13309,19 @@ int lfsr_file_sync(lfs_t *lfs, lfsr_file_t *file) { file_->b.shrub = file->b.shrub; // update leaves file_->leaf = file->leaf; - // TODO wait, what if cache sizes don't match? + // update caches - file_->cache.pos = file->cache.pos; - LFS_ASSERT(file->cache.size - <= lfsr_file_cachesize(lfs, file)); - lfs_memcpy(file_->cache.buffer, - file->cache.buffer, + // + // note we need to be careful if caches have different + // sizes, prefer the most recent data in this case + lfs_size_t d = file->cache.size - lfs_min( + lfsr_file_cachesize(lfs, file_), file->cache.size); - file_->cache.size = file->cache.size; + file_->cache.pos = file->cache.pos + d; + lfs_memcpy(file_->cache.buffer, + file->cache.buffer + d, + file->cache.size - d); + file_->cache.size = file->cache.size - d; // update any custom attrs for (lfs_size_t i = 0; i < file->cfg->attr_count; i++) {