]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/memory-util.h
c36a0cc337a3b296628ff0e8e789ef7a5af90353
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include "memory-util-fundamental.h" /* IWYU pragma: export */
9 size_t page_size(void) _pure_
;
10 #define PAGE_ALIGN(l) ALIGN_TO(l, page_size())
11 #define PAGE_ALIGN_U64(l) ALIGN_TO_U64(l, page_size())
12 #define PAGE_ALIGN_DOWN(l) ALIGN_DOWN(l, page_size())
13 #define PAGE_ALIGN_DOWN_U64(l) ALIGN_DOWN_U64(l, page_size())
14 #define PAGE_OFFSET(l) ALIGN_OFFSET(l, page_size())
15 #define PAGE_OFFSET_U64(l) ALIGN_OFFSET_U64(l, page_size())
17 /* Normal memcpy() requires src to be nonnull. We do nothing if n is 0. */
18 static inline void* memcpy_safe(void *dst
, const void *src
, size_t n
) {
22 return memcpy(dst
, src
, n
);
25 /* Normal mempcpy() requires src to be nonnull. We do nothing if n is 0. */
26 static inline void* mempcpy_safe(void *dst
, const void *src
, size_t n
) {
30 return mempcpy(dst
, src
, n
);
33 #define _mempcpy_typesafe(dst, src, n, sz) \
36 assert_se(MUL_SAFE(&sz, sizeof((dst)[0]), n)); \
37 (typeof((dst)[0])*) mempcpy_safe(dst, src, sz); \
40 #define mempcpy_typesafe(dst, src, n) \
41 _mempcpy_typesafe(dst, src, n, UNIQ_T(sz, UNIQ))
43 /* Normal memcmp() requires s1 and s2 to be nonnull. We do nothing if n is 0. */
44 static inline int memcmp_safe(const void *s1
, const void *s2
, size_t n
) {
49 return memcmp(s1
, s2
, n
);
52 /* Compare s1 (length n1) with s2 (length n2) in lexicographic order. */
53 static inline int memcmp_nn(const void *s1
, size_t n1
, const void *s2
, size_t n2
) {
54 return memcmp_safe(s1
, s2
, MIN(n1
, n2
))
58 #define zero(x) (memzero(&(x), sizeof(x)))
60 bool memeqbyte(uint8_t byte
, const void *data
, size_t length
) _nonnull_if_nonzero_(2, 3);
62 #define memeqzero(data, length) memeqbyte(0x00, data, length)
64 #define eqzero(x) memeqzero(x, sizeof(x))
66 static inline void* mempset(void *s
, int c
, size_t n
) {
68 return (uint8_t*) s
+ n
;
71 /* Normal memmem() requires haystack to be nonnull, which is annoying for zero-length buffers */
72 static inline void* memmem_safe(const void *haystack
, size_t haystacklen
, const void *needle
, size_t needlelen
) {
75 return (void*) haystack
;
77 if (haystacklen
< needlelen
)
83 return memmem(haystack
, haystacklen
, needle
, needlelen
);
86 static inline void* mempmem_safe(const void *haystack
, size_t haystacklen
, const void *needle
, size_t needlelen
) {
89 p
= memmem_safe(haystack
, haystacklen
, needle
, needlelen
);
93 return (uint8_t*) p
+ needlelen
;
96 void* erase_and_free(void *p
);
98 static inline void erase_and_freep(void *p
) {
99 erase_and_free(*(void**) p
);
102 /* Use with _cleanup_ to erase a single 'char' when leaving scope */
103 static inline void erase_char(char *p
) {
104 explicit_bzero_safe(p
, sizeof(char));
107 /* Makes a copy of the buffer with reversed order of bytes */
108 void* memdup_reverse(const void *mem
, size_t size
);