]> git.proxmox.com Git - mirror_lxcfs.git/blob - src/memory_utils.h
Add macro pivot&bpf for loongarch64
[mirror_lxcfs.git] / src / memory_utils.h
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #ifndef __LXCFS_MEMORY_UTILS_H
4 #define __LXCFS_MEMORY_UTILS_H
5
6 #include "config.h"
7
8 #include <dirent.h>
9 #include <errno.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 #include "macro.h"
17
18 #define define_cleanup_function(type, cleaner) \
19 static inline void cleaner##_function(type *ptr) \
20 { \
21 if (*ptr) \
22 cleaner(*ptr); \
23 }
24
25 #define call_cleaner(cleaner) __attribute__((__cleanup__(cleaner##_function)))
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
35 #define close_prot_errno_replace(fd, new_fd) \
36 if (fd >= 0) { \
37 int _e_ = errno; \
38 close(fd); \
39 errno = _e_; \
40 fd = new_fd; \
41 }
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)
54
55 #define free_disarm(ptr) \
56 ({ \
57 free(ptr); \
58 ptr = NULL; \
59 })
60
61 static inline void free_disarm_function(void *ptr)
62 {
63 free_disarm(*(void **)ptr);
64 }
65 #define __do_free call_cleaner(free_disarm)
66
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)
77
78 static inline void *memdup(const void *data, size_t len)
79 {
80 void *copy = NULL;
81
82 copy = len ? malloc(len) : NULL;
83 return copy ? memcpy(copy, data, len) : NULL;
84 }
85
86 #define zalloc(__size__) (calloc(1, __size__))
87
88 #endif /* __LXCFS_MEMORY_UTILS_H */