2 * utils_safe_memory - safe memory helpers
4 * Copyright (C) 2009-2020 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2009-2020 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;
73 alloc = (struct safe_allocation *)
74 ((char *)data - offsetof(struct safe_allocation, data));
76 crypt_safe_memzero(data, alloc->size);
78 alloc->size = 0x55aa55aa;
82 void *crypt_safe_realloc(void *data, size_t size)
84 struct safe_allocation *alloc;
87 new_data = crypt_safe_alloc(size);
89 if (new_data && data) {
91 alloc = (struct safe_allocation *)
92 ((char *)data - offsetof(struct safe_allocation, data));
94 if (size > alloc->size)
97 memcpy(new_data, data, size);
100 crypt_safe_free(data);