x86-16 emulation: no segment user op, and far returns and indirect far branches lose CS
Describe the bug
16-bit x86 code (x86:LE:16:Protected Mode and x86:LE:16:Real Mode) can't be emulated without workarounds, in the legacy EmulatorHelper, PcodeEmulator or JitPcodeEmulator. There are two causes.
No emulator implements the
segmentuser op. The x86-16 SLEIGH computes every memory operand and several branch targets throughsegment(seg, off). The processor specs define its meaning for the decompiler (segmentopinx86-16.pspecandx86-16-real.pspec:(zext(base) << 16) + zext(inner)in protected mode,<< 4in real mode), but thex86userop library has nosegment. So the first memory access fails:- legacy
EmulatorHelper:UnimplementedCallOtherException; PcodeEmulatorandJitPcodeEmulator:SleighLinkException: Sleigh userop 'segment' is not in the library.
- legacy
Some 16-bit far branches in
ia.sincdrop or never set the code segment.RET imm16(C2),RETF imm16(CA) andIRET(CF) with 16-bit operand and address size setEIP=zext(IP), while plainRET(C3) andRETF(CB) setEIP=segment(CS,IP). After aRETF imm16, execution continues at segment0000and the next decode fails, for exampleUnknown disassembly error (PC=0000:4d3e).CALLF m16:16(FF /3) branches to the right linear address but never assignsCS, so the next near return or segment-relative access uses the caller'sCS.JMPF m16:16(FF /5) with 16-bit operand size zero-extends the offset and ignores the selector.
The direct forms (
CALLF ptr16:16,JMPF ptr16:16) are correct, becauseptr1616assignsCS.
To Reproduce
- Create a
PcodeEmulatorforx86:LE:16:Real Mode. - Put
C2 04 00(RET 4) at1000:0100, setCS=1000,SS=2000,SP=0100, and write the word0234at2000:0100. - Step one instruction.
stepInstructionstops on the missingsegmentop when it pops the stack. With asegmentop supplied, the counter ends at0000:0234instead of1000:0234.
Expected behavior
16-bit code emulates with the segment arithmetic the processor specs already define, and far returns, far indirect calls and far indirect jumps leave CS and the counter at the far target.
Environment
- OS: Windows 11 Pro (build 26200)
- Java Version: Temurin 21.0.12.1+1
- Ghidra Version: 12.1.3; the same definitions are in
ia.sinconmaster - Ghidra Origin: official GitHub distro
Additional context
We hit this running functions of a 1994 16-bit Windows (NE) executable in all three emulators. With a segment implementation and the branch targets corrected, PcodeEmulator gave the same results as another emulator on every case we ran. Patching branch targets from outside did not work for JitPcodeEmulator, because the CS in its thread state was out of date when a compiled block exited. With CS assigned in ia.sinc itself, it passes the same single-instruction tests as PcodeEmulator. #9678 has the fix and the tests.
Source: NationalSecurityAgency/ghidra