Incorrect PushA PopA Mask Calculation #6814
Labels
bug
Something isn't working
compiler: codegen
Everything to do with IR->ASM, register allocation, etc.
P: high
Should be looked at if there are no critical issues left
emit_pusha_popa only handles the first def_reg of each instruction, and could lead to corruption of register in function caller.
Vulnerability Details
When calling a function, we need to store caller registers onto stack and restore it later, so that it doesn't get overwritten by the callee. The compiler does a small optimization by storing only the registers that callee modifies to reduce the amount of stack memory writes.
However, the compiler incorrectly assumes each instruction only modifies one register, so if there are more than one register modified, the remaining registers will not be pushed and popped from stack. Without a push and pop for modified registers, caller register can be modified unexpectedly and cause incorrect execution result.
For example, we compile this code
And the allocated abstract instruction after compiling the code is this
The store_read_24 function uses pshl i23 to store caller registers, which does not include the $r3 register. But $r3 register in modified by srw $r2 $r3 $r1. This causes caller registers to be modified after the call. And any usage of the $r3 register after this will have incorrect value in it.
Impact Details
As usual, it is hard to come up with a precise impact estimation of incorrect code generation because it depends on what code the user writes. The best case scenario would be contracts that run into those bugs getting bricked, and the worst case scenario would be that incorrect program behaviors lead to loss of funds.
References
sway/sway-core/src/asm_generation/fuel/allocated_abstract_instruction_set.rs
Line 63 in c186d93
sway/sway-core/src/asm_lang/allocated_ops.rs
Line 341 in c186d93
Proof of Concept
This test would fail because c in the asm block of setup is overwritten by store_read srw a b slot unexpectedly.
The text was updated successfully, but these errors were encountered: