]> www.infradead.org Git - users/sagi/nvme-cli.git/commitdiff
nvme: add some simplifying macros for __attribute__((cleanup()))
authorMartin Wilck <mwilck@suse.com>
Thu, 4 Mar 2021 17:16:03 +0000 (18:16 +0100)
committerMartin Wilck <mwilck@suse.com>
Tue, 30 Mar 2021 15:41:26 +0000 (17:41 +0200)
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.

Reviewed-by: Chaitanya Kulkarni <chaitanya.kulkarni@wdc.com>
Reviewed-by: Sagi Grimberg <sagi@grimberg.me>
Makefile
util/cleanup.c [new file with mode: 0644]
util/cleanup.h [new file with mode: 0644]

index 3ea17b5ff584a8747c370a8bc2f12c810f626c7b..3412e5de9f961ab5d90304c1ac12487788e55939 100644 (file)
--- 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 (file)
index 0000000..0d5d910
--- /dev/null
@@ -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 (file)
index 0000000..89a4984
--- /dev/null
@@ -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