From 71a69367dfceeba8441dafd103ec733558327b64 Mon Sep 17 00:00:00 2001 From: junan Date: Mon, 9 Sep 2024 20:09:59 +0800 Subject: [PATCH] AP_HAL_Linux: file descriptor leaking and other issues in "Storage" of 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 --- libraries/AP_HAL_Linux/Storage.cpp | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/libraries/AP_HAL_Linux/Storage.cpp b/libraries/AP_HAL_Linux/Storage.cpp index 7d3a460b62e75..377a42867bd95 100644 --- a/libraries/AP_HAL_Linux/Storage.cpp +++ b/libraries/AP_HAL_Linux/Storage.cpp @@ -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) { @@ -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; } @@ -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;