Files
esp-idf/components/heap/heap_kasan_hooks.c
Meet Patel 383e9adb82 feat(kasan): add Kernel Address Sanitizer (KASAN) support for ESP-IDF
Add KASAN support for detecting heap memory safety bugs (buffer
overflows, underflows, use-after-free) at runtime using compiler
instrumentation and shadow memory. Gated behind
CONFIG_IDF_EXPERIMENTAL_FEATURES, with touch points kept to esp_system
and heap so other components stay untouched.

- Core runtime (esp_system/kasan.c, esp_kasan.h): nibble-based shadow
  memory in DRAM, poison/unpoison, per-access validation, and __asan_*
  stubs; hot-path stubs in IRAM so they stay valid with the flash cache
  off. Shadow init runs before heap bring-up.
- Heap integration (heap/heap_kasan*.c): alloc/free hooks add redzones,
  a quarantine FIFO, and shadow updates.
- Panic handling: disable checks once at the panic handler entry so
  backtrace and stack dumps can read redzones without nested reports.
- Build system: -fsanitize=kernel-address for app code, with HAL, SoC,
  esp_rom, SPI flash, esp_hw_support, bootloader_support, FreeRTOS, and
  heap internals excluded from instrumentation.
- Test app (tools/test_apps/system/kasan_test): Unity tests for
  overflow, underflow, use-after-free, and all sized __asan_* stubs,
  with halt and no-halt configurations.
- Docs: document KASAN in the heap memory debugging guide (EN and CN).
2026-06-24 11:27:00 +05:30

49 lines
1.5 KiB
C

/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
* Strong (non-weak) definitions of the heap trace hooks for KASAN.
*
* IMPORTANT: This file must NOT include esp_heap_caps.h or any header that
* transitively includes it (e.g. freertos/idf_additions.h). The reason is
* that esp_heap_caps.h declares esp_heap_trace_alloc_hook and
* esp_heap_trace_free_hook with __attribute__((weak)), and GCC propagates the
* weak attribute to the definition in the same TU. By keeping this file free
* of that header we get strong (globally overriding) definitions that the
* linker will prefer over the empty weak stubs.
*
* The actual KASAN logic lives in heap_kasan.c; this file just calls into it.
*/
#include "sdkconfig.h"
#if CONFIG_COMPILER_KASAN && CONFIG_HEAP_USE_HOOKS
#include <stddef.h>
#include <stdint.h>
#include "esp_kasan.h"
/* Forward-declare the real implementation from heap_kasan.c */
void kasan_heap_alloc_impl(void *ptr, size_t size, uint32_t caps);
void kasan_heap_free_impl(void *ptr);
/*
* These definitions are strong because this TU never sees the weak declaration
* from esp_heap_caps.h. The linker will therefore use these in preference to
* the empty weak stubs generated by the heap component's own code.
*/
void esp_heap_trace_alloc_hook(void *ptr, size_t size, uint32_t caps)
{
kasan_heap_alloc_impl(ptr, size, caps);
}
void esp_heap_trace_free_hook(void *ptr)
{
kasan_heap_free_impl(ptr);
}
#endif /* CONFIG_COMPILER_KASAN && CONFIG_HEAP_USE_HOOKS */