NationalSecurityAgency / ghidra

Ghidra is a software reverse engineering (SRE) framework
https://www.nsa.gov/ghidra
Apache License 2.0
51.63k stars 5.87k forks source link

PowerPC PPC Sleigh files mis-handle branch-conditional-and-link #5218

Closed FrazzleDancer closed 1 year ago

FrazzleDancer commented 1 year ago

Sleigh for PowerPC branches where CC & LK=1 or CTR_DEC & LK=1 use code like

if (!CC) goto inst_next;
LR = inst_next;
call addressBD;

which sets the link register to the address of the following instruction only if the branch is taken; but IBM's "Power ISATM Version 3.0"'s description of "Branch Conditional B-form" (p. 39) is

  if (64-bit mode) 
     then M <- 0 
     else M <- 32
  if ¬BO<sub>2</sub> then CTR <- CTR - 1
  ctr_ok <- BO<sub>2</sub> | ((CTR<sub>M:63</sub> != 0) XOR BO<sub>3</sub>) 
  cond_ok <- BO<sub>0</sub> | (CR<sub>BI+32</sub> == BO<sub>1</sub>)
  if ctr_ok & cond_ok then
     if AA then NIA <- <sub>iea</sub> EXTS(BD || 0b00)
     else           NIA <- <sub>iea</sub> CIA + EXTS(BD || 0b00) 
  if LK then LR <- <sub>iea</sub> CIA + 4

which sets the link register to the address of the following instruction regardless of whether the branch is taken; this is supported by the subsequent text, which states without qualification that if LK=1, the effective address of the next instruction is placed into the link register. I have seen production code that relies upon this peculiarity. I believe where LK=1, the line "LR = inst_next;" should be the first line of the body, preceding the conditional test.

[Apologies for the appearance of the sup and sub tags in the quote of the IBM manual; I avoided back-ticks around that in the hopes that the tags would render correctly, but apparently GitHub is too smart for that.]

mumbel commented 1 year ago

you need to be more specific for which instruction you're talking about in SLEIGH and the manual. p39 only discusses bctar and bctarl which is implemented in ppc_isa.sinc and does not use the variables you provided as the faulty SLEIGH.

Are you sure you're using the right language settings?

FrazzleDancer commented 1 year ago

All of the "branch conditional and link" instructions are affected; in the 2015 manual, they are

In the Sleigh file ppc_instructions.sinc, they are

FrazzleDancer commented 1 year ago

The discrepency is evident in this screencap of (on the left) part of ppc_instructions.sinc and (on the right) the 2015 IBM PowerISA Version 3.0 manual: Screen Shot 2023-04-13 at 12 28 26 AM