]>
Commit | Line | Data |
---|---|---|
cc73685d | 1 | /* SPDX-License-Identifier: LGPL-2.1+ */ |
af1dc7cd CB |
2 | |
3 | #ifndef __LXC_MEMORY_UTILS_H | |
4 | #define __LXC_MEMORY_UTILS_H | |
5 | ||
d97919ab CB |
6 | #include <dirent.h> |
7 | #include <errno.h> | |
8 | #include <stdio.h> | |
af1dc7cd | 9 | #include <stdlib.h> |
d97919ab | 10 | #include <sys/types.h> |
e236fe05 | 11 | #include <unistd.h> |
af1dc7cd | 12 | |
4aa90f60 CB |
13 | #include "macro.h" |
14 | ||
e16ad728 CB |
15 | #define define_cleanup_function(type, cleaner) \ |
16 | static inline void cleaner##_function(type *ptr) \ | |
17 | { \ | |
18 | if (*ptr) \ | |
19 | cleaner(*ptr); \ | |
bbba37f7 CB |
20 | } |
21 | ||
e16ad728 CB |
22 | #define call_cleaner(cleaner) __attribute__((__cleanup__(cleaner##_function))) |
23 | ||
6e87cb17 CB |
24 | #define close_prot_errno_disarm(fd) \ |
25 | if (fd >= 0) { \ | |
26 | int _e_ = errno; \ | |
27 | close(fd); \ | |
28 | errno = _e_; \ | |
29 | fd = -EBADF; \ | |
30 | } | |
31 | ||
32 | static inline void close_prot_errno_disarm_function(int *fd) | |
33 | { | |
34 | close_prot_errno_disarm(*fd); | |
35 | } | |
f62cf1d4 | 36 | #define __do_close call_cleaner(close_prot_errno_disarm) |
6e87cb17 CB |
37 | |
38 | define_cleanup_function(FILE *, fclose); | |
39 | #define __do_fclose call_cleaner(fclose) | |
40 | ||
41 | define_cleanup_function(DIR *, closedir); | |
42 | #define __do_closedir call_cleaner(closedir) | |
43 | ||
ba7536c0 CB |
44 | #define free_disarm(ptr) \ |
45 | ({ \ | |
46 | free(ptr); \ | |
47 | ptr = NULL; \ | |
bbba37f7 CB |
48 | }) |
49 | ||
6e87cb17 | 50 | static inline void free_disarm_function(void *ptr) |
af1dc7cd | 51 | { |
6e87cb17 | 52 | free_disarm(*(void **)ptr); |
af1dc7cd | 53 | } |
6e87cb17 | 54 | #define __do_free call_cleaner(free_disarm) |
af1dc7cd | 55 | |
bbba37f7 CB |
56 | static inline void free_string_list(char **list) |
57 | { | |
58 | if (list) { | |
59 | for (int i = 0; list[i]; i++) | |
60 | free(list[i]); | |
61 | free_disarm(list); | |
62 | } | |
63 | } | |
e16ad728 | 64 | define_cleanup_function(char **, free_string_list); |
6e87cb17 | 65 | #define __do_free_string_list call_cleaner(free_string_list) |
af1dc7cd | 66 | |
4bfb655e CB |
67 | static inline void *memdup(const void *data, size_t len) |
68 | { | |
69 | void *copy = NULL; | |
70 | ||
71 | copy = len ? malloc(len) : NULL; | |
72 | return copy ? memcpy(copy, data, len) : NULL; | |
73 | } | |
74 | ||
1973b62a CB |
75 | #define zalloc(__size__) (calloc(1, __size__)) |
76 | ||
af1dc7cd | 77 | #endif /* __LXC_MEMORY_UTILS_H */ |