Skip to content

Commit 2adb404

Browse files
authored
Merge pull request #20974 from benpicco/gnrc_pktbuf_static-double-free
sys/net/gnrc_pktbuf_static: add double free detection
2 parents dedc8f9 + 982af61 commit 2adb404

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

sys/net/gnrc/pktbuf_static/gnrc_pktbuf_static.c

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -240,12 +240,13 @@ gnrc_pktsnip_t *gnrc_pktbuf_start_write(gnrc_pktsnip_t *pkt)
240240
}
241241

242242
#ifdef DEVELHELP
243-
#ifdef MODULE_OD
244243
static inline void _print_chunk(void *chunk, size_t size, int num)
245244
{
246245
printf("=========== chunk %3i (%-10p size: %4" PRIuSIZE ") ===========\n", num, chunk,
247246
size);
247+
#ifdef MODULE_OD
248248
od_hex_dump(chunk, size, OD_WIDTH_DEFAULT);
249+
#endif
249250
}
250251

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

271271
void gnrc_pktbuf_stats(void)
272272
{
273-
#ifdef MODULE_OD
274273
_unused_t *ptr = _first_unused;
275274
uint8_t *chunk = &_static_buf[0];
276275
int count = 0;
@@ -306,9 +305,6 @@ void gnrc_pktbuf_stats(void)
306305
if (chunk <= &_static_buf[CONFIG_GNRC_PKTBUF_SIZE - 1]) {
307306
_print_chunk(chunk, &_static_buf[CONFIG_GNRC_PKTBUF_SIZE] - chunk, count);
308307
}
309-
#else
310-
DEBUG("pktbuf: needs od module\n");
311-
#endif
312308
}
313309
#endif
314310

@@ -438,6 +434,10 @@ static void *_pktbuf_alloc(size_t size)
438434
#endif
439435
assert(0);
440436
}
437+
if (CONFIG_GNRC_PKTBUF_CHECK_USE_AFTER_FREE) {
438+
/* clear out canary */
439+
memset(ptr, ~CANARY, size);
440+
}
441441

442442
return (void *)ptr;
443443
}
@@ -469,6 +469,13 @@ void gnrc_pktbuf_free_internal(void *data, size_t size)
469469
}
470470

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

0 commit comments

Comments
 (0)