1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "alloc-util.h"
12 #include "memory-util-fundamental.h"
14 size_t page_size(void) _pure_
;
15 #define PAGE_ALIGN(l) ALIGN_TO((l), page_size())
16 #define PAGE_ALIGN_DOWN(l) ((l) & ~(page_size() - 1))
17 #define PAGE_OFFSET(l) ((l) & (page_size() - 1))
19 /* Normal memcpy() requires src to be nonnull. We do nothing if n is 0. */
20 static inline void *memcpy_safe(void *dst
, const void *src
, size_t n
) {
24 return memcpy(dst
, src
, n
);
27 /* Normal mempcpy() requires src to be nonnull. We do nothing if n is 0. */
28 static inline void *mempcpy_safe(void *dst
, const void *src
, size_t n
) {
32 return mempcpy(dst
, src
, n
);
35 /* Normal memcmp() requires s1 and s2 to be nonnull. We do nothing if n is 0. */
36 static inline int memcmp_safe(const void *s1
, const void *s2
, size_t n
) {
41 return memcmp(s1
, s2
, n
);
44 /* Compare s1 (length n1) with s2 (length n2) in lexicographic order. */
45 static inline int memcmp_nn(const void *s1
, size_t n1
, const void *s2
, size_t n2
) {
46 return memcmp_safe(s1
, s2
, MIN(n1
, n2
))
50 #define memzero(x,l) \
57 #define zero(x) (memzero(&(x), sizeof(x)))
59 bool memeqbyte(uint8_t byte
, const void *data
, size_t length
);
61 #define memeqzero(data, length) memeqbyte(0x00, data, length)
63 #define eqzero(x) memeqzero(x, sizeof(x))
65 static inline void *mempset(void *s
, int c
, size_t n
) {
67 return (uint8_t*)s
+ n
;
70 /* Normal memmem() requires haystack to be nonnull, which is annoying for zero-length buffers */
71 static inline void *memmem_safe(const void *haystack
, size_t haystacklen
, const void *needle
, size_t needlelen
) {
74 return (void*) haystack
;
76 if (haystacklen
< needlelen
)
82 return memmem(haystack
, haystacklen
, needle
, needlelen
);
85 static inline void *mempmem_safe(const void *haystack
, size_t haystacklen
, const void *needle
, size_t needlelen
) {
88 p
= memmem_safe(haystack
, haystacklen
, needle
, needlelen
);
92 return (uint8_t*) p
+ needlelen
;
95 static inline void* erase_and_free(void *p
) {
101 l
= MALLOC_SIZEOF_SAFE(p
);
102 explicit_bzero_safe(p
, l
);
106 static inline void erase_and_freep(void *p
) {
107 erase_and_free(*(void**) p
);
110 /* Use with _cleanup_ to erase a single 'char' when leaving scope */
111 static inline void erase_char(char *p
) {
112 explicit_bzero_safe(p
, sizeof(char));
115 /* An automatic _cleanup_-like logic for destroy arrays (i.e. pointers + size) when leaving scope */
116 typedef struct ArrayCleanup
{
119 free_array_func_t pfunc
;
122 static inline void array_cleanup(const ArrayCleanup
*c
) {
125 assert(!c
->parray
== !c
->pn
);
132 c
->pfunc(*c
->parray
, *c
->pn
);
139 #define CLEANUP_ARRAY(array, n, func) \
140 _cleanup_(array_cleanup) _unused_ const ArrayCleanup CONCATENATE(_cleanup_array_, UNIQ) = { \
141 .parray = (void**) &(array), \
143 .pfunc = (free_array_func_t) ({ \
144 void (*_f)(typeof(array[0]) *a, size_t b) = func; \