bmenkveld wrote on Wednesday, June 04, 2014:
I finally got to the bottom of a very nasty issue that was causing random crashes of my software. With this post I’m hoping to maybe save somebody else a lot of time and aggravation, but I would also appreciate any insights from those with more knowledge of the compiler, FreeRTOS, and just what they are supposed to do with interrupt handlers.
The program I’m working on is a new application for an AT32UC3C1512 CPU, using FreeRTOS V7.0.0. I’m using Atmel Studio V6.2.
The problem code looked like this:
#if GNUC
attribute((naked))
#elif ICCAVR32
#pragma shadow_registers = full // Naked.
#endif
static void can0_int_tx_handler(void)
{
/* This ISR can cause a context switch, so the first statement must be a
call to the portENTER_SWITCHING_ISR() macro. This must be BEFORE any
variable declarations. */
portENTER_SWITCHING_ISR();
U8 handle;
handle = CANIF_mob_get_mob_txok(0);
…
/* Exit the ISR. Supposed to pass indication of task switch, but no in the FreeRTOS example code. */
portEXIT_SWITCHING_ISR();
}
Here’s the listing file showing what the compiler produced for this code segment:
8000ffcc <can0_int_tx_handler>:
static void can0_int_tx_handler(void)
{
/* This ISR can cause a context switch, so the first statement must be a
call to the portENTER_SWITCHING_ISR() macro. This must be BEFORE any
variable declarations. */
portENTER_SWITCHING_ISR();
8000ffcc: eb cd 00 ff pushm r0-r7
8000ffd0: e0 68 00 08 mov r8,8
8000ffd4: ea 18 00 00 orh r8,0x0
8000ffd8: 70 00 ld.w r0,r8[0x0]
8000ffda: 1a d0 st.w --sp,r0
8000ffdc: 7a 90 ld.w r0,sp[0x24]
8000ffde: e1 d0 c2 c3 bfextu r0,r0,0x16,0x3
8000ffe2: 58 10 cp.w r0,1
8000ffe4: e0 8b 00 08 brhi 8000fff4 <LABEL_ISR_SKIP_SAVE_CONTEXT_102>
8000ffe8: e0 68 12 c0 mov r8,4800
8000ffec: ea 18 00 00 orh r8,0x0
8000fff0: 70 00 ld.w r0,r8[0x0]
8000fff2: 81 0d st.w r0[0x0],sp
8000fff4 <LABEL_ISR_SKIP_SAVE_CONTEXT_102>:
U8 handle;
handle = CANIF_mob_get_mob_txok(0);
8000fff4: fc 78 1c 00 mov r8,-189440
8000fff8: 70 c8 ld.w r8,r8[0x30]
8000fffa: e6 18 00 3f andh r8,0x3f,COH
8000fffe: b1 88 lsr r8,0x10
80010000: ef 68 ff ff st.b r7[-1],r8
Note that the very last line of assembler here uses register R7, but R7 has not been initialized. So this code ends up over-writing one byte on some task’s stack, which eventually leads to bad things happening.
I fixed the problem by declaring “handle” as “static”.
But why did the compiler generate what appears to be wrong code? And is there a different way to declare an interrupt handler so the compiler will generate correct code even for automatic variables?
Any insights would be appreciated.
And in a related matter, the portEXIT_SWITCHING_ISR() macro generates code that seems to use R12 to decide whether or not to invoke a context switch. But how is the C code supposed to get the correct value into R12?
–
Bert Menkveld
xxxx@xxxx.com