5 xalloc.h -- malloc and related functions with out of memory checking
6 Copyright (C) 1990, 91, 92, 93, 94, 95, 96, 97 Free Software Foundation, Inc.
7 Copyright (C) 2011-2013 Guus Sliepen <guus@tinc-vpn.org>
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License along
20 with this program; if not, write to the Free Software Foundation, Inc., Foundation,
21 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 static inline void *xmalloc(size_t n) ATTR_MALLOC;
29 static inline void *xmalloc(size_t n) {
39 static inline void *xzalloc(size_t n) ATTR_MALLOC;
40 static inline void *xzalloc(size_t n) {
41 void *p = calloc(1, n);
50 static inline void *xrealloc(void *p, size_t n) {
60 static inline char *xstrdup(const char *s) ATTR_MALLOC ATTR_NONNULL;
61 static inline char *xstrdup(const char *s) {
71 static inline int xvasprintf(char **strp, const char *fmt, va_list ap) {
74 int result = vsnprintf(buf, sizeof(buf), fmt, ap);
82 int result = vasprintf(strp, fmt, ap);
92 static inline int xasprintf(char **strp, const char *fmt, ...) ATTR_FORMAT(printf, 2, 3);
93 static inline int xasprintf(char **strp, const char *fmt, ...) {
96 int result = xvasprintf(strp, fmt, ap);
101 // Zero out a block of memory containing sensitive information using whatever secure
102 // erase function is available on the platform (or an unreliable fallback if none are).
103 // The pointer must not be NULL. Length can be zero, in which case the call is a noop.
104 static inline void memzero(void *buf, size_t buflen) ATTR_NONNULL;
105 static inline void memzero(void *buf, size_t buflen) {
112 #if defined(HAVE_EXPLICIT_BZERO)
113 explicit_bzero(buf, buflen);
114 #elif defined(HAVE_EXPLICIT_MEMSET)
115 explicit_memset(buf, 0, buflen);
116 #elif defined(HAVE_MEMSET_S)
117 errno_t err = memset_s(buf, buflen, 0, buflen);
119 #elif defined(HAVE_WINDOWS)
120 SecureZeroMemory(buf, buflen);
122 volatile uint8_t *p = buf;
131 // Zero out a buffer of size `len` located at `ptr` and free() it.
132 // Does nothing if called on NULL.
133 static inline void xzfree(void *ptr, size_t len) {
140 // Zero out a NULL-terminated string using memzero() and then free it.
141 // Does nothing if called on NULL.
142 static inline void free_string(char *str) {
144 xzfree(str, strlen(str));
148 #endif // TINC_XALLOC_H