From: Caleb Sander Date: Tue, 28 Nov 2023 20:35:01 +0000 (-0700) Subject: cleanup: add cleanup functions X-Git-Tag: v1.7~18 X-Git-Url: https://www.infradead.org/git/?a=commitdiff_plain;h=c35a784585ef68aad61be2f392476e40ccf0e811;p=users%2Fsagi%2Flibnvme.git cleanup: add cleanup functions Introduce _cleanup_free_ from nvme-cli to call free() on cleanup, _cleanup_file_ to call fclose(), _cleanup_dir_ to call closedir(), and _cleanup_fd_ to call close(). _cleanup_free_ generalizes __cleanup__(cleanup_charp), so remove it along with cleanup.c. Signed-off-by: Caleb Sander --- diff --git a/src/meson.build b/src/meson.build index 92e39d44..811f0f82 100644 --- a/src/meson.build +++ b/src/meson.build @@ -6,7 +6,6 @@ # Authors: Martin Belanger # sources = [ - 'nvme/cleanup.c', 'nvme/nbft.c', 'nvme/fabrics.c', 'nvme/filters.c', @@ -19,7 +18,6 @@ sources = [ ] mi_sources = [ - 'nvme/cleanup.c', 'nvme/log.c', 'nvme/mi.c', 'nvme/mi-mctp.c', diff --git a/src/nvme/cleanup.c b/src/nvme/cleanup.c deleted file mode 100644 index e652e33d..00000000 --- a/src/nvme/cleanup.c +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-License-Identifier: LGPL-2.1-or-later -#include -#include "cleanup.h" - -DEFINE_CLEANUP_FUNC(cleanup_charp, char *, free); diff --git a/src/nvme/cleanup.h b/src/nvme/cleanup.h index b7e15335..43276004 100644 --- a/src/nvme/cleanup.h +++ b/src/nvme/cleanup.h @@ -2,6 +2,11 @@ #ifndef __CLEANUP_H #define __CLEANUP_H +#include +#include +#include +#include + #define __cleanup__(fn) __attribute__((cleanup(fn))) #define DECLARE_CLEANUP_FUNC(name, type) \ @@ -14,6 +19,23 @@ DECLARE_CLEANUP_FUNC(name, type) \ free_fn(*__p); \ } -DECLARE_CLEANUP_FUNC(cleanup_charp, char *); +static inline void freep(void *p) +{ + free(*(void **)p); +} +#define _cleanup_free_ __cleanup__(freep) + +static inline DEFINE_CLEANUP_FUNC(cleanup_file, FILE *, fclose) +#define _cleanup_file_ __cleanup__(cleanup_file) + +static inline DEFINE_CLEANUP_FUNC(cleanup_dir, DIR *, closedir) +#define _cleanup_dir_ __cleanup__(cleanup_dir) + +static inline void cleanup_fd(int *fd) +{ + if (*fd >= 0) + close(*fd); +} +#define _cleanup_fd_ __cleanup__(cleanup_fd) #endif diff --git a/src/nvme/log.c b/src/nvme/log.c index d4cef19f..2ffca3eb 100644 --- a/src/nvme/log.c +++ b/src/nvme/log.c @@ -46,8 +46,8 @@ __nvme_msg(nvme_root_t r, int lvl, "[%s] <%s>%s ", "[%s] <%s> %s: ", }; - char *header __cleanup__(cleanup_charp) = NULL; - char *message __cleanup__(cleanup_charp) = NULL; + _cleanup_free_ char *header = NULL; + _cleanup_free_ char *message = NULL; int idx = 0; if (!r) diff --git a/test/test-util.c b/test/test-util.c index e32f030a..88a3f42c 100644 --- a/test/test-util.c +++ b/test/test-util.c @@ -20,7 +20,6 @@ #include #include -#include "nvme/cleanup.c" /* to resolve cleanup_charp() */ #include "nvme/log.c" /* to resolve __nvme_msg() */ #include "nvme/util.c"