Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions decompiler/crates/kuna-analysis/src/loader/kuna_ppc64r12.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! (kuna `ppc64r12`) PPC64 ELFv2 global entries hold their own address in `r12`.
//!
//! The OpenPOWER ELFv2 ABI requires a caller that enters a function at its
//! *global* entry (an indirect call, a PLT stub, a cross-module call) to pass the
//! entry address in `r12`. The global entry derives the TOC pointer from it,
//! `addis r2,r12,hi; addi r2,r2,lo`, before falling into the local entry. Without
//! that fact `r2` is an unknown function input and every TOC-relative global
//! access prints as an offset from an uninitialised register
//! (`*(T *)(r12 + 0x22068) = p`), which also does not recompile.
//!
//! The pass seeds `r12 = entry` at each defined function whose symbol declares a
//! distinct local entry (`st_other`). That annotation is what says the function
//! begins with the `r12`-based TOC setup; a function without one keeps `r2` as
//! received. The kuna analog of the MIPS `t9 = entry` seed in
//! [`super::mips_markers`].

use object::read::{Object, ObjectSymbol};
use object::{SymbolFlags, SymbolKind};

use crate::pass::{AnalysisCtx, AnalysisOutput, AnalysisPass, Phase, TrackedRegFact};

/// The ELFv2 global-entry address register.
const R12: &str = "r12";

/// One `r12 = entry` fact per PPC64 function symbol with a distinct local entry.
fn scan_global_entries(file: &object::File) -> AnalysisOutput {
let mut out = AnalysisOutput::default();
// An image whose e_flags declare ELFv1 (1) gives st_other no entry meaning.
if file.architecture() != object::Architecture::PowerPc64
|| !matches!(file.format(), object::BinaryFormat::Elf)
|| matches!(file.flags(), object::FileFlags::Elf { e_flags, .. } if e_flags & 3 == 1)
{
return out;
}
for sym in file.symbols().chain(file.dynamic_symbols()) {
if sym.kind() != SymbolKind::Text || sym.is_undefined() || sym.address() == 0 {
continue;
}
let SymbolFlags::Elf { st_other, .. } = sym.flags() else { continue };
// Bits 5-7 of st_other: 2..=6 name a local entry 4..64 bytes in.
if !matches!((st_other >> 5) & 7, 2..=6) {
continue;
}
out.tracked_regs.push(TrackedRegFact { func_addr: sym.address(), reg: R12, value: sym.address() });
}
out
}

/// Seeds `r12` at PPC64 ELFv2 global entries; empty on every other image.
#[derive(Clone, Copy, Default)]
pub struct Ppc64GlobalEntryPass;

impl AnalysisPass for Ppc64GlobalEntryPass {
fn phase(&self) -> Phase {
Phase::P1
}

fn id(&self) -> &'static str {
"ppc64r12"
}

fn run(&self, ctx: &AnalysisCtx) -> AnalysisOutput {
if ctx.arch.get_register_varnode(R12.as_bytes()).is_err() {
return AnalysisOutput::default();
}
scan_global_entries(ctx.file)
}
}
1 change: 1 addition & 0 deletions decompiler/crates/kuna-analysis/src/loader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub mod kuna_globalref;
pub mod elfv1;
mod elfv1_imports;
pub mod kuna_ppc32_imports;
pub mod kuna_ppc64r12;
mod kuna_ppc32picimports;
pub use kuna_ppc32picimports::{ImportProofMemo, ImportProofScope};
// (kuna) ELF section-table tolerance: an image whose section headers are
Expand Down
2 changes: 2 additions & 0 deletions decompiler/crates/kuna-analysis/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ pub fn passes_for(compiler: Compiler, format: object::BinaryFormat) -> Vec<Box<d
Box::new(crate::loader::mips_markers::MipsIsaModePass),
// PPC32 ELF relocation metadata; self-gated like the register passes.
Box::new(crate::loader::kuna_ppc32_imports::PicSlotsPass),
// PPC64 ELFv2 `r12 = entry` at global entries; self-gated like mips_gp.
Box::new(crate::loader::kuna_ppc64r12::Ppc64GlobalEntryPass),
// S1 DWARF: recover function/global names and TYPED function signatures
// from `.debug_*` sections (the kuna analog of Ghidra's `DWARFAnalyzer`).
// Registered AFTER LibProtoPass so for any name both emit, the DWARF
Expand Down
Binary file not shown.
2 changes: 2 additions & 0 deletions decompiler/crates/kuna-cli/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,8 @@ mod x87_free_operands;

#[path = "prototype_call_mechanisms.rs"]
mod prototype_call_mechanisms;
#[path = "ppc64_global_entry_toc.rs"]
mod ppc64_global_entry_toc;
#[path = "qualified_storage_addresses.rs"]
mod qualified_storage_addresses;
#[path = "qualified_import_storage.rs"]
Expand Down
20 changes: 20 additions & 0 deletions decompiler/crates/kuna-cli/tests/ppc64_global_entry_toc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//! A PPC64 ELFv2 global entry derives its TOC pointer from `r12`, which the
//! ABI sets to the entry address, so TOC-relative globals resolve by name.

use crate::common;
use std::process::Command;

/// `publish(p) { escaped = p; }` from clang -O1 for powerpc64le:
/// `addis r2,r12,2; addi r2,r2,-32736; addis r4,r2,1; std r3,-32760(r4)`.
#[test]
fn a_global_entry_resolves_its_toc_relative_global() {
let binary = common::fixture("publish_toc_ppc64le");
let output = Command::new(env!("CARGO_BIN_EXE_kuna"))
.env("KUNA_SPECS", common::repo_root().join("specs"))
.args(["decompile", &binary, "publish"])
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
let code = String::from_utf8(output.stdout).unwrap();
assert!(code.contains("escaped = a0;"), "{code}");
}
14 changes: 10 additions & 4 deletions decompiler/crates/kuna-cli/tests/prototype_call_mechanisms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,12 +392,18 @@ fn default_keeps_a_local_in_the_elfv1_toc_slot_of_an_elfv2_frame() {
let kept = code
.lines()
.any(|line| line.trim().starts_with("return ") && line.contains(product.as_str()));
(kept, code)
(kept, code, product)
};
let (kept, off) = returned(Some("off"));
let (kept, off, _) = returned(Some("off"));
assert!(kept && !off.contains("r2save"), "{off}");
let (kept, code) = returned(Some("on"));
assert!(!kept && code.contains("r2save"), "{code}");
let (kept, code, product) = returned(Some("on"));
// `on` stores the TOC over the local; the global entry's `r12` resolves
// that TOC to a constant, so the store prints as that constant (not
// `r2save`) and the return reads it back.
assert!(!kept, "{code}");
let toc = code.lines().find_map(|line| line.trim().strip_prefix(&format!("{product} = 0x")))
.and_then(|rest| rest.strip_suffix(';')).unwrap_or_else(|| panic!("{code}"));
assert!(code.contains(&format!("+ 0x{toc};")) && !code.contains("r2save"), "{code}");
for value in [None, Some("auto")] {
assert_eq!(returned(value).1, off, "{value:?}");
}
Expand Down
Loading