Skip to content

Commit cc1bad9

Browse files
committed
littlefs: Fixed issue with cleanup in mount function on error
As a part of the v1.6 update, littlefs added proper handling for cleaning up memory in the case of an error during mount. This took care of a memory leak users were seeing. Ironically, it turns out the implementation and user patterns in mbed-os was _relying_ on this memory leak to avoid a double free in the same case of an error during mount. The issue was that a failed mount would leave the LittleFileSystem class in a state where it thought it was mounted, and later it would attempt to unmount the filesystem. With the previous memory leak this would be "ok", and the leaked memory would be freed. But with the fix in v1.6, no memory is leaked, and the incorrect free triggers a hard fault. Fixed to clean up state properly on failed mounts.
1 parent b53a9ea commit cc1bad9

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

features/filesystem/littlefs/LittleFileSystem.cpp

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ int LittleFileSystem::mount(BlockDevice *bd)
134134
_bd = bd;
135135
int err = _bd->init();
136136
if (err) {
137+
_bd = NULL;
137138
LFS_INFO("mount -> %d", err);
138139
_mutex.unlock();
139140
return err;
@@ -164,36 +165,40 @@ int LittleFileSystem::mount(BlockDevice *bd)
164165
}
165166

166167
err = lfs_mount(&_lfs, &_config);
167-
LFS_INFO("mount -> %d", lfs_toerror(err));
168+
if (err) {
169+
_bd = NULL;
170+
LFS_INFO("mount -> %d", lfs_toerror(err));
171+
_mutex.unlock();
172+
return lfs_toerror(err);
173+
}
174+
168175
_mutex.unlock();
169-
return lfs_toerror(err);
176+
LFS_INFO("mount -> %d", 0);
177+
return 0;
170178
}
171179

172180
int LittleFileSystem::unmount()
173181
{
174182
_mutex.lock();
175183
LFS_INFO("unmount(%s)", "");
184+
int res = 0;
176185
if (_bd) {
177186
int err = lfs_unmount(&_lfs);
178-
if (err) {
179-
LFS_INFO("unmount -> %d", lfs_toerror(err));
180-
_mutex.unlock();
181-
return lfs_toerror(err);
187+
if (err && !res) {
188+
res = lfs_toerror(err);
182189
}
183190

184191
err = _bd->deinit();
185-
if (err) {
186-
LFS_INFO("unmount -> %d", err);
187-
_mutex.unlock();
188-
return err;
192+
if (err && !res) {
193+
res = err;
189194
}
190195

191196
_bd = NULL;
192197
}
193198

194-
LFS_INFO("unmount -> %d", 0);
199+
LFS_INFO("unmount -> %d", res);
195200
_mutex.unlock();
196-
return 0;
201+
return res;
197202
}
198203

199204
int LittleFileSystem::format(BlockDevice *bd,

0 commit comments

Comments
 (0)