diff --git a/lfs.c b/lfs.c index b2c0a631aac..463c097a298 100644 --- a/lfs.c +++ b/lfs.c @@ -975,6 +975,7 @@ static int lfs_index_find(lfs_t *lfs, return err; } + assert(head >= 2 && head <= lfs->cfg->block_count); current -= 1 << skip; } @@ -1054,6 +1055,8 @@ static int lfs_index_extend(lfs_t *lfs, return err; } } + + assert(head >= 2 && head <= lfs->cfg->block_count); } *off = 4*skips; @@ -1428,18 +1431,17 @@ lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file, // check if we need a new block if (!(file->flags & LFS_F_WRITING) || file->off == lfs->cfg->block_size) { - if (!(file->flags & LFS_F_WRITING)) { + if (!(file->flags & LFS_F_WRITING) && file->pos > 0) { // find out which block we're extending from int err = lfs_index_find(lfs, &file->cache, NULL, file->head, file->size, - file->pos, &file->block, &file->off); + file->pos-1, &file->block, &file->off); if (err) { return err; } // mark cache as dirty since we may have read data into it file->cache.block = 0xffffffff; - file->flags |= LFS_F_WRITING; } // extend file with new blocks @@ -1450,6 +1452,8 @@ lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file, if (err) { return err; } + + file->flags |= LFS_F_WRITING; } // program as much as we can in current block diff --git a/tests/test_seek.sh b/tests/test_seek.sh index 8c0093852eb..1f70ee391cd 100755 --- a/tests/test_seek.sh +++ b/tests/test_seek.sh @@ -277,5 +277,33 @@ tests/test.py << TEST lfs_unmount(&lfs) => 0; TEST +echo "--- Boundary seek and write ---" +tests/test.py << TEST + lfs_mount(&lfs, &cfg) => 0; + lfs_file_open(&lfs, &file[0], "hello/kitty42", LFS_O_RDWR) => 0; + + size = strlen("hedgehoghog"); + const lfs_soff_t offsets[] = {512, 1020, 513, 1021, 511, 1019}; + + for (int i = 0; i < sizeof(offsets) / sizeof(offsets[0]); i++) { + lfs_soff_t off = offsets[i]; + memcpy(buffer, "hedgehoghog", size); + lfs_file_seek(&lfs, &file[0], off, LFS_SEEK_SET) >= 0 => 1; + lfs_file_write(&lfs, &file[0], buffer, size) => size; + lfs_file_seek(&lfs, &file[0], off, LFS_SEEK_SET) => off+size; + lfs_file_read(&lfs, &file[0], buffer, size) => size; + memcmp(buffer, "hedgehoghog", size) => 0; + + lfs_file_seek(&lfs, &file[0], 0, LFS_SEEK_SET) => off+size; + lfs_file_read(&lfs, &file[0], buffer, size) => size; + memcmp(buffer, "kittycatcat", size) => 0; + + lfs_file_sync(&lfs, &file[0]) => 0; + } + + lfs_file_close(&lfs, &file[0]) => 0; + lfs_unmount(&lfs) => 0; +TEST + echo "--- Results ---" tests/stats.py