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
3 changes: 2 additions & 1 deletion decompiler/crates/kuna-base/src/xml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2205,7 +2205,8 @@ mod tests {
// and kuna-repframecopy / a by-value argument copied with rep movs reaches its call
// and kuna-libcnames-win32 / a local takes the name of the Win32 call it meets
// and kuna-libcnames-addr / a stack object takes the name of the library parameter its address meets
assert_eq!(count, 756, "corpus file count drifted");
// and kuna-x86-directalias / a call keeps an argument a later direct stack store sits below
assert_eq!(count, 757, "corpus file count drifted");
}

/// ~20 representative SLEIGH spec files across varied processors
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ pub fn check_input_trial_use(
let has_alias = !read_end.is_some_and(|end| trial_end <= end) && {
let mut access = data.alias_gather_access();
aliascheck.has_local_alias(Some((vn_space.clone(), vn_offset)), &mut access)
};
} && crate::p4_calls::kuna_directalias::aliases(data, aliascheck, vn_offset, vn_size);
// C++ keeps these two no-use conditions as separate branches
// (fspec.cc:5616-5619): a stack alias, OR a stack location outside the
// CALLER's local range, both mean "not a parameter". The range test is
Expand Down
84 changes: 84 additions & 0 deletions decompiler/crates/kuna-decomp/src/p4_calls/kuna_directalias.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//! (kuna) A direct access at a known stack offset aliases only the bytes it
//! touches.
//!
//! `checkInputTrialUse` drops a stack trial when the frame's alias boundary
//! (`AliasChecker::hasLocalAlias`) reaches it: some pointer formed from the
//! stack pointer sits at or below the slot, so anything above it may be
//! reached. A `LOAD`/`STORE` through such a pointer counts until heritage turns
//! it into a stack variable, and a pointer whose offset only becomes known late
//! — a stack pointer restored from the frame slot it was saved in, after an
//! `alloca` — is still one when call inputs are scored. The call after the
//! restore stores its own argument through it, below the earlier calls'
//! arguments, and those were dropped (`reg(1)` printed for `reg(1, n)`).
//!
//! A pointer that is the stack-pointer input plus constants, through copies
//! and frame slots only, and that is used solely as the address of `LOAD`s and
//! `STORE`s, touches exactly `[offset, offset + size)`. Such a pointer aliases a
//! trial only when those bytes overlap it; every other pointer keeps the
//! upstream boundary. Always on.

use crate::context::VarnodeId;
use crate::funcdata::Funcdata;
use crate::varmap::{AddBase, AliasChecker};
use kuna_base::types::{int4, uintb};
use kuna_num::opcodes::OpCode;

/// How many definitions [`fixed_offset`] follows back to the stack pointer.
const MAX_STEPS: usize = 16;

/// Does a gathered pointer reach the trial at `[offset, offset + size)`?
/// Call after `has_local_alias` answered `true` for it.
pub fn aliases(data: &Funcdata, aliascheck: &AliasChecker, offset: uintb, size: int4) -> bool {
let direct = |base: &AddBase| direct_bytes(data, base.base).is_some();
if aliascheck.has_local_alias_among(offset, |base| !direct(base)) {
return true;
}
let end = offset.wrapping_add(size.max(1) as uintb);
aliascheck.get_alias().iter().zip(aliascheck.get_add_base()).any(|(&start, base)| {
direct_bytes(data, base.base).is_some_and(|bytes| start < end && offset < start.wrapping_add(bytes))
})
}

/// The widest access through `vn` when it is only ever the address of a
/// `LOAD`/`STORE` and a fixed offset from the stack pointer.
fn direct_bytes(data: &Funcdata, vn: VarnodeId) -> Option<uintb> {
if !fixed_offset(data, vn) {
return None;
}
let mut widest = 0;
for id in data.vbank().get(vn)?.descend_iter() {
let op = data.obank().get(id)?;
let accessed = match op.code() {
OpCode::CPUI_LOAD if op.get_in(1) == Some(vn) => op.get_out()?,
OpCode::CPUI_STORE if op.get_in(1) == Some(vn) && op.get_in(2) != Some(vn) => op.get_in(2)?,
_ => return None,
};
widest = widest.max(data.vbank().get(accessed)?.get_size().max(0) as uintb);
}
(widest > 0).then_some(widest)
}

