Debian Codegraph @

libdrgn/cleanup.h

raw
1 // Copyright (c) Meta Platforms, Inc. and affiliates.
2 // SPDX-License-Identifier: LGPL-2.1-or-later
3
4 /**
5 * @file
6 *
7 * Cleanup functions.
8 */
9
10 #ifndef DRGN_CLEANUP_H
11 #define DRGN_CLEANUP_H
12
13 #include <dirent.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <sys/types.h>
17 #include <unistd.h>
18
19 #define _cleanup_(x) __attribute__((__cleanup__(x)))
20
21 /** Call @c free() when the variable goes out of scope. */
22 #define _cleanup_free_ _cleanup_(freep)
23 static inline void freep(void *p)
24 {
25 free(*(void **)p);
26 }
27
28 /** Call @c fclose() when the variable goes out of scope. */
29 #define _cleanup_fclose_ _cleanup_(fclosep)
30 static inline void fclosep(FILE **fp)
31 {
32 if (*fp)
33 fclose(*fp);
34 }
35
36 /** Call @c close() when the variable goes out of scope. */
37 #define _cleanup_close_ _cleanup_(closep)
38 static inline void closep(int *fd)
39 {
40 if (*fd >= 0)
41 close(*fd);
42 }
43
44 /** Call @c closedir() when the variable goes out of scope. */
45 #define _cleanup_closedir_ _cleanup_(closedirp)
46 static inline void closedirp(DIR **dirp)
47 {
48 if (*dirp)
49 closedir(*dirp);
50 }
51
52 /**
53 * Get the value of a pointer variable and reset it to @c NULL.
54 *
55 * This can be used to avoid freeing a variable declared with @ref
56 * _cleanup_free_ or another scope guard that is a no-op for @c NULL.
57 */
58 #define no_cleanup_ptr(p) ({ __auto_type __ptr = (p); (p) = NULL; __ptr; })
59
60 /**
61 * Return a pointer declared with @ref _cleanup_free_ without freeing it.
62 *
63 * This can also be used for other scope guards that are a no-op for @c NULL.
64 */
65 #define return_ptr(p) return no_cleanup_ptr(p)
66
67 #endif /* DRGN_CLEANUP_H */