Incorrect implementation of x86 BSF/BSR
Describe the bug The current implementations of the x86 instructions BSF and BSR are incorrect. The Intel manual states "If the content of the source operand is zero, the destination operand is unmodified." (Vol. 2A 3-107) However, the current implementation sets the destination operand to the highest bit depending on the source size (15, 31, or 63).
To Reproduce Steps to reproduce the behavior:
- Import the attached program into Ghidra
- Emulate the bit scans and observe the result (in RDI)
- Compare to real-world execution (
make run, it's only compatible with Linux though)
Expected behavior If the source operand is zero, the destination should remain unchanged.
Screenshots
Actual execution of the attached MRE:
Result via sleigh emulation:
63
1Decompiled code:
(notice that uVar1 is set before the zero check, not within those conditional blocks)
Attachments MRE source code and object files: bit_scan_bug.zip
Environment (please complete the following information):
- OS: Linux 7.0.10 (Fedora 43)
- Java Version: 26.0.1 (Red Hat)
- Ghidra Version: 12.2
- Ghidra Origin: Locally built from
2a81006bf6554f7e5986fcf5fe6eec8c013194bf
Additional context The current Sleigh constructor for 64-bit BSF is:
bitIndex:8 = 0;
ZF = ( rm64 == 0 );
if ( ZF == 1 ) goto <done>;
<start>
if ( ((rm64 >> bitIndex) & 0x0000000000000001) != 0 ) goto <done>;
bitIndex = bitIndex + 1;
goto <start>;
<done>
Reg64 = bitIndex;The issue is that if rm64 is zero, it jumps to , which still sets Reg64 to bitIndex. It can probably be fixed by just adding a label or something at the very end of the constructor. This is an issue with all the BSF/BSR constructors, not just the 64-bit BSF.
Source: NationalSecurityAgency/ghidra