16#ifndef __LAMMP_SAFE_MEMORY_H__
17#define __LAMMP_SAFE_MEMORY_H__
37#define MEM_MAGIC 0xDEADBEEFDEADBEEFULL
38#define MEM_GUARD 0xDEADBEEFUL
39#define EXTRA_MEM_PATTERN 0xAA
41#define ALIGNMENT LAMMP_MAX_ALIGN
52 unsigned char pattern,
62 for (
size_t i = 0; i < len; i++) {
63 if ((
unsigned char)data[i] != pattern) {
80 char* extra_start = (
char*)user_ptr + aligned_user_size;
82 int first, last, count;
88 const int buf_size =
sizeof(error_buf);
90#define SAFE_APPEND(...) \
92 if (offset < buf_size) { \
93 int n = snprintf(error_buf + offset, (size_t)(buf_size - offset), __VA_ARGS__); \
99 SAFE_APPEND(
"Memory overflow (extra memory corruption) detected!%s",
"\n");
102 SAFE_APPEND(
" checked at: [%s]:%d\n", check_func, check_line);
107 SAFE_APPEND(
" extra memory: %p to %p\n", (
void*)extra_start, (
void*)(extra_start + hdr->
extra_size - 1));
108 SAFE_APPEND(
" corrupted range: offset %d to %d (total %d bytes)\n", first, last, count);
109 SAFE_APPEND(
"Likely cause: Buffer overflow beyond the end of the memory.%s",
"\n");
111 error_buf[buf_size - 1] =
'\0';
122 if (!hdr || !user_ptr)
127 snprintf(error_buf,
sizeof(error_buf),
128 "Memory header corruption detected!\n"
129 " Magic: 0x%016llx (expected 0x%016llx)\n"
130 " Guard: 0x%08lx (expected 0x%08lx)\n"
131 "Possible overflow or underflow or invalid pointer.",
161 snprintf(
msg,
sizeof(
msg),
"Memory allocation failed (size: %zu bytes, extra: %zu bytes)", size, extra_size);
171 hdr->user_size = size;
172 hdr->total_size = total_size;
173 hdr->extra_size = extra_size;
237#undef EXTRA_MEM_PATTERN
void lmmp_abort(lmmp_error_t type, const char *msg, const char *func, int line)
LAMMP 全局退出函数,内部错误或断言失败时调用,若设置了全局退出函数,则会调用该函数,否则会调用默认的退出函数。
#define LAMMP_MEMORY_MORE_ALLOC_TIMES
@ LAMMP_ERROR_MEMORY_ALLOC_FAILURE
@ LAMMP_ERROR_MEMORY_FREE_FAILURE
@ LAMMP_ERROR_OUT_OF_BOUNDS
static void * lmmp_realloc_debug(void *ptr, size_t new_size, const char *func, int line)
调试版 realloc
static void find_corruption_range(const char *data, unsigned char pattern, size_t len, int *first, int *last, int *count)
找到指定模式的连续内存区域,并记录起始和结束位置。
static int check_extra_memory_overflow(mem_header *hdr, void *user_ptr, const char *check_func, int check_line)
检查额外内存区域是否被修改。
#define EXTRA_MEM_PATTERN
static size_t align_up(size_t size)
static int check_memory_block_integrity(mem_header *hdr, void *user_ptr, const char *check_func, int check_line)
检查内存块的完整性(包括头尾和额外内存区域)。
static void * lmmp_alloc_debug(size_t size, const char *func, int line)
调试版 malloc
static void lmmp_free_debug(void *ptr, const char *func, int line)
调试版 free