2024-03-24 18:24:04 +05:30
|
|
|
/*
|
|
|
|
* safe_mem.h
|
|
|
|
*
|
|
|
|
* A header-only library (macro collection) for safer memory management.
|
|
|
|
*
|
2024-03-27 01:42:37 +05:30
|
|
|
* 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.
|
2024-03-31 22:12:10 +05:30
|
|
|
*
|
|
|
|
* Author: Intel A80486DX2-66
|
|
|
|
* License: Creative Commons Zero 1.0 Universal
|
2024-03-24 18:24:04 +05:30
|
|
|
*/
|
|
|
|
|
|
|
|
#ifndef _SAFE_MEM_H
|
|
|
|
#define _SAFE_MEM_H
|
|
|
|
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
2024-03-24 23:34:19 +05:30
|
|
|
typedef unsigned char byte;
|
|
|
|
|
2024-03-24 18:24:04 +05:30
|
|
|
#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 */ \
|
2024-03-24 23:34:19 +05:30
|
|
|
malloc((size_t) (nmemb) * (size_t) (size))
|
2024-03-24 18:24:04 +05:30
|
|
|
|
|
|
|
/* secure_erase(dest, count): erases memory explicitly */
|
2024-03-27 22:27:27 +05:30
|
|
|
#if (defined(__OpenBSD__) || defined(__FreeBSD__)) && !defined(SAFE_MEM_OLD_BSD)
|
2024-03-24 18:24:04 +05:30
|
|
|
# define NO_SECURE_ERASE_WARRANTY 0
|
|
|
|
# define SECURE_ERASE_WARRANTY "OpenBSD/FreeBSD: explicit_bzero"
|
|
|
|
|
|
|
|
# include <strings.h>
|
|
|
|
# define secure_erase explicit_bzero
|
|
|
|
#elif defined(_WIN32)
|
|
|
|
# define NO_SECURE_ERASE_WARRANTY 0
|
|
|
|
# define SECURE_ERASE_WARRANTY "Microsoft Windows: SecureZeroMemory"
|
|
|
|
|
|
|
|
# include <windows.h>
|
|
|
|
# define secure_erase SecureZeroMemory
|
2024-03-24 20:39:40 +05:30
|
|
|
#elif __STDC_LIB_EXT1__
|
2024-03-24 18:24:04 +05:30
|
|
|
# define NO_SECURE_ERASE_WARRANTY 0
|
|
|
|
# define SECURE_ERASE_WARRANTY "C11+: memset_s"
|
|
|
|
|
2024-03-24 19:59:04 +05:30
|
|
|
# include <string.h>
|
2024-03-24 23:34:19 +05:30
|
|
|
# define secure_erase(dest, count) memset_s((dest), (count), 0, (count))
|
2024-03-24 18:24:04 +05:30
|
|
|
#else
|
|
|
|
# define NO_SECURE_ERASE_WARRANTY 1
|
|
|
|
|
2024-03-25 02:58:11 +05:30
|
|
|
# include <stdint.h>
|
2024-03-24 19:59:04 +05:30
|
|
|
|
2024-03-24 18:24:04 +05:30
|
|
|
# define secure_erase(dest, count) do { \
|
2024-03-24 23:34:19 +05:30
|
|
|
uintptr_t max = (uintptr_t) ((count) / sizeof(byte)); \
|
|
|
|
for (size_t i = 0; i < max; i++) \
|
|
|
|
*((byte*) (dest) + i) = 0; \
|
2024-03-24 18:24:04 +05:30
|
|
|
} while (0)
|
|
|
|
#endif
|
|
|
|
|
|
|
|
#endif /* _SAFE_MEM_H */
|