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