/// Is `vn` the stack-pointer input plus constants, through copies only?
fn fixed_offset(data: &Funcdata, mut vn: VarnodeId) -> bool {
for _ in 0..MAX_STEPS {
let Some(node) = data.vbank().get(vn) else { return false };
if node.is_input() {
return node.get_space().get_type() == kuna_base::space::spacetype::IPTR_PROCESSOR
&& data.get_arch().manage().get_stack_space().is_some_and(|stack| {
stack.get_spacebase(0).is_ok_and(|sp| sp.offset == node.get_offset() && sp.size as int4 == node.get_size())
});
}
let Some(op) = node.get_def().and_then(|id| data.obank().get(id)) else { return false };
let constant = |slot| op.get_in(slot).and_then(|v| data.vbank().get(v)).is_some_and(|v| v.is_constant());
let next = match op.code() {
OpCode::CPUI_COPY => op.get_in(0),
OpCode::CPUI_INT_ADD if constant(1) => op.get_in(0),
OpCode::CPUI_INT_ADD if constant(0) => op.get_in(1),
OpCode::CPUI_INT_SUB if constant(1) => op.get_in(0),
_ => None,
};
let Some(next) = next else { return false };
vn = next;
}
false
}
1 change: 1 addition & 0 deletions decompiler/crates/kuna-decomp/src/p4_calls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub mod kuna_retcallhalf; // (kuna) a call's result handed back beside a compute
pub mod kuna_retsysreg; // (kuna) a register set for a system register is not the high word of the return
pub mod kuna_retpushedhalf;
pub mod kuna_reloadarg; // (kuna) a register reloaded from the caller's frame is re-scored once the frame is heritaged
pub mod kuna_directalias; // (kuna) a direct access at a known stack offset aliases only the bytes it touches
pub mod kuna_returnuncomputed;
pub mod kuna_spillargtrial;
pub mod kuna_stackaddrargtrial;
Expand Down
20 changes: 20 additions & 0 deletions decompiler/crates/kuna-decomp/src/p6_variables/varmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,26 @@ impl AliasChecker {
vn_offset >= self.alias_boundary
}

/// (kuna) [`Self::has_local_alias`]'s boundary drawn from only the gathered
/// pointers `keep` accepts. Call after `has_local_alias` gathered them.
pub fn has_local_alias_among(&self, offset: uintb, keep: impl Fn(&AddBase) -> bool) -> bool {
if self.direction == -1 {
return false;
}
if self.alias.len() != self.add_base.len() {
return offset >= self.alias_boundary;
}
let mut boundary = self.local_extreme;
for (&alias, base) in self.alias.iter().zip(&self.add_base) {
let parameter =
if self.direction == 1 { alias < self.local_boundary } else { alias > self.local_boundary };
if !parameter && keep(base) {
boundary = boundary.min(alias);
}
}
offset >= boundary
}

