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
97 changes: 93 additions & 4 deletions decompiler/crates/kuna-analysis/src/loader/elfv1_imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ fn ld(word: u32, rt: u32, ra: u32) -> Option<i64> {
fn mtctr(reg: u32) -> u32 { 0x7c0903a6 | (reg<<21) }

/// Return the TOC displacement and optional lazy-branch offset from the stub start.
/// The environment load is optional; from r2 itself it must precede the TOC load.
fn stub_displacement(w: &[u32]) -> Option<(i64,Option<i64>)> {
if w.first()!=Some(&0xf8410028) {return None;}
let mut i=1;
Expand All @@ -72,14 +73,13 @@ fn stub_displacement(w: &[u32]) -> Option<(i64,Option<i64>)> {
let low=ld(*w.get(i)?,target,base)?;i+=1;
let early_ctr=*w.get(i)?==mtctr(target);
if early_ctr {i+=1;}
if early_ctr && base==2 && ld(*w.get(i)?,11,2)==Some(low+16) {i+=1;}
if ld(*w.get(i)?,2,base)!=Some(low+8) {return None;}i+=1;
if !early_ctr {
if *w.get(i)?!=mtctr(target) {return None;}i+=1;
}
if base!=2 && ld(*w.get(i)?,11,base)==Some(low+16) {
i+=1;
return (*w.get(i)?==0x4e800420).then_some((high+low,None));
}
if base!=2 && ld(*w.get(i)?,11,base)==Some(low+16) {i+=1;}
if *w.get(i)?==0x4e800420 {return Some((high+low,None));}
if *w.get(i)?!=0x28220000 {return None;}i+=1;
if *w.get(i)? & !0x00600000 != 0x4c820420 {return None;}i+=1;
Some((high+low,Some(i as i64*4+branch_displacement(*w.get(i)?)?)))
Expand Down Expand Up @@ -189,4 +189,93 @@ mod tests {
let small=[0xf8410028,0xe9820040,0x7d8903a6,0xe8420048,0x28220000,0x4ca20420,0x48000004];
assert_eq!(stub_displacement(&small),Some((0x40,Some(28))));
}
#[test]
fn small_toc_environment_form_loads_the_environment_before_the_toc() {
const R11: [u32;6]=[0xf8410028,0xe9628118,0x7d6903a6,0xe9628128,0xe8428120,0x4e800420];
const R12: [u32;6]=[0xf8410028,0xe9828118,0x7d8903a6,0xe9628128,0xe8428120,0x4e800420];
for stub in [R11,R12] {
assert_eq!(stub_displacement(&stub),Some((-32488,None)));
let mut lazy=stub[..5].to_vec();lazy.extend([0x28220000,0x4ce20420,0x480000b8]);
assert_eq!(stub_displacement(&lazy),Some((-32488,Some(28+0xb8))));
for i in 0..lazy.len() {assert_eq!(stub_displacement(&lazy[..i]),None,"{i} words");}
for (i,value,why) in [
(0,0xf8410018,"TOC save slot"),(2,stub[2]^0x00200000,"CTR source"),
(3,0xe9628120,"environment at +8"),(3,0xe9628130,"environment at +24"),
(3,0xe9828128,"environment in r12"),(3,0xe96b8128,"environment from r11"),
(3,0xe9628129,"environment load with update"),
(4,0xe8428128,"TOC at +16"),(4,0xe8428118,"TOC at +0"),(4,0xe84b8120,"TOC from r11"),
(4,0xe9628120,"TOC in r11"),(5,0x4e800020,"return"),(5,0x4e800421,"linking branch"),
] {
let mut bad=stub;bad[i]=value;assert_eq!(stub_displacement(&bad),None,"{why}");
}
let swapped=[stub[0],stub[1],stub[2],stub[4],stub[3],stub[5]];
assert_eq!(stub_displacement(&swapped),None,"environment read through the callee TOC");
let late_ctr=[stub[0],stub[1],stub[3],stub[2],stub[4],stub[5]];
assert_eq!(stub_displacement(&late_ctr),None,"environment load before the CTR move");
let last_ctr=[stub[0],stub[1],stub[3],stub[4],stub[2],stub[5]];
assert_eq!(stub_displacement(&last_ctr),None,"CTR move after both loads");
}
let full_base=[0xf8410028,0x3d620000,0xe98b0040,0x7d8903a6,0xe96b0050,0xe84b0048,0x4e800420];
assert_eq!(stub_displacement(&full_base),None,"environment overwrites the high-adjusted base");
let mixed_base=[0xf8410028,0x3d820001,0xe96c0040,0x7d6903a6,0xe9620050,0xe84c0048,0x4e800420];
assert_eq!(stub_displacement(&mixed_base),None,"environment from r2 beside a high-adjusted base");
}
#[test]
fn either_ending_follows_every_base_and_environment_choice() {
const TAIL: [u32;3]=[0x28220000,0x4ce20420,0x480000b8];
let near=[0xf8410028u32,0xe9828118,0x7d8903a6,0xe8428120];
let near_env=[0xf8410028,0xe9828118,0x7d8903a6,0xe9628128,0xe8428120];
let far=[0xf8410028,0x3d620001,0xe98b8118,0x7d8903a6,0xe84b8120];
let far_env=[0xf8410028,0x3d620001,0xe98b8118,0x7d8903a6,0xe84b8120,0xe96b8128];
let far_r12=[0xf8410028,0x3d820001,0xe96c8118,0x7d6903a6,0xe84c8120];
let late_ctr=[0xf8410028,0xe9628118,0xe8428120,0x7d6903a6];
for (body,toc,delta) in [(&near[..],3,-32488),(&near_env[..],4,-32488),(&far[..],4,33048),
(&far_env[..],4,33048),(&far_r12[..],4,33048),(&late_ctr[..],2,-32488)] {
let direct=[body,&[0x4e800420][..]].concat();
let lazy=[body,&TAIL[..]].concat();
assert_eq!(stub_displacement(&direct),Some((delta,None)),"{body:x?}");
assert_eq!(stub_displacement(&lazy),Some((delta,Some(body.len() as i64*4+8+0xb8))),"{body:x?}");
for stub in [&direct,&lazy] {
for i in 0..stub.len() {assert_eq!(stub_displacement(&stub[..i]),None,"{i} of {stub:x?}");}
for (i,value,why) in [
(0,0xf8410018,"TOC save slot"),(toc,0x60000000,"no TOC load"),
(toc,stub[toc]+8,"TOC at +16"),(toc,stub[toc]^0x00010000,"TOC from another base"),
(body.len(),0x4e800020,"return"),(body.len(),0x4e800421,"linking branch"),
(body.len(),0x4c820420,"conditional branch without its compare"),
(body.len(),0x2c220000,"signed compare"),
] {
let mut bad=stub.to_vec();bad[i]=value;assert_eq!(stub_displacement(&bad),None,"{why} in {stub:x?}");
}
}
for (i,value,why) in [(1,0x4ce20421,"linking conditional branch"),(2,0x480000b9,"linking resolver branch"),
(2,0x480000ba,"absolute resolver branch")] {
let mut bad=lazy.clone();bad[body.len()+i]=value;assert_eq!(stub_displacement(&bad),None,"{why} in {lazy:x?}");
}
}
for (value,why) in [(0xe96b8130,"environment at +24"),(0xe96b8120,"environment at +8"),
(0xe98b8128,"environment in r12"),(0xe9628128,"environment through the new TOC"),(0xe96c8128,"environment from r12")] {
for ending in [&[0x4e800420][..],&TAIL[..]] {
let mut bad=far_env.to_vec();bad[5]=value;bad.extend(ending);
assert_eq!(stub_displacement(&bad),None,"{why}");
}
}
let twice=[&far_env[..],&[0xe96b8128,0x4e800420][..]].concat();
assert_eq!(stub_displacement(&twice),None,"second environment load");
let same_register=[0xf8410028,0x3d820001,0xe98c8118,0x7d8903a6,0xe84c8120,0x4e800420];
assert_eq!(stub_displacement(&same_register),None,"entry loaded over its own base");
let other_base=[0xf8410028,0x3d220001,0xe9898118,0x7d8903a6,0xe8498120,0x4e800420];
assert_eq!(stub_displacement(&other_base),None,"base outside r11 and r12");
let late_wrong=[0xf8410028,0xe9628118,0xe8428120,0x7d8903a6,0x4e800420];
assert_eq!(stub_displacement(&late_wrong),None,"late CTR move from another register");
for (entry,ctr,why) in [(0xe8628118,0x7c6903a6,"entry through r3"),(0xe8028118,0x7c0903a6,"entry through r0")] {
for ending in [&[0x4e800420][..],&TAIL[..]] {
let stub=[&[0xf8410028,entry,ctr,0xe8428120][..],ending].concat();
assert_eq!(stub_displacement(&stub),None,"{why}");
}
}
for (stub,why) in [
(&[0xf8410028u32,0x3d620002,0xe98b7ff8,0x396b7ff8,0x7d8903a6,0xe84b0008,0xe96b0010,0x4e800420][..],"addi-adjusted base"),
(&[0xf8410028,0xe9828118,0x7d8903a6,0x7d8b6278,0x7c425a14,0xe8428120,0x4e800420][..],"xor/add dependency"),
] {assert_eq!(stub_displacement(stub),None,"{why}");}
}
}
43 changes: 33 additions & 10 deletions decompiler/crates/kuna-cli/tests/elfv1_imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ fn put64(b: &mut [u8], p: usize, n: u64) { b[p..p+8].copy_from_slice(&n.to_be_by
enum AliasToc { Conflicting, Symbolic, LocalDescriptor, HiddenLocalDescriptor }

#[derive(Clone, Copy, PartialEq)]
enum Transfer { Lazy, Full, Fallback, OtherImport, ReturningResolver }
enum Transfer { Lazy, Full, FullLazy, SmallEnvironment, SmallEnvironmentLazy, SmallDirect, LargeDirect, Fallback, OtherImport, FullLazyOther, ReturningResolver }

/// Synthetic linked ELFv1 with a descriptor-call stub and optional TOC aliases.
fn image(abi: u32, import: &str, alias_toc: Option<AliasToc>, import_addend: i64, transfer: Transfer) -> Vec<u8> {
let conflicting_aliases=alias_toc.is_some();
let local=matches!(alias_toc,Some(AliasToc::LocalDescriptor|AliasToc::HiddenLocalDescriptor));
let hidden=alias_toc==Some(AliasToc::HiddenLocalDescriptor);
let second_import=(conflicting_aliases && !local) || transfer==Transfer::OtherImport;
let second_import=(conflicting_aliases && !local) || matches!(transfer,Transfer::OtherImport|Transfer::FullLazyOther);
let mut o = Object::new(BinaryFormat::Elf, Architecture::PowerPc64, Endianness::Big);
let text = o.add_section(Vec::new(), b".text".to_vec(), SectionKind::Text);
let mut code=Vec::new();
Expand All @@ -33,14 +33,21 @@ fn image(abi: u32, import: &str, alias_toc: Option<AliasToc>, import_addend: i64
code[0x70..0x74].copy_from_slice(&0x48000091u32.to_be_bytes());
}
code.resize(0x100,0);
let stub=if transfer==Transfer::Full {
vec![0xf8410028u32,0x3d620000,0xe98b0000,0x7d8903a6,0xe84b0008,0xe96b0010,0x4e800420]
} else {
let branch=match transfer {Transfer::Fallback=>0x48000004,Transfer::OtherImport=>0x48000058,_=>0x48000050};
vec![0xf8410028,0x3d620000,0xe98b0000,0x7d8903a6,0xe84b0008,0x28220000,0x4ce20420,branch]
let stub=match transfer {
Transfer::Full=>vec![0xf8410028u32,0x3d620000,0xe98b0000,0x7d8903a6,0xe84b0008,0xe96b0010,0x4e800420],
Transfer::SmallEnvironment=>vec![0xf8410028,0xe9620000,0x7d6903a6,0xe9620010,0xe8420008,0x4e800420],
Transfer::SmallEnvironmentLazy=>vec![0xf8410028,0xe9820000,0x7d8903a6,0xe9620010,0xe8420008,0x28220000,0x4ce20420,0x48000050],
Transfer::FullLazy|Transfer::FullLazyOther=>vec![0xf8410028,0x3d620000,0xe98b0000,0x7d8903a6,0xe84b0008,0xe96b0010,0x28220000,0x4ce20420,
if transfer==Transfer::FullLazy {0x4800004c} else {0x48000054}],
Transfer::SmallDirect=>vec![0xf8410028,0xe9820000,0x7d8903a6,0xe8420008,0x4e800420],
Transfer::LargeDirect=>vec![0xf8410028,0x3d620000,0xe98b0000,0x7d8903a6,0xe84b0008,0x4e800420],
_=>{
let branch=match transfer {Transfer::Fallback=>0x4800000c,Transfer::OtherImport=>0x48000058,_=>0x48000050};
vec![0xf8410028,0x3d620000,0xe98b0000,0x7d8903a6,0xe84b0008,0x28220000,0x4ce20420,branch]
}
};
for word in stub {code.extend(word.to_be_bytes());}
code.resize(0x120,0);
code.resize(0x128,0);
for word in [0xe8410028u32,0x4e800020] {code.extend(word.to_be_bytes());}
code.resize(0x138,0);
code.extend((0x2fe8u64-0x1148).to_be_bytes());
Expand Down Expand Up @@ -146,7 +153,8 @@ fn image(abi: u32, import: &str, alias_toc: Option<AliasToc>, import_addend: i64
fn descriptor_definition_wins_over_its_import_stub() {
let specs = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../specs");
for abi in [0, 1] {
for transfer in [Transfer::Lazy, Transfer::Full] {
for transfer in [Transfer::Lazy, Transfer::Full, Transfer::FullLazy, Transfer::SmallEnvironment,
Transfer::SmallEnvironmentLazy, Transfer::SmallDirect, Transfer::LargeDirect] {
let bytes = image(abi, "get_byte", None, 0, transfer);
let path = common::scratch_file("elfv1-definition-and-import", "elf");
std::fs::write(&path, bytes).unwrap();
Expand Down Expand Up @@ -182,12 +190,27 @@ fn descriptor_import_names_and_noreturn_require_unambiguous_targets() {
("__stack_chk_fail",Some(AliasToc::HiddenLocalDescriptor),0,Transfer::Lazy),
("__stack_chk_fail",None,24,Transfer::Lazy),("__stack_chk_fail",None,-24,Transfer::Lazy),
("__stack_chk_fail",None,0,Transfer::Full),
("__stack_chk_fail",None,0,Transfer::SmallEnvironment),
("returning_import",None,0,Transfer::SmallEnvironment),
("__stack_chk_fail",None,0,Transfer::SmallEnvironmentLazy),
("__stack_chk_fail",Some(AliasToc::Conflicting),0,Transfer::SmallEnvironment),
("__stack_chk_fail",Some(AliasToc::LocalDescriptor),0,Transfer::SmallEnvironment),
("__stack_chk_fail",None,24,Transfer::SmallEnvironment),
("__stack_chk_fail",None,0,Transfer::FullLazy),
("__stack_chk_fail",None,0,Transfer::SmallDirect),
("returning_import",None,0,Transfer::SmallDirect),
("__stack_chk_fail",None,0,Transfer::LargeDirect),
("__stack_chk_fail",Some(AliasToc::Conflicting),0,Transfer::SmallDirect),
("__stack_chk_fail",Some(AliasToc::LocalDescriptor),0,Transfer::LargeDirect),
("__stack_chk_fail",Some(AliasToc::Conflicting),0,Transfer::FullLazy),
("__stack_chk_fail",None,0,Transfer::FullLazyOther),
("__stack_chk_fail",None,0,Transfer::Fallback),
("__stack_chk_fail",None,0,Transfer::OtherImport),
("__stack_chk_fail",None,0,Transfer::ReturningResolver),
] {
let conflicts=alias_toc.is_some();
let named=!conflicts && addend==0 && matches!(transfer,Transfer::Lazy|Transfer::Full);
let named=!conflicts && addend==0 && !matches!(transfer,
Transfer::Fallback|Transfer::OtherImport|Transfer::FullLazyOther|Transfer::ReturningResolver);
let bytes=image(1,import,alias_toc,addend,transfer);
let file=object::File::parse(&*bytes).unwrap();
assert!(file.dynamic_relocations().unwrap().any(|(slot,r)|
Expand Down
15 changes: 13 additions & 2 deletions docs/spec/01-program-prep.md
Original file line number Diff line number Diff line change
Expand Up @@ -2785,13 +2785,24 @@ TOCs include aliases that disagree and cannot seed their shared code entry.
This resolver declines all descriptor-stub names if any validated descriptor's
TOC remains unresolved: without a caller-specific TOC, the unknown value could
select a different import and invalidate a no-return fact.
Both full environment-word and GNU lazy-resolution forms are supported. A lazy
A stub addresses the descriptor from `r2` itself or from a base that `addis`
forms from `r2`, and it ends in `bctr` or in the GNU lazy-resolution tail.
The entry goes through `r11` or `r12`, an `addis` base is the other of the
two, and the move to CTR directly follows the entry load or the TOC load.
Loading the environment word into `r11` is optional. From an `addis` base it
is the last instruction before the ending. From `r2` it must directly follow
an early CTR move and precede the TOC load, which replaces `r2`. An environment
load in any other position is declined, as is a stub that does not load the
TOC. GNU ld's rarer forms also stay unnamed: an `addi` that moves the base when
the TOC or environment offset would cross into the next 64 KiB, the `xor`/`add`
pair that replaces the lazy tail when the resolver is out of branch range, and a
stub without the TOC save. A lazy
stub's zero-TOC branch must reach the matching import's resolver entry: its
relocation index, branch to the common glink code, and the common code's load of
`DT_PLTGOT` are validated against `DT_PPC64_GLINK` and `DT_JMPREL`. Returning
fallbacks, entries for another slot, and unknown resolver code or metadata are
declined. Currently only the two-instruction resolver entries with indices below
32768 qualify. The full environment-word form needs no lazy resolver.
32768 qualify. A stub that ends in `bctr` needs no lazy resolver.
The existing known-no-return pass consumes these names, so a guard failure
import no longer introduces false fall-through or consumes the normal return.
ELFv2 decoding and ordinary returning imports retain their existing behavior.
Expand Down
Loading