Skip to content

Commit 9294141

Browse files
aykevldeadprogram
authored andcommitted
avr: fix race condition in stack write
If an interrupt happens between the writes to SPL and SPH, the stack pointer is inconsistent and terrible things will happen. Therefore, disable interrupts while updating the stack pointer. Interrupts are restored _before_ the write to SPH. This is safe, because interrupts are re-enabled with a one cycle delay. The avr-gcc and Clang compilers do the same thing when they need to update the stack pointer. It's almost impossible to test for this bug, but it should make firmware just a little bit more reliable.
1 parent bcf58c0 commit 9294141

File tree

1 file changed

+3
-0
lines changed

1 file changed

+3
-0
lines changed

src/internal/task/task_stack_avr.S

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,10 @@ tinygo_swapTask:
7272
std Y+1, r3
7373

7474
// Switch to the new stack pointer.
75+
in r0, 0x3f ; SREG
76+
cli
7577
out 0x3d, r24; SPL
78+
out 0x3f, r0 ; SREG, restore interrupts (after the next instruction)
7679
out 0x3e, r25; SPH
7780

7881
// Load saved register from the new stack.

0 commit comments

Comments
 (0)