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%)
This commit is contained in:
Christopher Haster
2025-05-24 23:45:28 -05:00
parent f7e17c8aad
commit 328c1706cf
+11 -7
View File
@@ -13309,15 +13309,19 @@ int lfsr_file_sync(lfs_t *lfs, lfsr_file_t *file) {
file_->b.shrub = file->b.shrub; file_->b.shrub = file->b.shrub;
// update leaves // update leaves
file_->leaf = file->leaf; file_->leaf = file->leaf;
// TODO wait, what if cache sizes don't match?
// update caches // update caches
file_->cache.pos = file->cache.pos; //
LFS_ASSERT(file->cache.size // note we need to be careful if caches have different
<= lfsr_file_cachesize(lfs, file)); // sizes, prefer the most recent data in this case
lfs_memcpy(file_->cache.buffer, lfs_size_t d = file->cache.size - lfs_min(
file->cache.buffer, lfsr_file_cachesize(lfs, file_),
file->cache.size); 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 // update any custom attrs
for (lfs_size_t i = 0; i < file->cfg->attr_count; i++) { for (lfs_size_t i = 0; i < file->cfg->attr_count; i++) {