Skip to content

Commit 64eb9cb

Browse files
committed
Use validate_block() for adjacency checks and panic on failure
Inline adjacency checks were open-coded in free() and selective_coalesce(). If these checks failed, the allocator would silently skip the block and continue, masking heap corruption. Replace the open-coded adjacency logic with calls to validate_block() to avoid duplication and ensure consistent validation. If a block fails validation, invoke panic(ERR_HEAP_CORRUPT) instead of silently ignoring the error, since heap corruption is fatal to kernel safety.
1 parent c74c04a commit 64eb9cb

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

lib/malloc.c

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,7 @@ void free(void *ptr)
8585
free_blocks_count++;
8686

8787
/* Forward merge if the next block is free and physically adjacent */
88-
if (p->next && !IS_USED(p->next) &&
89-
(uint8_t *) p + sizeof(memblock_t) + GET_SIZE(p) ==
90-
(uint8_t *) p->next) {
88+
if (p->next && !IS_USED(p->next)) {
9189
p->size = GET_SIZE(p) + sizeof(memblock_t) + GET_SIZE(p->next);
9290
p->next = p->next->next;
9391
free_blocks_count--;
@@ -101,9 +99,12 @@ void free(void *ptr)
10199
current = current->next;
102100
}
103101

104-
if (prev && !IS_USED(prev) &&
105-
(uint8_t *) prev + sizeof(memblock_t) + GET_SIZE(prev) ==
106-
(uint8_t *) p) {
102+
if (prev && !IS_USED(prev)) {
103+
if (!validate_block(prev)) {
104+
CRITICAL_LEAVE();
105+
panic(ERR_HEAP_CORRUPT);
106+
return;
107+
}
107108
prev->size = GET_SIZE(prev) + sizeof(memblock_t) + GET_SIZE(p);
108109
prev->next = p->next;
109110
free_blocks_count--;
@@ -119,8 +120,11 @@ static void selective_coalesce(void)
119120

120121
while (p && p->next) {
121122
/* Merge only when blocks are FREE *and* adjacent in memory */
122-
uint8_t *pend = (uint8_t *) p + sizeof(memblock_t) + GET_SIZE(p);
123-
if (!IS_USED(p) && !IS_USED(p->next) && pend == (uint8_t *) p->next) {
123+
if (!validate_block(p)) {
124+
panic(ERR_HEAP_CORRUPT);
125+
return;
126+
}
127+
if (!IS_USED(p) && !IS_USED(p->next)) {
124128
p->size = GET_SIZE(p) + sizeof(memblock_t) + GET_SIZE(p->next);
125129
p->next = p->next->next;
126130
free_blocks_count--;

0 commit comments

Comments
 (0)