]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/alloc-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include "alloc-util.h"
9 #include "memory-util.h"
11 void* memdup(const void *p
, size_t l
) {
20 return memcpy_safe(ret
, p
, l
);
23 void* memdup_suffix0(const void *p
, size_t l
) {
28 /* The same as memdup() but place a safety NUL byte after the allocated memory */
30 if (_unlikely_(l
== SIZE_MAX
)) /* prevent overflow */
37 ((uint8_t*) ret
)[l
] = 0;
38 return memcpy_safe(ret
, p
, l
);
51 /* We use malloc_usable_size() for determining the current allocated size. On all systems we care
52 * about this should be safe to rely on. Should there ever arise the need to avoid relying on this we
53 * can instead locally fall back to realloc() on every call, rounded up to the next exponent of 2 or
56 if (*p
&& (size
== 0 || (MALLOC_SIZEOF_SAFE(*p
) / size
>= need
)))
59 if (_unlikely_(need
> SIZE_MAX
/2)) /* Overflow check */
63 if (size_multiply_overflow(newalloc
, size
))
67 if (a
< 64) /* Allocate at least 64 bytes */
77 void* greedy_realloc0(
87 before
= MALLOC_SIZEOF_SAFE(*p
); /* malloc_usable_size() will return 0 on NULL input, as per docs */
89 q
= greedy_realloc(p
, need
, size
);
93 after
= MALLOC_SIZEOF_SAFE(q
);
95 if (size
== 0) /* avoid division by zero */
98 before
= (before
/ size
) * size
; /* Round down */
101 memzero(q
+ before
, after
- before
);
106 void* greedy_realloc_append(
117 assert(from
|| n_from
== 0);
119 if (n_from
> SIZE_MAX
- *n_p
)
122 q
= greedy_realloc(p
, *n_p
+ n_from
, size
);
126 memcpy_safe(q
+ *n_p
* size
, from
, n_from
* size
);
133 void *expand_to_usable(void *ptr
, size_t newsize _unused_
) {