Ruby 4.1.0dev (2026-08-28 revision 5eb9a6925b805a17dced976d5b741afe5086aab1)
allocator_debug.h
1#ifndef PRISM_INTERNAL_ALLOCATOR_DEBUG_H
2#define PRISM_INTERNAL_ALLOCATOR_DEBUG_H
3
4#include <string.h>
5#include <stdio.h>
6#include <stdlib.h>
7
8static inline void *
9pm_allocator_debug_malloc(size_t size) {
10 size_t *memory = xmalloc(size + sizeof(size_t));
11 memory[0] = size;
12 return memory + 1;
13}
14
15static inline void *
16pm_allocator_debug_calloc(size_t nmemb, size_t size) {
17 size_t total_size = nmemb * size;
18 void *ptr = pm_allocator_debug_malloc(total_size);
19 memset(ptr, 0, total_size);
20 return ptr;
21}
22
23static inline void *
24pm_allocator_debug_realloc(void *ptr, size_t size) {
25 if (ptr == NULL) {
26 return pm_allocator_debug_malloc(size);
27 }
28
29 size_t *memory = (size_t *)ptr;
30 void *raw_memory = memory - 1;
31 memory = (size_t *)xrealloc(raw_memory, size + sizeof(size_t));
32 memory[0] = size;
33 return memory + 1;
34}
35
36static inline void
37pm_allocator_debug_free(void *ptr) {
38 if (ptr != NULL) {
39 size_t *memory = (size_t *)ptr;
40 xfree(memory - 1);
41 }
42}
43
44static inline void
45pm_allocator_debug_free_sized(void *ptr, size_t old_size) {
46 if (ptr != NULL) {
47 size_t *memory = (size_t *)ptr;
48 if (old_size != memory[-1]) {
49 fprintf(stderr, "[BUG] buffer %p was allocated with size %lu but freed with size %lu\n", ptr, memory[-1], old_size);
50 abort();
51 }
52 xfree_sized(memory - 1, old_size + sizeof(size_t));
53 }
54}
55
56static inline void *
57pm_allocator_debug_realloc_sized(void *ptr, size_t size, size_t old_size) {
58 if (ptr == NULL) {
59 if (old_size != 0) {
60 fprintf(stderr, "[BUG] realloc_sized called with NULL pointer and old size %lu\n", old_size);
61 abort();
62 }
63 return pm_allocator_debug_malloc(size);
64 }
65
66 size_t *memory = (size_t *)ptr;
67 if (old_size != memory[-1]) {
68 fprintf(stderr, "[BUG] buffer %p was allocated with size %lu but realloced with size %lu\n", ptr, memory[-1], old_size);
69 abort();
70 }
71 return pm_allocator_debug_realloc(ptr, size);
72}
73
74#undef xmalloc
75#undef xrealloc
76#undef xcalloc
77#undef xfree
78#undef xrealloc_sized
79#undef xfree_sized
80
81#define xmalloc pm_allocator_debug_malloc
82#define xrealloc pm_allocator_debug_realloc
83#define xcalloc pm_allocator_debug_calloc
84#define xfree pm_allocator_debug_free
85#define xrealloc_sized pm_allocator_debug_realloc_sized
86#define xfree_sized pm_allocator_debug_free_sized
87
88#endif
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define xrealloc
Old name of ruby_xrealloc.
Definition xmalloc.h:56
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53