[PATCH 05/10] nvme: add some simplifying macros for __attribute__((cleanup()))
mwilck at suse.com
mwilck at suse.com
Sat Mar 6 00:36:19 GMT 2021
From: Martin Wilck <mwilck at suse.com>
Using __attribute__((cleanup())) is very helpful for writing leak-free
code, but it requires lots of awkward boiler plate code. Add some
small helpers to make its use more comfortable.
Signed-off-by: Martin Wilck <mwilck at suse.com>
---
Makefile | 2 +-
util/cleanup.c | 4 ++++
util/cleanup.h | 18 ++++++++++++++++++
3 files changed, 23 insertions(+), 1 deletion(-)
create mode 100644 util/cleanup.c
create mode 100644 util/cleanup.h
diff --git a/Makefile b/Makefile
index 3ea17b5..3412e5d 100644
--- a/Makefile
+++ b/Makefile
@@ -62,7 +62,7 @@ OBJS := nvme-print.o nvme-ioctl.o nvme-rpmb.o \
nvme-lightnvm.o fabrics.o nvme-models.o plugin.o \
nvme-status.o nvme-filters.o nvme-topology.o
-UTIL_OBJS := util/argconfig.o util/suffix.o util/json.o util/parser.o
+UTIL_OBJS := util/argconfig.o util/suffix.o util/json.o util/parser.o util/cleanup.o
PLUGIN_OBJS := \
plugins/intel/intel-nvme.o \
diff --git a/util/cleanup.c b/util/cleanup.c
new file mode 100644
index 0000000..0d5d910
--- /dev/null
+++ b/util/cleanup.c
@@ -0,0 +1,4 @@
+#include <stdlib.h>
+#include "cleanup.h"
+
+DEFINE_CLEANUP_FUNC(cleanup_charp, char *, free);
diff --git a/util/cleanup.h b/util/cleanup.h
new file mode 100644
index 0000000..89a4984
--- /dev/null
+++ b/util/cleanup.h
@@ -0,0 +1,18 @@
+#ifndef __CLEANUP_H
+#define __CLEANUP_H
+
+#define __cleanup__(fn) __attribute__((cleanup(fn)))
+
+#define DECLARE_CLEANUP_FUNC(name, type) \
+ void name(type *__p)
+
+#define DEFINE_CLEANUP_FUNC(name, type, free_fn)\
+DECLARE_CLEANUP_FUNC(name, type) \
+{ \
+ if (*__p) \
+ free_fn(*__p); \
+}
+
+DECLARE_CLEANUP_FUNC(cleanup_charp, char *);
+
+#endif
--
2.29.2
More information about the Linux-nvme
mailing list