]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/alloc-util.c
Add SPDX license identifiers to source files under the LGPL
[thirdparty/systemd.git] / src / basic / alloc-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
b5efdb8a
LP
2/***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
6
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19***/
20
11c3a366
TA
21#include <stdint.h>
22#include <string.h>
23
b5efdb8a 24#include "alloc-util.h"
11c3a366 25#include "macro.h"
b5efdb8a
LP
26#include "util.h"
27
28void* memdup(const void *p, size_t l) {
c165d97d 29 void *ret;
b5efdb8a 30
c165d97d
LP
31 assert(l == 0 || p);
32
33 ret = malloc(l);
34 if (!ret)
35 return NULL;
36
37 memcpy(ret, p, l);
38 return ret;
39}
40
41void* memdup_suffix0(const void*p, size_t l) {
42 void *ret;
43
44 assert(l == 0 || p);
45
46 /* The same as memdup() but place a safety NUL byte after the allocated memory */
b5efdb8a 47
c165d97d
LP
48 ret = malloc(l + 1);
49 if (!ret)
b5efdb8a
LP
50 return NULL;
51
c165d97d
LP
52 *((uint8_t*) mempcpy(ret, p, l)) = 0;
53 return ret;
b5efdb8a
LP
54}
55
56void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
57 size_t a, newalloc;
58 void *q;
59
60 assert(p);
61 assert(allocated);
62
63 if (*allocated >= need)
64 return *p;
65
66 newalloc = MAX(need * 2, 64u / size);
67 a = newalloc * size;
68
69 /* check for overflows */
70 if (a < size * need)
71 return NULL;
72
73 q = realloc(*p, a);
74 if (!q)
75 return NULL;
76
77 *p = q;
78 *allocated = newalloc;
79 return q;
80}
81
82void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
83 size_t prev;
84 uint8_t *q;
85
86 assert(p);
87 assert(allocated);
88
89 prev = *allocated;
90
91 q = greedy_realloc(p, allocated, need, size);
92 if (!q)
93 return NULL;
94
95 if (*allocated > prev)
96 memzero(q + prev * size, (*allocated - prev) * size);
97
98 return q;
99}