2 * utils_safe_memory - safe memory helpers
4 * Copyright (C) 2009-2021 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2009-2021 Milan Broz
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "libcryptsetup.h"
26 struct safe_allocation {
32 * Replacement for memset(s, 0, n) on stack that can be optimized out
33 * Also used in safe allocations for explicit memory wipe.
35 void crypt_safe_memzero(void *data, size_t size)
37 #ifdef HAVE_EXPLICIT_BZERO
38 explicit_bzero(data, size);
40 volatile uint8_t *p = (volatile uint8_t *)data;
47 /* safe allocations */
48 void *crypt_safe_alloc(size_t size)
50 struct safe_allocation *alloc;
52 if (!size || size > (SIZE_MAX - offsetof(struct safe_allocation, data)))
55 alloc = malloc(size + offsetof(struct safe_allocation, data));
60 crypt_safe_memzero(&alloc->data, size);
62 /* coverity[leaked_storage] */
66 void crypt_safe_free(void *data)
68 struct safe_allocation *alloc;
74 alloc = (struct safe_allocation *)
75 ((char *)data - offsetof(struct safe_allocation, data));
77 crypt_safe_memzero(data, alloc->size);
79 s = (volatile size_t *)&alloc->size;
84 void *crypt_safe_realloc(void *data, size_t size)
86 struct safe_allocation *alloc;
89 new_data = crypt_safe_alloc(size);
91 if (new_data && data) {
93 alloc = (struct safe_allocation *)
94 ((char *)data - offsetof(struct safe_allocation, data));
96 if (size > alloc->size)
99 memcpy(new_data, data, size);
102 crypt_safe_free(data);