Skip to content

Custom panic handler is called with improper stack alignment on ARM #2861

@arthomnix

Description

@arthomnix

When a custom panic handler is set using PICO_PANIC_FUNCTION, the stack pointer is not aligned to 8 bytes when the handler is called (as it should be according to the ARM calling convention).

The definition of panic used when PICO_PANIC_FUNCTION is defined contains a single push {lr} instruction, which causes the stack pointer to become misaligned when the custom handler is called:

"push {lr}\n"
#if !PICO_PANIC_FUNCTION_EMPTY
"bl " __XSTRING(PICO_PANIC_FUNCTION) "\n"

This can result in strange, difficult-to-debug behaviour in the panic handler, as the C compiler assumes that functions will be called according to the calling convention with proper stack alignment. For example, this program

#include <stdio.h>
#include "pico/stdlib.h"

void handle_panic(void) {
    printf("%f\n", 1.234567f);
    while (1);
}

int main(void) {
    stdio_init_all();
    sleep_ms(5000);
    panic("test");
}

(with add_compile_definitions(PICO_PANIC_FUNCTION=handle_panic) in CMakeLists.txt) prints 2.681562e+154 on the Pico W with the current SDK.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions