
Function pointer state machines are a staple of embedded C firmware because they are clean, efficient, and deterministic. But when a nearby ring buffer overruns, it can silently overwrite a function pointer, sending the CPU into a hard fault at an address that makes no sense. The crash site is rarely the bug site. This article shows how to catch the corruption in the act using Cortex-M Data Watchpoint and Trace (DWT), implement bulletproof circular buffers, and harden your state machines against this class of failure.
You are debugging a UART driver with a DMA-backed ring buffer. The state machine uses a function pointer table to dispatch events:
typedef void (*state_fn_t)(void);state_fn_t state_table[] = {state_idle,state_rx_header,state_rx_payload,state_process,state_error};volatile state_fn_t current_state = state_idle;
The ring buffer sits in RAM right next to current_state. Under load, the DMA writes past the buffer end. One byte overwrites the LSB of current_state. The next state transition jumps to 0x0800xxxx instead of 0x0800yyyy — a valid flash address, but the wrong function. The CPU executes garbage, eventually hitting an UNDEFINSTR or INVSTATE usage fault.
The hard fault handler shows:
CFSR = 0x00008200 (INVSTATE | IBUSERR)PC = 0x08001234 (middle of a function, not an entry point)LR = 0xFFFFFFF9 (EXC_RETURN, Thread mode, MSP)
The PC does not point to any function in your map file. Standard backtraces are useless because the stack was never properly set up for the bogus function. The crash appears to be in valid code, but the execution path makes no sense.
Traditional debugging approaches fail here. Printf debugging changes timing and may mask the overrun. JTAG breakpoints on the state machine functions never hit because the corruption happens in the buffer write routine, not in the state functions themselves. The fault manifests later, when the corrupted function pointer is dereferenced. By then, the stack frame of the corrupting instruction is long gone.
This is why hardware watchpoints are essential. They catch the write at the moment it happens, not millions of cycles later when the symptom appears.
The linker places variables in declaration order unless you force otherwise. A typical map file excerpt:
.bss.current_state 0x20001000 0x4 (function pointer).bss.rx_ring_buffer 0x20001004 0x100 (256-byte ring buffer)
Wait — the function pointer comes before the buffer. An overrun past the buffer end would hit whatever follows, not current_state. But if the buffer is declared first:
.bss.rx_ring_buffer 0x20001000 0x100.bss.current_state 0x20001004 0x4 -- OVERLAP!
Or the buffer write index wraps incorrectly, writing before the buffer start (negative index). Either way, adjacency is the enemy.
The real-world trigger is often a classic off-by-one in the ring buffer:
// BUG: writes to buffer[SIZE] on the last iterationvoid ring_push(uint8_t byte) {buffer[head] = byte;head = (head + 1) % SIZE; // modulo is slow, but correctif (head == tail) { /* overflow */ }}// BUG: modulo with signed int, negative head wraps to huge positivehead = (head + 1) % SIZE; // if head == -1, result is -1 % 256 = -1 (C99) or 255 (C++?)
On Cortex-M with 16-bit int, uint16_t head promoted to int (16-bit) causes modulo to misbehave when head >= 32768.
The C integer promotion rules silently convert uint16_t to int (signed 16-bit on many Cortex-M toolchains) before the modulo operation. When head reaches 32768, the promoted value becomes negative. The modulo of a negative number in C99 yields a negative result, which when converted back to unsigned produces a huge index — far beyond the buffer bounds. This single promotion bug can corrupt kilobytes of RAM before the modulo wraps back.
Cortex-M3/M4/M7 have hardware Data Watchpoint and Trace (DWT) units — up to 4 comparators. You can set a watchpoint on current_state that triggers DebugMon_Handler the moment any instruction writes to it.
#include <stdint.h>#include "stm32f4xx.h" // or your MCU header// Enable DWT watchpoint on a variable address// comparator: 0-3 (DWT_COMP0..3)// mask: 0 = exact address, 1 = 2-byte, 2 = 4-byte, ... up to 31 = 2GB regionvoid dwt_watchpoint_enable(uint32_t comparator, void *addr, uint32_t mask_bits) {// Enable TRC in DEMCRCoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;// Unlock DWT (if locked)DWT->LAR = 0xC5ACCE55;// Configure comparatorDWT->COMP[comparator] = (uint32_t)addr;DWT->MASK[comparator] = mask_bits; // 0 = exact 4-byte matchDWT->FUNCTION[comparator] =(DWT_FUNCTION_DATA_MATCH_Msk | // match on data addressDWT_FUNCTION_DATAVADDR0_Msk | // use COMP0 as address (adjust for comparator)DWT_FUNCTION_DATAVSIZE_Msk | // match 4-byte accessDWT_FUNCTION_DATAVADDR0_Msk); // enable comparator// Enable Debug Monitor exception (priority 0 = highest)NVIC_SetPriority(DebugMonitor_IRQn, 0);NVIC_EnableIRQ(DebugMonitor_IRQn);}// Usage: watch the 4-byte function pointerdwt_watchpoint_enable(0, ¤t_state, 0);
__attribute__((naked)) void DebugMon_Handler(void) {__asm volatile ("MRS R0, PSP\n""MRS R1, MSP\n""TST LR, #4\n""ITE EQ\n""MOVEQ R0, R0\n""MOVNE R0, R1\n""B dwt_debugmon_c\n");}void dwt_debugmon_c(uint32_t *sp) {// sp[6] = PC, sp[5] = LR, sp[4] = R12, sp[3] = R3, sp[2] = R2, sp[1] = R1, sp[0] = R0uint32_t fault_pc = sp[6];uint32_t fault_lr = sp[5];// Log the corrupting instruction addresslog_corruption(fault_pc, fault_lr, (void *)¤t_state);// Optional: break into debugger__asm volatile ("BKPT #0");// Clear DWT match flagDWT->FUNCTION[0] &= ~DWT_FUNCTION_MATCHED_Msk;}
Now when the ring buffer overrun writes to current_state, you get the exact instruction that did it — the STR instruction in your buffer push routine. No guessing.
// Test: deliberately corrupt the pointervoid test_dwt(void) {dwt_watchpoint_enable(0, ¤t_state, 0);current_state = state_idle; // This should NOT trigger (same value)current_state = state_error; // This SHOULD trigger watchpoint}
If DebugMon_Handler fires on the second write, DWT is working. If not, check:
CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk is setDWT->LAR unlock succeeded (read back should be 1)DWT->FUNCTION[0] & DWT_FUNCTION_MATCHED_Msk sets after writeDebugMonitor_IRQn is enabled in NVICEach DWT comparator can match on instruction address (PC), data address, or data value. For catching buffer overruns, we need data address matching. The FUNCTION register controls the match type:
For our use case, FUNCTION=3 (data address read/write) with DATAVSIZE=2 (word access) and DATAVADDR pointing to the comparator holding the address.
The root cause is the buffer implementation. Here is a pattern that eliminates the off-by-one class of bugs entirely.
#define RING_SIZE 256 // Must be power of 2#define RING_MASK (RING_SIZE - 1)typedef struct {uint8_t data[RING_SIZE];volatile uint16_t head; // Written by producer (ISR/DMA)volatile uint16_t tail; // Read by consumer (main loop)volatile uint16_t count; // Atomic shared state} ring_buffer_t;ring_buffer_t rx_ring;// Producer (ISR or DMA callback) - only modifies head, countvoid ring_push_isr(ring_buffer_t *rb, uint8_t byte) {uint16_t next_head = (rb->head + 1) & RING_MASK;if (next_head == rb->tail) {// Buffer full -- handle overflowrb->overflow_count++;return;}rb->data[rb->head] = byte;__asm volatile ("" ::: "memory"); // Compiler barrierrb->head = next_head;__asm volatile ("" ::: "memory");rb->count++; // Updated LAST -- consumer sees new count only after data is visible}// Consumer (main loop) - only modifies tail, countbool ring_pop(ring_buffer_t *rb, uint8_t *byte) {if (rb->count == 0) {return false;}*byte = rb->data[rb->tail];__asm volatile ("" ::: "memory");rb->tail = (rb->tail + 1) & RING_MASK;__asm volatile ("" ::: "memory");rb->count--; // Updated LAST -- producer sees space only after tail movedreturn true;}
| Property | Mechanism |
|---|---|
| No modulo | & (SIZE-1) is single-cycle on Cortex-M |
| No signed overflow | uint16_t wraps defined by C standard |
| Atomic count | Single 16-bit read/write is atomic on Cortex-M |
| Memory ordering | Compiler barriers prevent reordering around volatile |
| Full/empty unambiguous | count == 0 empty, count == SIZE full (but we never let it reach SIZE) |
Critical: count is the only shared variable used for synchronization decisions. Head and tail are updated after data movement, and count is updated last. This makes the buffer lock-free for single-producer/single-consumer.
The modulo operator % is not a single instruction on Cortex-M0/M0+/M3/M4. It expands to a library call (__aeabi_uidivmod or similar) taking 10-20 cycles. Worse, it introduces signed/unsigned promotion bugs as shown earlier. The bitmask & (SIZE-1) compiles to a single AND instruction — zero cycles on most pipelines since it pairs with the load/store.
For DMA, the producer is hardware. Configure DMA in circular mode with RING_SIZE buffer. The DMA “head” is RING_SIZE - DMA_Stream->NDTR. Consumer reads up to that position:
void ring_dma_consumer(ring_buffer_t *rb) {uint16_t dma_head = RING_SIZE - DMA1_Stream5->NDTR;uint16_t available = (dma_head - rb->tail) & RING_MASK;for (uint16_t i = 0; i < available; i++) {uint8_t byte = rb->data[rb->tail];rb->tail = (rb->tail + 1) & RING_MASK;process_byte(byte);}rb->count = available; // Sync count with reality}
This approach works because DMA writes are naturally sequential and the NDTR register gives the exact write position. No interrupt latency, no ISR overhead.
Even with a correct buffer, defense-in-depth adds safety against unexpected corruption sources (cosmic rays, DMA bugs, stack overflow from unrelated code).
// Known valid range: flash (0x08000000 - 0x080FFFFF for 1MB flash)#define FLASH_START 0x08000000#define FLASH_END 0x08100000bool is_valid_state_fn(state_fn_t fn) {uintptr_t addr = (uintptr_t)fn;return (addr >= FLASH_START && addr < FLASH_END && (addr & 1) == 1); // Thumb bit set}void state_machine_run(void) {if (!is_valid_state_fn(current_state)) {// Corruption detected -- safe recoverylog_error("Invalid state fn: %p", (void*)current_state);current_state = state_error;return;}current_state(); // Safe to call}
The Thumb bit (LSB=1) check is crucial — Cortex-M requires it for all function entries. A corrupted pointer with LSB=0 would cause INVSTATE usage fault on branch.
// In linker script or via section attribute__attribute__((section(".critical_data")))volatile struct {uint32_t canary1;state_fn_t current_state;uint32_t canary2;} sm_state = {.canary1 = 0xDEADBEEF,.current_state = state_idle,.canary2 = 0xFEEDFACE};// Periodic check (e.g., in SysTick or watchdog task)void check_state_machine_integrity(void) {if (sm_state.canary1 != 0xDEADBEEF || sm_state.canary2 != 0xFEEDFACE) {trigger_safe_shutdown("State machine canary corrupted");}}
Canaries detect any overwrite of the critical region, not just function pointer corruption. The 32-bit patterns 0xDEADBEEF and 0xFEEDFACE are chosen because they are unlikely to appear naturally in RAM.
On Cortex-M4/M7 with MPU, make the state variable read-only in normal operation:
// MPU Region 0: Flash (execute, read)// MPU Region 1: RAM (read/write)// MPU Region 2: State machine variables (read-only)void mpu_protect_state_machine(void) {// Region base = &sm_state, size = 32 bytes (round up to 32B)MPU->RBAR = ((uint32_t)&sm_state) & ~0x1F;MPU->RASR = (0x2 << MPU_RASR_AP_Pos) | // RO for privileged, no user access(0x4 << MPU_RASR_SIZE_Pos) | // 32 bytesMPU_RASR_ENABLE_Msk;MPU->CTRL |= MPU_CTRL_ENABLE_Msk;// To update state, temporarily disable MPU or use privileged handler}
Note: This requires the state machine to run in privileged mode, or updates via SVC call. The MPU region size must be a power of two, minimum 32 bytes, aligned to its size.
+------------------------------------------------------------------+| MEMORY LAYOUT (TYPICAL) |+------------------------------------------------------------------+| 0x20001000 | rx_ring_buffer[0..255] | 256 bytes || 0x20001100 | current_state (fn ptr) | 4 bytes || 0x20001104 | tx_ring_buffer[0..255] | 256 bytes |+------------------------------------------------------------------+| BUG: DMA WRITES PAST rx_ring_buffer END || rx_ring_buffer[256] --> OVERWRITES current_state LSB |+------------------------------------------------------------------+| STATE TRANSITION: || current_state() --> JUMPS TO 0x0800xxxx || (valid flash, wrong function) |+------------------------------------------------------------------+| HARD FAULT: CFSR.INVSTATE = 1 || PC = 0x08001234 (middle of function) |+------------------------------------------------------------------+| DWT WATCHPOINT TRIGGERS: || DebugMon_Handler catches STR at fault_pc |+------------------------------------------------------------------+
void test_ring_buffer(void) {ring_buffer_t rb = {0};uint8_t data[] = {0x01, 0x02, 0x03, 0x04};// Fill to capacity-1for (int i = 0; i < RING_SIZE - 1; i++) {ring_push_isr(&rb, i);}assert(rb.count == RING_SIZE - 1);// Next push should detect fullring_push_isr(&rb, 0xFF);assert(rb.overflow_count == 1);assert(rb.count == RING_SIZE - 1); // Unchanged// Pop allfor (int i = 0; i < RING_SIZE - 1; i++) {uint8_t val;assert(ring_pop(&rb, &val));assert(val == i);}assert(rb.count == 0);assert(!ring_pop(&rb, &val)); // Empty// Wrap-around testfor (int cycle = 0; cycle < 3; cycle++) {for (int i = 0; i < 100; i++) ring_push_isr(&rb, i);for (int i = 0; i < 100; i++) {uint8_t val; ring_pop(&rb, &val); assert(val == i);}}}
// Test harness: deliberately overrun and verify DWT catches itvoid test_dwt_catches_overrun(void) {dwt_watchpoint_enable(0, &sm_state.current_state, 0);// Simulate buggy buffer that writes past enduint8_t *buf = rx_ring.data;for (int i = 0; i < RING_SIZE + 8; i++) {buf[i] = 0xAA; // Overruns into current_state at i=256}// DWT should have triggeredassert(dwt_was_triggered(0));uint32_t fault_pc = dwt_get_fault_pc();// fault_pc should point to the STR instruction in this loop}
Run Clang Static Analyzer and MISRA checker:
## Clang tidy checks for buffer overrunsclang-tidy -checks='-*,bugprone-*,clang-analyzer-*' \ring_buffer.c -- -std=c11 -DSTM32F4## MISRA C:2012 Rule 18.1 (pointer arithmetic bounds)cppcheck --enable=all --std=c11 --addon=misra.py ring_buffer.c
Function pointer corruption from buffer overruns is a silent killer in embedded C. The crash appears in a valid flash address, far from the bug site. Three defenses work together:
The DWT technique applies beyond state machines — any global variable that “mysteriously changes” can be watched. On Cortex-M33/MCU with TrustZone, the same DWT unit works in both secure and non-secure worlds.
Next time your state machine jumps to 0x0800xxxx and the backtrace shows garbage, do not stare at the fault handler. Set a watchpoint on the function pointer and let the hardware tell you who wrote to it.
Quick Links
Legal Stuff





