| 1 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
#ifndef __CLEANUP_H |
| 3 |
#define __CLEANUP_H |
| 4 |
|
| 5 |
#include <dirent.h> |
| 6 |
#include <stdio.h> |
| 7 |
#include <stdlib.h> |
| 8 |
#include <unistd.h> |
| 9 |
|
| 10 |
#define __cleanup__(fn) __attribute__((cleanup(fn))) |
| 11 |
|
| 12 |
#define DECLARE_CLEANUP_FUNC(name, type) \ |
| 13 |
void name(type *__p) |
| 14 |
|
| 15 |
#define DEFINE_CLEANUP_FUNC(name, type, free_fn)\ |
| 16 |
DECLARE_CLEANUP_FUNC(name, type) \ |
| 17 |
{ \ |
| 18 |
if (*__p) \ |
| 19 |
free_fn(*__p); \ |
| 20 |
} |
| 21 |
|
| 22 |
static inline void freep(void *p) |
| 23 |
{ |
| 24 |
free(*(void **)p); |
| 25 |
} |
| 26 |
#define _cleanup_free_ __cleanup__(freep) |
| 27 |
|
| 28 |
static inline DEFINE_CLEANUP_FUNC(cleanup_file, FILE *, fclose) |
| 29 |
#define _cleanup_file_ __cleanup__(cleanup_file) |
| 30 |
|
| 31 |
static inline DEFINE_CLEANUP_FUNC(cleanup_dir, DIR *, closedir) |
| 32 |
#define _cleanup_dir_ __cleanup__(cleanup_dir) |
| 33 |
|
| 34 |
static inline void cleanup_fd(int *fd) |
| 35 |
{ |
| 36 |
if (*fd >= 0) |
| 37 |
close(*fd); |
| 38 |
} |
| 39 |
#define _cleanup_fd_ __cleanup__(cleanup_fd) |
| 40 |
|
| 41 |
#endif |