summaryrefslogtreecommitdiffstats
path: root/util/cleanup.h
diff options
context:
space:
mode:
Diffstat (limited to 'util/cleanup.h')
-rw-r--r--util/cleanup.h37
1 files changed, 37 insertions, 0 deletions
diff --git a/util/cleanup.h b/util/cleanup.h
new file mode 100644
index 0000000..ee9b120
--- /dev/null
+++ b/util/cleanup.h
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+#ifndef __CLEANUP_H
+#define __CLEANUP_H
+
+#include <unistd.h>
+#include <stdlib.h>
+
+#include "util/mem.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); \
+}
+
+static inline void freep(void *p)
+{
+ free(*(void**) p);
+}
+#define _cleanup_free_ __cleanup__(freep)
+
+#define _cleanup_huge_ __cleanup__(nvme_free_huge)
+
+static inline void close_file(int *f)
+{
+ if (*f > STDERR_FILENO)
+ close(*f);
+}
+#define _cleanup_file_ __cleanup__(close_file)
+
+#endif