]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/memory_utils.h
tree-wide: port cgroup cleanup to call_cleaner(cgroup_exit)
[mirror_lxc.git] / src / lxc / memory_utils.h
CommitLineData
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
bbba37f7
CB
24#define free_disarm(ptr) \
25 ({ \
26 free(ptr); \
27 move_ptr(ptr); \
28 })
29
af1dc7cd
CB
30static inline void __auto_free__(void *p)
31{
32 free(*(void **)p);
33}
34
bbba37f7
CB
35static inline void free_string_list(char **list)
36{
37 if (list) {
38 for (int i = 0; list[i]; i++)
39 free(list[i]);
40 free_disarm(list);
41 }
42}
e16ad728
CB
43define_cleanup_function(char **, free_string_list);
44#define __do_free_string_list \
45 __attribute__((__cleanup__(free_string_list_function)))
bbba37f7 46
d97919ab
CB
47static inline void __auto_fclose__(FILE **f)
48{
49 if (*f)
50 fclose(*f);
51}
52
53static inline void __auto_closedir__(DIR **d)
54{
55 if (*d)
56 closedir(*d);
57}
58
4aa90f60
CB
59#define close_prot_errno_disarm(fd) \
60 if (fd >= 0) { \
61 int _e_ = errno; \
62 close(fd); \
63 errno = _e_; \
64 fd = -EBADF; \
65 }
66
e236fe05
CB
67static inline void __auto_close__(int *fd)
68{
4aa90f60 69 close_prot_errno_disarm(*fd);
e236fe05
CB
70}
71
72#define __do_close_prot_errno __attribute__((__cleanup__(__auto_close__)))
af1dc7cd 73#define __do_free __attribute__((__cleanup__(__auto_free__)))
d97919ab
CB
74#define __do_fclose __attribute__((__cleanup__(__auto_fclose__)))
75#define __do_closedir __attribute__((__cleanup__(__auto_closedir__)))
af1dc7cd 76
4bfb655e
CB
77static inline void *memdup(const void *data, size_t len)
78{
79 void *copy = NULL;
80
81 copy = len ? malloc(len) : NULL;
82 return copy ? memcpy(copy, data, len) : NULL;
83}
84
1973b62a
CB
85#define zalloc(__size__) (calloc(1, __size__))
86
af1dc7cd 87#endif /* __LXC_MEMORY_UTILS_H */