1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! Argument registers of calls whose callee does not say what it reads.
use std::collections::{HashMap, HashSet};
use vlk_ir::ir::{BinOp, Block, Expr, FunctionIr, Stmt};
use vlk_types::types::abi::LayoutKind;
use vlk_types::types::{CallKind, Convention};
use super::abi;
/// The argument registers the system call `number` reads, when its
/// argument count is known; they pass no more arguments than there are of
/// them. `operation` is what the block set its second argument to, when
/// that is a constant: some calls take fewer arguments for some operations.
pub(crate) fn system_call_arguments(
convention: Convention,
number: u64,
operation: Option<u64>,
) -> Option<&'static [u16]> {
let registers = convention.arguments();
let name = vlk_prototypes::prototypes::syscalls::name(convention, number);
let arity = match name.and_then(vlk_prototypes::prototypes::syscalls::arity) {
// futex(address, operation, value): waking takes no more, and
// waiting takes a timeout. The operation's low bits say which.
Some(_) if name == Some("futex") && operation.map(|op| op & 0x7f) == Some(1) => 3,
Some(_) if name == Some("futex") && operation.map(|op| op & 0x7f) == Some(0) => 4,
// The MIPS kernel takes no address for pipe: it returns the two
// descriptors in v0 and v1.
_ if convention == Convention::SyscallMips && name == Some("pipe") => 0,
Some(arity) => arity,
// A MIPS system call takes four arguments in registers at most:
// one whose count is not known is given them all, so that a
// function that only makes the call keeps its parameters.
None if convention == Convention::SyscallMips => registers.len() - 1,
None => return None,
};
registers.get(1..(arity + 1).min(registers.len()))
}
/// The registers an expression reads other than as the base of a load.
fn collect_used(expr: &Expr, out: &mut HashSet<u16>) {
match expr {
Expr::Load { addr, .. } => match addr.as_ref() {
Expr::Reg { .. } => {}
Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} if matches!(lhs.as_ref(), Expr::Reg { .. })
&& matches!(rhs.as_ref(), Expr::Const(_)) => {}
other => collect_used(other, out),
},
Expr::Reg { index, .. } => {
out.insert(*index);
}
other => {
for child in vlk_ir::ir::visit::children(other) {
collect_used(child, out);
}
}
}
}
/// The registers that hold arguments as the function starts: its
/// parameters, and under the Windows x64 convention those its declared
/// parameters of a register's size take.
fn incoming_arguments(
ir: &FunctionIr,
types: Option<&vlk_loader::loader::dwarf::FunctionTypes>,
) -> HashSet<u16> {
let mut incoming: HashSet<u16> = ir.params.iter().map(|param| param.index).collect();
if ir.convention == Convention::Win64
&& let Some(types) = types.filter(|types| !abi::has_aggregate(types))
{
for (register, layout) in ir.convention.arguments().iter().zip(&types.param_layouts) {
if layout.as_ref().is_ok_and(|layout| {
matches!(layout.size, 1 | 2 | 4 | 8)
&& matches!(
layout.kind,
LayoutKind::Integer | LayoutKind::Boolean | LayoutKind::Pointer
)
}) {
incoming.insert(*register);
}
}
}
incoming
}
/// The constants registers hold.
type Constants = HashMap<u16, u64>;
/// The constants each block leaves in registers after its last statement.
fn constants_left(blocks: &[Block]) -> Vec<Constants> {
blocks
.iter()
.map(|block| {
let mut constants = Constants::new();
for stmt in &block.stmts {
for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
constants.remove(®ister);
}
if let Stmt::Assign {
dest,
value: Expr::Const(value),
..
} = stmt
{
constants.insert(dest.index, *value);
}
}
constants
})
.collect()
}
/// The constant every block before `block` leaves in `register`, when they
/// all leave the same one. The entry block starts with none.
fn carried_constant(
entering: &[Vec<usize>],
left: &[Constants],
block: usize,
register: u16,
) -> Option<u64> {
let Some((first, rest)) = entering[block].split_first() else {
return None;
};
if block == 0 {
return None;
}
let Some(value) = left[*first].get(®ister).copied() else {
return None;
};
rest.iter()
.all(|other| left[*other].get(®ister) == Some(&value))
.then_some(value)
}
/// Gives a call whose callee's arguments are unknown, such as one through a
/// pointer, the argument registers the code sets up for it: up to the last
/// one written since the block's previous call and not used again before
/// the call, as a register holding scratch is. Loading through a register,
/// as a virtual call loads its table through the object, is no such use.
pub(super) fn set_up_arguments(
ir: &mut FunctionIr,
types: Option<&vlk_loader::loader::dwarf::FunctionTypes>,
) {
let incoming = incoming_arguments(ir, types);
// Only the operation of a system call is looked up in the blocks
// before its own.
let left = constants_left(&ir.blocks);
let mut entering: Vec<Vec<usize>> = vec![Vec::new(); ir.blocks.len()];
for index in 0..ir.blocks.len() {
for next in vlk_ir::ir::cfg::block_successors(&ir.blocks, index) {
entering[next].push(index);
}
}
for (position, block) in ir.blocks.iter_mut().enumerate() {
let mut written = if position == 0 && ir.convention == Convention::Win64 {
incoming.clone()
} else {
HashSet::new()
};
// The registers the block has set to constants.
let mut constants = Constants::new();
// Those it has written at all.
let mut touched: HashSet<u16> = HashSet::new();
for stmt in &mut block.stmts {
touched.extend(vlk_ir::ir::visit::statement_registers(stmt).0);
let assigned = match stmt {
Stmt::Assign {
dest,
value: Expr::Const(value),
..
} => Some((dest.index, *value)),
_ => None,
};
if !matches!(stmt, Stmt::Call { .. }) {
for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
constants.remove(®ister);
}
constants.extend(assigned);
}
// A declared call names what it reads; it keeps no argument
// guessed from the writes before it.
if stmt.has_declared_call() {
written.clear();
continue;
}
let Stmt::Call {
kind,
convention,
args,
through,
..
} = stmt
else {
let mut reads = HashSet::new();
for operand in stmt.operands() {
collect_used(operand, &mut reads);
}
for read in reads {
written.remove(&read);
}
written.extend(vlk_ir::ir::visit::statement_registers(stmt).0);
continue;
};
// The register holding the callee's address is no argument.
if let Some(through) = through {
let mut read = HashSet::new();
vlk_ir::ir::visit::collect_reads(through, &mut read);
written.retain(|register| !read.contains(register));
}
let registers = convention.arguments();
// A system call of a known number reads the arguments it
// takes, whether or not the block set them.
if *kind == CallKind::Syscall
&& args.is_none()
&& let Some(number) = registers.first().and_then(|first| constants.get(first))
&& let Some(read) = system_call_arguments(
*convention,
*number,
registers.get(2).and_then(|second| {
constants.get(second).copied().or_else(|| {
(!touched.contains(second))
.then(|| carried_constant(&entering, &left, position, *second))
.flatten()
})
}),
)
{
let width = if matches!(
convention,
Convention::Aapcs32 | Convention::O32 | Convention::SyscallMips
) {
32
} else {
64
};
*args = Some(
registers[..1]
.iter()
.chain(read)
.map(|register| Expr::reg(*register, width))
.collect(),
);
}
constants.clear();
if args.is_none()
&& let Some(last) = registers
.iter()
.rposition(|register| written.contains(register))
{
let width = if matches!(convention, Convention::Aapcs32 | Convention::O32) {
32
} else {
64
};
*args = Some(
registers[..=last]
.iter()
.map(|register| Expr::reg(*register, width))
.collect(),
);
}
written.clear();
}
}
}