LMMP 4.3.0
Lamina High-Precision Arithmetic Library
载入中...
搜索中...
未找到
memory.c
浏览该文件的文档.
1/**
2 * Copyright (C) 2026 HJimmyK (Jericho Knox)
3 *
4 * This file is part of LMMP.
5 *
6 * LMMP is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 3 of
9 * the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library. If not, see
18 * <https://www.gnu.org/licenses/>.
19 *
20 * SPDX-License-Identifier: LGPL-3.0-or-later
21 */
22
23#include "mparam.h"
24#include "impl/tmp_alloc.h"
25#include "lmmp/lmmpn.h"
26
27#undef lmmp_alloc
28#undef lmmp_realloc
29#undef lmmp_free
30#undef lmmp_stack_alloc
31#undef lmmp_stack_free
32#undef lmmp_leak_tracker
33#define HSIZE sizeof(void*)
34
36 .alloc = (lmmp_heap_alloc_fn)malloc,
37 .free = (lmmp_heap_free_fn)free,
38 .realloc = (lmmp_realloc_fn)realloc,
39};
40
41#define heap_alloc_func global_heap.alloc
42#define heap_free_func global_heap.free
43#define realloc_func global_heap.realloc
44
46
48 .stack_begin = NULL,
49 .stack_end = NULL,
50 .stack_top = NULL,
51 .pool_begin = NULL,
52 .pool_top = NULL,
53 .remain = 0,
54 .capacity = 0,
55};
56
58 if (lmmp_tmpmem_ctx.stack_begin != NULL) {
60 if (lmmp_tmpmem_ctx.pool_begin != NULL)
67 lmmp_tmpmem_ctx.remain = 0; // Reset remain to 0
68 lmmp_tmpmem_ctx.capacity = 0; // Reset capacity to 0
69 return 0;
70 } else {
71 return -1;
72 }
73}
74
75int lmmp_stack_init(size_t size) {
76 if (lmmp_tmpmem_ctx.stack_begin != NULL) {
77 return -1;
78 } else {
80 if (lmmp_tmpmem_ctx.stack_begin == NULL) {
81 lmmp_abort(LMMP_ERROR_MEMORY_ALLOC_FAILURE, "Failed to allocate stack memory", __func__, __LINE__);
82 }
85 if (size > LMMP_MAX_ALIGN) {
86 // 只有当size大于最大对齐单位时,才分配缓冲池
88 if (lmmp_tmpmem_ctx.pool_begin == NULL) {
89 heap_free_func(lmmp_tmpmem_ctx.stack_begin); // Free old stack memory
90 lmmp_abort(LMMP_ERROR_MEMORY_ALLOC_FAILURE, "Failed to allocate pool memory", __func__, __LINE__);
91 }
95 }
96 return 0;
97 }
98}
99
101 if (heap == NULL)
102 return;
104#if LMMP_DEBUG_MEMORY_LEAK == 1
105 lmmp_leak_tracker(__func__, __LINE__); // Check for memory leaks before setting new allocator
106#endif
107 global_heap = *heap;
109}
110
111#if LMMP_DEBUG_MEMORY_CHECK == 1
112typedef struct {
113 uint64_t magic; // 魔数,用于验证有效性
114 size_t user_size; // 用户请求的大小
115 size_t total_size; // 总分配大小(含头部、用户内存、额外内存)
116 size_t extra_size; // 额外分配的内存大小
117 const char* func; // 分配发生的函数名
118 int line; // 分配发生的行号
119 uint32_t guard; // 尾哨兵
120} mem_header;
121
122#define MEM_MAGIC 0xDEADBEEFDEADBEEFULL // deadbeef
123#define MEM_GUARD 0xDEADBEEFUL // deadbeef
124#define EXTRA_MEM_PATTERN 0xAA // 额外内存填充模式
125
126#define ALIGNMENT LMMP_MAX_ALIGN
127
128static inline size_t align_up(size_t size) {
129 return (size + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
130}
131
132/**
133 * @brief 找到指定模式的连续内存区域,并记录起始和结束位置。
134 */
135static inline void find_corruption_range(
136 const char* data,
137 unsigned char pattern,
138 size_t len,
139 int* first,
140 int* last,
141 int* count
142) {
143 *first = -1;
144 *last = -1;
145 *count = 0;
146
147 for (size_t i = 0; i < len; i++) {
148 if ((unsigned char)data[i] != pattern) {
149 (*count)++;
150 if (*first == -1)
151 *first = (int)i;
152 *last = (int)i;
153 }
154 }
155}
156
157/**
158 * @brief 检查额外内存区域是否被修改。
159 */
160static inline int check_extra_memory_overflow(mem_header* hdr, void* user_ptr, const char* check_func, int check_line) {
161 if (!hdr || !user_ptr || hdr->extra_size == 0)
162 return 0;
163
164 size_t aligned_user_size = align_up(hdr->user_size);
165 char* extra_start = (char*)user_ptr + aligned_user_size;
166
167 int first, last, count;
168 find_corruption_range(extra_start, EXTRA_MEM_PATTERN, hdr->extra_size, &first, &last, &count);
169
170 if (count > 0) {
171 char error_buf[640];
172 int offset = 0;
173 const int buf_size = sizeof(error_buf);
174
175#define SAFE_APPEND(...) \
176 do { \
177 if (offset < buf_size) { \
178 int n = snprintf(error_buf + offset, (size_t)(buf_size - offset), __VA_ARGS__); \
179 if (n > 0) \
180 offset += n; \
181 } \
182 } while (0)
183
184 SAFE_APPEND("Memory overflow (extra memory corruption) detected!%s", "\n");
185 SAFE_APPEND("Memory header:%s", "\n");
186 SAFE_APPEND(" allocated at: [%s]:%d\n", hdr->func, hdr->line);
187 SAFE_APPEND(" checked at: [%s]:%d\n", check_func, check_line);
188 SAFE_APPEND(" user size: %zu bytes\n", hdr->user_size);
189 SAFE_APPEND(" extra size: %zu bytes (%.0f%% of user size)\n", hdr->extra_size,
190 LMMP_MEMORY_MORE_ALLOC_TIMES * 10.0);
191 SAFE_APPEND(" user ptr: %p\n", user_ptr);
192 SAFE_APPEND(" extra memory: %p to %p\n", (void*)extra_start, (void*)(extra_start + hdr->extra_size - 1));
193 SAFE_APPEND(" corrupted range: offset %d to %d (total %d bytes)\n", first, last, count);
194 SAFE_APPEND("Likely cause: Buffer overflow beyond the end of the memory.%s", "\n");
195
196 error_buf[buf_size - 1] = '\0';
197 lmmp_abort(LMMP_ERROR_OUT_OF_BOUNDS, error_buf, check_func, check_line);
198 return 1;
199 }
200 return 0;
201}
202
203/**
204 * @brief 检查内存块的完整性(包括头尾和额外内存区域)。
205 */
206static inline int check_memory_block_integrity(mem_header* hdr, void* user_ptr, const char* check_func, int check_line) {
207 if (!hdr || !user_ptr)
208 return 0;
209
210 if (hdr->magic != MEM_MAGIC || hdr->guard != MEM_GUARD) {
211 char error_buf[240];
212 snprintf(error_buf, sizeof(error_buf),
213 "Memory header corruption detected!\n"
214 " Magic: 0x%016llx (expected 0x%016llx)\n"
215 " Guard: 0x%08lx (expected 0x%08lx)\n"
216 "Possible overflow or underflow or invalid pointer.",
217 hdr->magic, MEM_MAGIC, (unsigned long)hdr->guard, MEM_GUARD);
218 lmmp_abort(LMMP_ERROR_MEMORY_FREE_FAILURE, error_buf, check_func, check_line);
219 return 1;
220 }
221
222 return check_extra_memory_overflow(hdr, user_ptr, check_func, check_line);
223}
224
225/**
226 * @brief 调试版 malloc
227 * @param size 要分配的内存大小
228 * @param func 分配内存的函数名
229 * @param line 分配内存的行号
230 * @return 分配的内存块的指针
231 */
232static inline void* lmmp_alloc_debug(size_t size, const char* func, int line) {
233 if (size == 0) {
234 lmmp_abort(LMMP_ERROR_MEMORY_ALLOC_FAILURE, "Allocating zero bytes is not allowed.", func, line);
235 return NULL;
236 }
237
238 size_t extra_size = (size * LMMP_MEMORY_MORE_ALLOC_TIMES) / 10;
239 extra_size = align_up(extra_size);
240
241 size_t header_size = align_up(sizeof(mem_header));
242 size_t aligned_user_size = align_up(size);
243 size_t total_size = header_size + aligned_user_size + extra_size;
244
245 void* base = heap_alloc_func(total_size);
246 if (!base) {
247 char msg[128];
248 snprintf(msg, sizeof(msg), "Memory allocation failed (size: %zu bytes, extra: %zu bytes)", size, extra_size);
250 return NULL;
251 }
252
253 mem_header* hdr = (mem_header*)base;
254 void* user_ptr = (char*)base + header_size;
255 void* extra_mem = (char*)user_ptr + aligned_user_size;
256
257 hdr->magic = MEM_MAGIC;
258 hdr->user_size = size;
259 hdr->total_size = total_size;
260 hdr->extra_size = extra_size;
261 hdr->func = func;
262 hdr->line = line;
263 hdr->guard = MEM_GUARD;
264
265 memset(extra_mem, EXTRA_MEM_PATTERN, extra_size);
266
267 return user_ptr;
268}
269
270/**
271 * @brief 调试版 free
272 * @param ptr 指向要释放的内存块的指针
273 * @param func 分配内存的函数名
274 * @param line 分配内存的行号
275 */
276static inline void lmmp_free_debug(void* ptr, const char* func, int line) {
277 if (!ptr)
278 return;
279
280 size_t header_size = align_up(sizeof(mem_header));
281 mem_header* hdr = (mem_header*)((char*)ptr - header_size);
282
283 check_memory_block_integrity(hdr, ptr, func, line);
284
285 heap_free_func(hdr);
286}
287
288/**
289 * @brief 调试版 realloc
290 * @param ptr 指向要重新分配的内存块的指针
291 * @param new_size 新的内存大小
292 * @param func 分配内存的函数名
293 * @param line 分配内存的行号
294 * @return 新分配的内存块的指针
295 */
296static inline void* lmmp_realloc_debug(void* ptr, size_t new_size, const char* func, int line) {
297 if (!ptr)
298 return lmmp_alloc_debug(new_size, func, line);
299 if (new_size == 0) {
300 lmmp_abort(LMMP_ERROR_MEMORY_ALLOC_FAILURE, "Reallocating zero bytes is not allowed.", func, line);
301 return NULL;
302 }
303
304 size_t header_size = align_up(sizeof(mem_header));
305 mem_header* old_hdr = (mem_header*)((char*)ptr - header_size);
306
307 check_memory_block_integrity(old_hdr, ptr, func, line);
308
309 void* new_ptr = lmmp_alloc_debug(new_size, func, line);
310 if (!new_ptr)
311 return NULL;
312
313 size_t copy_size = (old_hdr->user_size < new_size) ? old_hdr->user_size : new_size;
314 memcpy(new_ptr, ptr, copy_size);
315
316 lmmp_free_debug(ptr, func, line);
317 return new_ptr;
318}
319
320#undef SAFE_APPEND
321#undef MEM_MAGIC
322#undef MEM_GUARD
323#undef ALIGNMENT
324#undef EXTRA_MEM_PATTERN
325
326#endif // LMMP_DEBUG_MEMORY_CHECK == 1
327
328int lmmp_alloc_count(int cnt) {
329 if (cnt != 0) {
330 int new_cnt = cnt;
331 cnt = heap_alloc_count;
332 heap_alloc_count = new_cnt;
333 return cnt;
334 }
335 return heap_alloc_count;
336}
337
338void lmmp_leak_tracker(const char* func, int line) {
339 char msg[360] = {0};
340 int offset = 0;
341 const int max_len = sizeof(msg) - 1;
342 bool t = false;
343 if (heap_alloc_count != 0) {
344 offset +=
345 snprintf(msg + offset, max_len - offset, "Heap allocations not freed: %d block(s);\n", heap_alloc_count);
346 t = true;
347 }
349 offset += snprintf(msg + offset, max_len - offset,
350 "Default stack allocator is not empty. top: %p, begin: %p, end: %p;\n",
352 t = true;
353 }
355 offset += snprintf(msg + offset, max_len - offset,
356 "Default pool allocator is not empty. top: %p, begin: %p; remain: %zu bytes, capacity: %zu "
357 "bytes;\n",
360 t = true;
361 }
362 if (t) {
363 lmmp_abort(LMMP_ERROR_MEMORY_LEAK, msg, func, line);
364 }
365}
366
367#if LMMP_DEBUG_MEMORY_CHECK == 1
368void* lmmp_alloc(size_t size, const char* func, int line) {
369 void* ret = lmmp_alloc_debug(size, func, line);
370#if LMMP_DEBUG_MEMORY_LEAK == 1
372#endif
373 return ret;
374}
375#else
376static inline void lmmp_memory_abort(size_t size, const char* func, int line) {
377 char msg[64];
378 snprintf(msg, sizeof(msg), "Memory allocation failed (size: %zu bytes)", size);
380}
381
382void* lmmp_alloc(size_t size) {
383#if LMMP_DEBUG_PARAM_ASSERT_CHECK == 1
384 if (size == 0) {
385 lmmp_abort(LMMP_ERROR_MEMORY_ALLOC_FAILURE, "Allocating zero bytes is not allowed.", __func__, __LINE__);
386 return NULL;
387 }
388#endif // LMMP_DEBUG_PARAM_ASSERT_CHECK == 1
389 void* ret = heap_alloc_func(size);
390 if (ret == NULL)
391 lmmp_memory_abort(size, __func__, __LINE__);
392#if LMMP_DEBUG_MEMORY_LEAK == 1
394#endif
395 return ret;
396}
397#endif
398
399#if LMMP_DEBUG_MEMORY_CHECK == 1
400void* lmmp_realloc(void* oldptr, size_t new_size, const char* func, int line) {
401 void* ret = lmmp_realloc_debug(oldptr, new_size, func, line);
402#if LMMP_DEBUG_MEMORY_LEAK == 1
403 if (oldptr == NULL)
405#endif
406 return ret;
407}
408#else
409void* lmmp_realloc(void* oldptr, size_t new_size) {
410#if LMMP_DEBUG_PARAM_ASSERT_CHECK == 1
411 if (new_size == 0) {
412 lmmp_abort(LMMP_ERROR_MEMORY_ALLOC_FAILURE, "Reallocating zero bytes is not allowed.", __func__, __LINE__);
413 return NULL;
414 }
415#endif // LMMP_DEBUG_PARAM_ASSERT_CHECK == 1
416 void* ret = realloc_func(oldptr, new_size);
417 if (ret == NULL) {
418 lmmp_memory_abort(new_size, __func__, __LINE__);
419 }
420#if LMMP_DEBUG_MEMORY_LEAK == 1
421 if (oldptr == NULL)
423#endif
424 return ret;
425}
426#endif // LMMP_DEBUG_MEMORY_CHECK == 1
427
428#if LMMP_DEBUG_MEMORY_CHECK == 1
429void lmmp_free(void* ptr, const char* func, int line) {
430 lmmp_free_debug(ptr, func, line);
431#if LMMP_DEBUG_MEMORY_LEAK == 1
432 if (ptr != NULL)
434#endif
435}
436#else
437void lmmp_free(void* ptr) {
438 heap_free_func(ptr);
439#if LMMP_DEBUG_MEMORY_LEAK == 1
440 if (ptr != NULL)
442#endif
443}
444#endif // LMMP_DEBUG_MEMORY_CHECK == 1
#define LMMP_DEFAULT_STACK_SIZE
Copyright (C) 2026 HJimmyK (Jericho Knox)
void * lmmp_realloc(void *ptr, size_t size)
内存重分配函数(调用lmmp_realloc_fn)
uint8_t mp_byte_t
定义 lmmp.h:91
void lmmp_set_heap_allocator(const lmmp_heap_allocator_t *heap)
设置 LMMP 全局堆内存分配函数
void *(*) lmmp_heap_alloc_fn(size_t size)
定义 lmmp.h:235
#define LMMP_MAX_ALIGN
定义 lmmp.h:100
void(*) lmmp_heap_free_fn(void *ptr)
定义 lmmp.h:236
void * lmmp_alloc(size_t size)
内存分配函数(调用lmmp_heap_alloc_fn)
void lmmp_abort(lmmp_error_t type, const char *msg, const char *func, int line)
LMMP 全局退出函数,内部错误或断言失败时调用,若设置了全局退出函数,则会调用该函数,否则会调用默认的退出函数。
int lmmp_stack_deinit(void)
LMMP 全局栈释放函数(通常不需要手动调用)
int lmmp_stack_init(size_t size)
LMMP 全局栈初始化函数(通常不需要手动调用)
void lmmp_free(void *ptr)
内存释放函数(调用lmmp_heap_free_fn)
void lmmp_global_init(void)
全局初始化函数(线程局部的)
void lmmp_global_deinit(void)
全局释放函数(线程局部的)
#define LMMP_THREAD_LOCAL
定义 lmmp.h:114
void *(*) lmmp_realloc_fn(void *ptr, size_t size)
定义 lmmp.h:237
@ LMMP_ERROR_MEMORY_ALLOC_FAILURE
定义 lmmp.h:285
@ LMMP_ERROR_MEMORY_FREE_FAILURE
定义 lmmp.h:286
@ LMMP_ERROR_MEMORY_LEAK
定义 lmmp.h:288
@ LMMP_ERROR_OUT_OF_BOUNDS
定义 lmmp.h:287
#define lmmp_leak_tracker
定义 lmmp.h:440
int lmmp_alloc_count(int cnt)
堆内存分配计数器(线程局部)
static __thread int heap_alloc_count
#define heap_alloc_func
#define realloc_func
#define heap_free_func
static void lmmp_memory_abort(size_t size, const char *func, int line)
#define t
__thread lmmp_heap_allocator_t global_heap
__thread lmmp_memory_ctx lmmp_tmpmem_ctx
Copyright (C) 2026 HJimmyK (Jericho Knox)