Skip to content

Commit da7db81

Browse files
aykevldeadprogram
authored andcommitted
cortexm: fix stack size calculation with interrupts
Interrupts store 32 bytes on the current stack, which may be a goroutine stack. After that the interrupt switches to the main stack pointer so nothing more is pushed to the current stack. However, these 32 bytes were not included in the stack size calculation. This commit adds those 32 bytes. The code is rather verbose, but that is intentional to make sure it is readable. This is tricky code that's hard to get right, so I'd rather keep it well documented.
1 parent 098fb5f commit da7db81

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

builder/build.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -447,11 +447,28 @@ func modifyStackSizes(executable string, stackSizeLoads []string, stackSizes map
447447
return fmt.Errorf("could not find symbol %s in ELF file", name)
448448
}
449449
if fn.stackSizeType == stacksize.Bounded {
450-
// Note: adding 4 for the stack canary. Even though the size may be
450+
stackSize := uint32(fn.stackSize)
451+
452+
// Adding 4 for the stack canary. Even though the size may be
451453
// automatically determined, stack overflow checking is still
452454
// important as the stack size cannot be determined for all
453455
// goroutines.
454-
binary.LittleEndian.PutUint32(data[i*4:], uint32(fn.stackSize)+4)
456+
stackSize += 4
457+
458+
// Add stack size used by interrupts.
459+
switch elfFile.Machine {
460+
case elf.EM_ARM:
461+
// On Cortex-M (assumed here), this stack size is 8 words or 32
462+
// bytes. This is only to store the registers that the interrupt
463+
// may modify, the interrupt will switch to the interrupt stack
464+
// (MSP).
465+
// Some background:
466+
// https://interrupt.memfault.com/blog/cortex-m-rtos-context-switching
467+
stackSize += 32
468+
}
469+
470+
// Finally write the stack size to the binary.
471+
binary.LittleEndian.PutUint32(data[i*4:], stackSize)
455472
}
456473
}
457474

0 commit comments

Comments
 (0)