Files
esp-idf/components/heap/heap_kasan_layout.h
T
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

44 lines
1.3 KiB
C

/*
* SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdint.h>
#include "sdkconfig.h"
/*
* Shared KASAN heap redzone layout helpers for heap_caps_base.c, heap_caps.c,
* and heap_kasan.c.
*
* Allocation layout (with CONFIG_HEAP_TASK_TRACKING=y):
*
* [ block-owner word ][ left redzone ][ user bytes ][ right redzone ]
*
* The user-visible pointer points at the start of the user region.
* KASAN_USER_TO_PTR / KASAN_USER_TO_RAW move back to the left redzone start;
* KASAN_PTR_TO_USER moves a block-owner-relative pointer to the user region.
*/
#if CONFIG_COMPILER_KASAN && CONFIG_HEAP_USE_HOOKS && (CONFIG_KASAN_HEAP_REDZONE_SIZE > 0)
#define HEAP_KASAN_RZ_ENABLED 1
#else
#define HEAP_KASAN_RZ_ENABLED 0
#endif
#if HEAP_KASAN_RZ_ENABLED
#define KASAN_RZ CONFIG_KASAN_HEAP_REDZONE_SIZE
#define KASAN_ADD_RZ(sz) ((sz) + 2 * KASAN_RZ)
#define KASAN_PTR_TO_USER(p) ((void *)((uint8_t *)(p) + KASAN_RZ))
#define KASAN_USER_TO_PTR(p) ((void *)((uint8_t *)(p) - KASAN_RZ))
#define KASAN_USER_TO_RAW(p) KASAN_USER_TO_PTR(p)
#else
#define KASAN_RZ 0
#define KASAN_ADD_RZ(sz) (sz)
#define KASAN_PTR_TO_USER(p) (p)
#define KASAN_USER_TO_PTR(p) (p)
#define KASAN_USER_TO_RAW(p) (p)
#endif