/// (kuna) Whether a pointer formed into the parameter area could reach the
/// slot at `offset`: an address taken there at or below it. `hasLocalAlias`
/// answers only for locals, so a caller slot above the return address whose
Expand Down
7 changes: 5 additions & 2 deletions docs/baseline-stages.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"data_footer": [
4340,
4340
4343,
4343
],
"passing": [
"data:64-bit logical shift retains unsigned destination",
Expand Down Expand Up @@ -4309,6 +4309,9 @@
"data:x86 callee stack: all second words survive",
"data:x86 callee stack: first writes survive off and real observers",
"data:x86 callee stack: stack-passed const writer does not fold stale bytes",
"data:x86-directalias #1: both functions pass n to the first call",
"data:x86-directalias #2: no first call loses its argument",
"data:x86-directalias #3: the call after the restore keeps its argument",
"data:x86_64 callee stack: all later overwrites survive",
"data:x86_64 callee stack: all second words survive",
"data:x86_64 callee stack: first writes survive off and real observers",
Expand Down
11 changes: 11 additions & 0 deletions docs/spec/04-calls-and-prototypes.md
Original file line number Diff line number Diff line change
Expand Up @@ -1850,6 +1850,17 @@ classified:
argument. That is visible as deleted basic blocks, not merely as a shorter
argument list. (kuna) The caller-relative Varnode address is the one probed
(`decompiler/crates/kuna-decomp/src/p4_calls/kuna_callsitestackargs.rs`, always on).

**Direct accesses alias only their bytes** (always on, kuna): a gathered
pointer that is the stack-pointer input plus constants, through copies and
frame slots only, and is used solely as the address of `LOAD`s and `STORE`s
(`kuna_directalias.rs (aliases)`) aliases a trial only when the bytes it
touches overlap the trial; every other pointer keeps the boundary above
(`varmap.rs (AliasChecker::has_local_alias_among)`). Such a pointer is an
access heritage has not converted yet: a stack pointer restored from the
frame slot it was saved in after an `alloca` is still one when call inputs
are scored, and the call after the restore storing its argument at -0x2c
dropped an earlier call's argument at -0x28 (`reg(1)` for `reg(1, n)`).
- (kuna `calleeargs`, default on) **Callee stack-argument extent.** On
x86-32 under a model that leaves extrapop unknown (`x86win.cspec`), a direct
call whose callee's own code can be read takes its stack arguments from what
Expand Down
40 changes: 40 additions & 0 deletions tests/stages/kuna-x86-directalias.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<decompilertest>
<binaryimage arch="x86:LE:32:default:gcc">
<!--
Two calls pass stack arguments through a copy of %esp (clang -O0), then a
variable-size allocation saves %esp in a frame slot, and after it %esp is
restored from that slot before a third call:

static_frame(n): reg(1, n); reg(0, n); reg(n);
later_vla(n): reg(1, n); reg(0, n); { char a[n]; a[0] = 7; } reg(n);

When call inputs are scored, the third call's argument store still goes
through the restored stack pointer, so the alias gather recorded it as a
pointer at -0x2c and every slot above it as aliased: later_vla printed
reg(1) for reg(1, n). That pointer is the stack pointer plus constants
through the frame slot, used only as the store's address, so it touches
only its own four bytes. Hand-assembled; reg is a ret stub.
-->
<bytechunk space="ram" offset="0x100000" readonly="true">
5589e583ec188b4d0883ec1089e0894804c70001000000e8e400000083c4108b4d0883ec3089e0894804c7402008000000c70000000000e8c400000083c4308b4d0883ec10890c24e8b300000083c41089ec5dc390909090909090909090909090909090909090909090909090909090909090909090909090909090909090905589e583ec188b4d0883ec1089e0894804c70001000000e86400000083c4108b4d0883ec3089e0894804c7402008000000c70000000000e84400000083c43089e1894df48b550829d489e0c600078b45f489c48b4d0883ec10890c24e81f00000083c41089ec5dc3909090909090909090909090909090909090909090909090c3909090909090909090909090909090
</bytechunk>
<symbol space="ram" offset="0x100000" name="static_frame"/>
<symbol space="ram" offset="0x100080" name="later_vla"/>
<symbol space="ram" offset="0x100100" name="reg"/>
</binaryimage>
<script>
<com>parse line extern uint4 reg(uint4 count, ...);</com>
<com>parse line extern void static_frame(uint4 n);</com>
<com>parse line extern void later_vla(uint4 n);</com>
<com>lo fu static_frame</com>
<com>decompile</com>
<com>print C</com>
<com>lo fu later_vla</com>
<com>decompile</com>
<com>print C</com>
<com>quit</com>
</script>
<stringmatch name="x86-directalias #1: both functions pass n to the first call" min="2" max="2">reg\(1,n\);</stringmatch>
<stringmatch name="x86-directalias #2: no first call loses its argument" min="0" max="0">reg\(1\);</stringmatch>
<stringmatch name="x86-directalias #3: the call after the restore keeps its argument" min="2" max="2">reg\(n\);</stringmatch>
</decompilertest>
Loading