19#ifndef __LAMMP_SAFE_MEMORY_H__
20#define __LAMMP_SAFE_MEMORY_H__
39#define MEM_MAGIC 0xDEADBEEF
40#define EXTRA_MEM_PATTERN 0xAA
42#define ALIGNMENT LAMMP_MAX_ALIGN
48 unsigned char pattern,
58 for (
size_t i = 0; i < len; i++) {
59 if ((
unsigned char)data[i] != pattern) {
74 char* extra_start = (
char*)user_ptr + aligned_user_size;
77 int first, last, count;
83 const int buf_size =
sizeof(error_buf);
85#define SAFE_APPEND(...) \
87 if (offset < buf_size) { \
88 int n = snprintf(error_buf + offset, (size_t)(buf_size - offset), __VA_ARGS__); \
94 SAFE_APPEND(
"Memory overflow (extra memory corruption) detected!%s",
"\n");
97 SAFE_APPEND(
" checked at: [%s]:%d\n", check_func, check_line);
102 SAFE_APPEND(
" extra memory: %p to %p\n", (
void*)extra_start, (
void*)(extra_start + hdr->
extra_size - 1));
103 SAFE_APPEND(
" corrupted range: offset %d to %d (total %d bytes)\n", first, last, count);
104 SAFE_APPEND(
"Likely cause: Buffer overflow beyond the end of the memory.%s",
"\n");
106 error_buf[buf_size - 1] =
'\0';
115 if (!hdr || !user_ptr)
121 snprintf(error_buf,
sizeof(error_buf),
122 "Memory header corruption detected! Magic: 0x%08x (expected 0x%08x)\n"
123 "Possible underflow or invalid pointer.",
143 size_t aligned_user_size =
align_up(size);
145 size_t total_size = header_size + aligned_user_size + extra_size;
150 snprintf(msg,
sizeof(msg),
"Memory allocation failed (size: %zu bytes, extra: %zu bytes)", size, extra_size);
155 memset(base, 0, total_size);
158 void* user_ptr = (
char*)base + header_size;
159 void* extra_mem = (
char*)user_ptr + aligned_user_size;
169 memset(user_ptr, 0xCD, aligned_user_size);
212 memcpy(new_ptr, ptr, copy_size);
227#define CHECK_OVERFLOW(ptr) check_memory_overflow(ptr, __func__, __LINE__)
232#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)
static void find_corruption_range(const char *data, unsigned char pattern, size_t len, int *first, int *last, int *count)
#define EXTRA_MEM_PATTERN
static size_t align_up(size_t size)
static int check_memory_overflow(void *ptr, const char *func, int line)
static void * lmmp_alloc_debug(size_t size, const char *func, int line)
static void lmmp_free_debug(void *ptr, const char *func, int line)
static int check_extra_memory_overflow(MemHeader *hdr, void *user_ptr, const char *check_func, int check_line)
static int check_memory_block_integrity(MemHeader *hdr, void *user_ptr, const char *check_func, int check_line)