Skip to content

Commit

Permalink
AP_HAL_Linux: file descriptor leaking and other issues in "Storage" o…
Browse files Browse the repository at this point in the history
…f Linux.

- Fixed the fd leaking issue in "_storage_create" found by @peterbarker
- Remove the unnecessary call of "unlinkat" in "_storage_create"
- Simplify the implementation of "init"

Signed-off-by: junan <[email protected]>
  • Loading branch information
junan76 authored and tridge committed Sep 17, 2024
1 parent 9cb3354 commit 71a6936
Showing 1 changed file with 4 additions and 14 deletions.
18 changes: 4 additions & 14 deletions libraries/AP_HAL_Linux/Storage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ int Storage::_storage_create(const char *dpath)
return -1;
}

unlinkat(dfd, dpath, 0);
int fd = openat(dfd, STORAGE_FILE, O_RDWR|O_CREAT|O_CLOEXEC, 0666);

if (fd == -1) {
Expand All @@ -114,6 +113,7 @@ int Storage::_storage_create(const char *dpath)
if (ftruncate(fd, sizeof(_buffer)) == -1) {
fprintf(stderr, "Failed to set file size to %u kB (%m)\n",
unsigned(sizeof(_buffer) / 1024));
close(fd);
goto fail;
}

Expand Down Expand Up @@ -145,26 +145,16 @@ void Storage::init()
dpath = HAL_BOARD_STORAGE_DIRECTORY;
}

int fd = open(dpath, O_RDWR|O_CLOEXEC);
int fd = _storage_create(dpath);
if (fd == -1) {
fd = _storage_create(dpath);
if (fd == -1) {
AP_HAL::panic("Cannot create storage %s (%m)", dpath);
}
AP_HAL::panic("Cannot create storage %s (%m)", dpath);
}

ssize_t ret = read(fd, _buffer, sizeof(_buffer));

if (ret != sizeof(_buffer)) {
close(fd);
_storage_create(dpath);
fd = open(dpath, O_RDONLY|O_CLOEXEC);
if (fd == -1) {
AP_HAL::panic("Failed to open %s (%m)", dpath);
}
if (read(fd, _buffer, sizeof(_buffer)) != sizeof(_buffer)) {
AP_HAL::panic("Failed to read %s (%m)", dpath);
}
AP_HAL::panic("Failed to read %s (%m)", dpath);
}

_fd = fd;
Expand Down

0 comments on commit 71a6936

Please sign in to comment.