Encountering hardfaults in FreeRTOS v10.3.0 on a Microchip PIC32 while using vsnprintf or sprin

Hi guys, I'm encountering hardfaults in FreeRTOS v10.3.0 on a Microchip PIC32 while using vsnprintf or sprintf functions. I suspect stack corruption, as I'm using static memory allocation no malloc with a pre-allocated buffer char _log_buffer[128]. I've tried different printf implementations newlib, newlib nano, tinyprintf without success. I tried troubleshooting with these: ~Verified thread stack alignment. ~Ruled out dynamic allocation issues by mocking malloc/calloc/realloc/free. Are there any recommended techniques to confirm stack corruption specifically related to printf calls in FreeRTOS? With static memory allocation, what are some effective ways to debug the stack pointer behavior during these hardfaults? @Middleware & OS
4 Replies
Marvee Amasi
Marvee Amasi7mo ago
Hi @Sterling you should start with basic format strings like "%d" instead of complex ones first of all to isolate formatting issues.
Marvee Amasi
Marvee Amasi7mo ago
Add a canary value in the end of your stack and you check it before using printf to check for any potential stuffs overwriting
Marvee Amasi
Marvee Amasi7mo ago
See here :
#define STACK_CANARY_VALUE 0xDEADBEEF

char _log_buffer[128];
uint32_t _log_buffer_canary = STACK_CANARY_VALUE;

void my_function(void) {
// your code bla bla bla

// This is where you should check the canary before using printf
if (_log_buffer_canary != STACK_CANARY_VALUE) {
// Stack corruption detected!
// Handle the error prolly stop execution or trigger a watchdog
}

// Now it is safe hopefully to use printf
vsnprintf(_log_buffer, sizeof(_log_buffer), "%d", some_variable);
}
#define STACK_CANARY_VALUE 0xDEADBEEF

char _log_buffer[128];
uint32_t _log_buffer_canary = STACK_CANARY_VALUE;

void my_function(void) {
// your code bla bla bla

// This is where you should check the canary before using printf
if (_log_buffer_canary != STACK_CANARY_VALUE) {
// Stack corruption detected!
// Handle the error prolly stop execution or trigger a watchdog
}

// Now it is safe hopefully to use printf
vsnprintf(_log_buffer, sizeof(_log_buffer), "%d", some_variable);
}
UC GEE
UC GEE7mo ago
@Sterling Try out a debugger like MPLAB X to inspect the stack pointer and stack contents during the execution of your code.Then, you can now set breakpoints and inspect variables to identify any issues with stack pointer behavior.You can try these techniques out.
Want results from more Discord servers?
Add your server