/* * safe_mem.h * * A header-only library (macro collection) for safer memory management. * * NOTE: Declare macro SAFE_MEM_OLD_BSD when compiling if you're using OpenBSD * version earlier than 5.5 or FreeBSD version earlier than 11.0. * * NOTE: See https://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob_plain; * f=lib/memset_explicit.c;hb=refs/heads/stable-202301 * * Author: Intel A80486DX2-66 * License: Creative Commons Zero 1.0 Universal */ #ifndef _SAFE_MEM_H #define _SAFE_MEM_H #define __STDC_WANT_LIB_EXT1__ 1 #include typedef unsigned char byte; #define SAFE_FREE_ERROR_HOOK /* user-defined */ #define safe_free(ptr) do { \ /* prevents NULL-freeing and double freeing */ \ if (ptr != NULL) { \ free(ptr); \ ptr = NULL; \ } else { SAFE_FREE_ERROR_HOOK; } \ } while (0) #define precise_malloc(nmemb, size) \ /* prevents incorrect casting */ \ malloc((size_t) (nmemb) * (size_t) (size)) /* secure_erase(dest, count): erases memory explicitly */ #if (defined(__OpenBSD__) || defined(__FreeBSD__)) && !defined(SAFE_MEM_OLD_BSD) # define NO_SECURE_ERASE_WARRANTY 0 # define SECURE_ERASE_WARRANTY "OpenBSD/FreeBSD: explicit_bzero" # include # define secure_erase explicit_bzero #elif defined(_WIN32) # define NO_SECURE_ERASE_WARRANTY 0 # define SECURE_ERASE_WARRANTY "Microsoft Windows: SecureZeroMemory" # include # define secure_erase SecureZeroMemory #elif __STDC_LIB_EXT1__ # define NO_SECURE_ERASE_WARRANTY 0 # define SECURE_ERASE_WARRANTY "C11+: memset_s" # include # define secure_erase(dest, count) memset_s((dest), (count), 0, (count)) #else # define NO_SECURE_ERASE_WARRANTY 1 # include # define secure_erase(dest, count) do { \ uintptr_t max = (uintptr_t) ((count) / sizeof(byte)); \ for (size_t i = 0; i < max; i++) \ *((byte*) (dest) + i) = 0; \ } while (0) #endif #endif /* _SAFE_MEM_H */