cancel
Showing results for 
Search instead for 
Did you mean: 

Unpredictable behavior when extracting SVC number inside handler — sometimes causes BusFault

Kishorer03
Associate

Hi everyone,

I'm new to embedded programming and trying to understand how SVC (Supervisor Call) works on ARM Cortex-M.

I wrote a small program that triggers an SVC call, and in the SVC handler, I try to extract the SVC number by accessing the PC that was stacked during the exception. It works fine sometimes, but other times it causes a BusFault, seemingly at random due to  printf in my statement. I changed the syscall.c script and configured the SWO.

Kishorer03_0-1744743921733.png

This is my code below,

 

#include <stdint.h>
#include <stdio.h>

int main()
{
__asm volatile("SVC #0x08");
printf("Returned from svc call \n");

while(1);
return 0;
}

__attribute__ ((naked)) void SVC_Handler(void) {
__asm volatile("MRS R0, MSP");
__asm volatile("B SVC_Handler_cl");
}

void SVC_Handler_cl(uint32_t *pEStack) {
uint16_t* PCC = ((uint16_t*)(*(pEStack + 6))) - 1;
printf("opcode := %u \n", *PCC);
}

Now here's the weird part:

  • If I don't use printf() in main, things seem okay.

  • If I do use printf() there, I often get a BusFault, particularly during the MRS R0,MSP line in the handler.

  • But if I modify the printf() call in printf() to include a format specifier (like printf("Returned from svc call %d\n", 0x20);), then everything works again — no faults!

I'm baffled. Kindly clarify this.

Any help or insight would be greatly appreciated. Thanks in advance!

 

1 REPLY 1
Pavel A.
Evangelist III

Maybe your program is too minimalistic and does not initialize the C runtime sufficiently. A complete code would be useful (including the SystemInit etc.) Check that the initial stack pointer address is good. Also note that printf() call with one arg may be changed to puts() by the compiler.