Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sys/net/gnrc_pktbuf_static: add double free detection #20974

Merged
merged 2 commits into from
Nov 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions sys/net/gnrc/pktbuf_static/gnrc_pktbuf_static.c
Original file line number Diff line number Diff line change
Expand Up @@ -240,12 +240,13 @@ gnrc_pktsnip_t *gnrc_pktbuf_start_write(gnrc_pktsnip_t *pkt)
}

#ifdef DEVELHELP
#ifdef MODULE_OD
static inline void _print_chunk(void *chunk, size_t size, int num)
{
printf("=========== chunk %3i (%-10p size: %4" PRIuSIZE ") ===========\n", num, chunk,
size);
#ifdef MODULE_OD
od_hex_dump(chunk, size, OD_WIDTH_DEFAULT);
#endif
}

static inline void _print_ptr(_unused_t *ptr)
Expand All @@ -266,11 +267,9 @@ static inline void _print_unused(_unused_t *ptr)
_print_ptr(ptr->next);
printf(", size: %4u) ~\n", ptr->size);
}
#endif

void gnrc_pktbuf_stats(void)
{
#ifdef MODULE_OD
_unused_t *ptr = _first_unused;
uint8_t *chunk = &_static_buf[0];
int count = 0;
Expand Down Expand Up @@ -306,9 +305,6 @@ void gnrc_pktbuf_stats(void)
if (chunk <= &_static_buf[CONFIG_GNRC_PKTBUF_SIZE - 1]) {
_print_chunk(chunk, &_static_buf[CONFIG_GNRC_PKTBUF_SIZE] - chunk, count);
}
#else
DEBUG("pktbuf: needs od module\n");
#endif
}
#endif

Expand Down Expand Up @@ -438,6 +434,10 @@ static void *_pktbuf_alloc(size_t size)
#endif
assert(0);
}
if (CONFIG_GNRC_PKTBUF_CHECK_USE_AFTER_FREE) {
/* clear out canary */
memset(ptr, ~CANARY, size);
}

return (void *)ptr;
}
Expand Down Expand Up @@ -469,6 +469,13 @@ void gnrc_pktbuf_free_internal(void *data, size_t size)
}

if (CONFIG_GNRC_PKTBUF_CHECK_USE_AFTER_FREE) {
/* check if the data has already been marked as free */
size_t chk_len = _align(size) - sizeof(*new);
if (chk_len && !memchk((uint8_t *)data + sizeof(*new), CANARY, chk_len)) {
printf("pktbuf: double free detected! (at %p, len=%u)\n",
data, (unsigned)_align(size));
DEBUG_BREAKPOINT(2);
}
memset(data, CANARY, _align(size));
}

Expand Down
Loading