liblisa 0.1.4

A tool for automated discovery and analysis of the ISA of a CPU.
Documentation
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Types representing the dataflows in an [`Encoding`](super::Encoding).

use std::fmt::{Debug, Display};
use std::ops::{Index, IndexMut};

use log::trace;
use serde::{Deserialize, Serialize};

use crate::arch::{Arch, Register};
use crate::encoding::bitpattern::{FlowInputLocation, FlowOutputLocation, FlowValueLocation};
use crate::instr::Instruction;
use crate::semantics::{Computation, ARG_NAMES};
use crate::state::{Area, SystemState};
use crate::value::{OwnedValue, Value};

mod accesses;
mod address_computation;
mod inputs;
mod locs;

pub use accesses::*;
pub use address_computation::*;
pub use inputs::*;
pub use locs::*;

/// A collection of dataflows and memory accesses.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(
    feature = "schemars",
    schemars(bound = "A: schemars::JsonSchema, A::Reg: schemars::JsonSchema, C: schemars::JsonSchema")
)]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(bound(serialize = "C: Serialize", deserialize = "C: Deserialize<'de>"))]
pub struct Dataflows<A: Arch, C> {
    /// The memory accesses of these dataflows.
    pub addresses: MemoryAccesses<A>,

    /// The outputs of the dataflows.
    pub outputs: Vec<Dataflow<A, C>>,

    /// Whether any dependent bytes were found during Dataflow Analysis.
    pub found_dependent_bytes: bool,
}

fn none<T>() -> Option<T> {
    None
}

/// A single dataflow.
/// Has one target (destination), and zero or more inputs (sources).
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(
    feature = "schemars",
    schemars(bound = "A: schemars::JsonSchema, A::Reg: schemars::JsonSchema, C: schemars::JsonSchema")
)]
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(bound(serialize = "C: Serialize", deserialize = "C: Deserialize<'de>"))]
pub struct Dataflow<A: Arch, C> {
    /// The storage location in which the result of the computation of this dataflow is saved.
    pub target: Dest<A>,

    /// The sources of the dataflow.
    pub inputs: Inputs<A>,

    /// The computation applied to the inputs to compute the value that is written to `target`.
    #[serde(default = "none::<C>")]
    pub computation: Option<C>,

    /// Whether this dataflow has unobservable external inputs.
    /// If true, `computation` must be `None` and `inputs` should be empty.
    #[serde(default)]
    pub unobservable_external_inputs: bool,
}

impl<A: Arch, C> Dataflow<A, C> {
    /// Returns the inputs of the dataflow.
    #[inline(always)]
    pub fn inputs(&self) -> &Inputs<A> {
        &self.inputs
    }

    /// Returns the storage locatin to which the result of the computation is written.
    #[inline(always)]
    pub fn target(&self) -> &Dest<A> {
        &self.target
    }
}

impl<A: Arch, C> Index<usize> for Dataflows<A, C> {
    type Output = Dataflow<A, C>;

    fn index(&self, index: usize) -> &Dataflow<A, C> {
        &self.outputs[index]
    }
}

impl<A: Arch, C> IndexMut<usize> for Dataflows<A, C> {
    fn index_mut(&mut self, index: usize) -> &mut Dataflow<A, C> {
        &mut self.outputs[index]
    }
}

impl<A: Arch, C> Debug for Dataflow<A, C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "[{:?}] <{}= {{ ",
            self.target,
            if self.unobservable_external_inputs { "*?" } else { "" }
        )?;

        for input in self.inputs.iter() {
            write!(f, "{input:?} ")?;
        }

        write!(f, "}}")?;

        Ok(())
    }
}

impl<A: Arch, C> Dataflows<A, C> {
    /// Returns the instruction for which these dataflow apply.
    pub fn instr(&self) -> &Instruction {
        &self.addresses.instr
    }

    /// Iterates over all dataflows.
    pub fn output_dataflows(&self) -> impl Iterator<Item = &Dataflow<A, C>> {
        self.outputs.iter()
    }

    /// Returns the dataflow at position `index`.
    pub fn output_dataflow(&self, index: usize) -> &Dataflow<A, C> {
        &self.outputs[index]
    }

    fn iter_with_locations(&self) -> impl Iterator<Item = FlowGroup<'_, A>> {
        self.outputs.iter().enumerate().map(|(output_index, output)| FlowGroup {
            inputs: &output.inputs,
            target: Some(&output.target),
            location: FlowOutputLocation::Output(output_index),
        })
    }

    fn inputs(&self) -> impl Iterator<Item = (FlowInputLocation, &Source<A>)> {
        self.iter_with_locations().flat_map(|g| g.iter_with_locations())
    }

    /// Returns all sources in these dataflows.
    pub fn values(&self) -> impl Iterator<Item = (FlowValueLocation, Source<A>)> + '_ {
        self.inputs().map(|(loc, input)| (loc.into(), *input)).chain(
            self.iter_with_locations()
                .map(|g| (g.location(), g.target()))
                .filter_map(|x| match x {
                    (FlowOutputLocation::Output(output_index), Some(dest)) => {
                        Some((FlowValueLocation::Output(output_index), Source::Dest(*dest)))
                    },
                    (FlowOutputLocation::MemoryAccess(_), None) => None,
                    _ => unreachable!(),
                }),
        )
    }

    /// Returns the dataflow with `target` set to `loc`.
    pub fn get(&self, loc: &Dest<A>) -> Option<&Dataflow<A, C>> {
        self.outputs.iter().find(|flow| &flow.target == loc)
    }

    /// Returns the memory areas read or written by these dataflows.
    pub fn extract_memory_areas<'a>(&'a self, state: &'a SystemState<A>) -> impl Iterator<Item = Area> + 'a {
        self.addresses
            .iter()
            .map(|access| Area::new(access.compute_address(state), access.size.end))
    }

    /// Executes the dataflows on `state`, modifying the `state`.
    pub fn execute(&self, state: &mut SystemState<A>)
    where
        C: Computation,
    {
        // TODO: Verify addresses are mapped correctly
        let outputs = self
            .outputs
            .iter()
            .map(|flow| {
                let inputs = flow
                    .inputs
                    .iter()
                    .map(|input| match input {
                        Source::Dest(dest) => state.get_dest(dest),
                        Source::Imm(_) => panic!("No imms should be here"),
                        Source::Const {
                            value, ..
                        } => Value::Num(*value),
                    })
                    .collect::<Vec<_>>();
                let output = flow.computation.as_ref().unwrap().evaluate(&inputs);
                trace!(
                    "{:X?} with {} -> {:X?}",
                    inputs,
                    flow.computation.as_ref().unwrap().display(ARG_NAMES),
                    output
                );
                (flow.target, output)
            })
            .collect::<Vec<_>>();

        for (target, value) in outputs {
            state.set_dest(
                &target,
                &match &value {
                    OwnedValue::Num(n) => Value::Num(*n),
                    OwnedValue::Bytes(b) => Value::Bytes(b),
                },
            );
        }
    }

    /// Maps all computations in the dataflows to new values.
    pub fn map_computations<CNew>(&self, f: impl Fn(&Inputs<A>, &C) -> Option<CNew>) -> Dataflows<A, CNew> {
        let outputs = self
            .outputs
            .iter()
            .map(|flow| Dataflow {
                target: flow.target,
                inputs: flow.inputs.clone(),
                unobservable_external_inputs: flow.unobservable_external_inputs,
                computation: flow.computation.as_ref().and_then(|c| f(&flow.inputs, c)),
            })
            .collect();

        Dataflows {
            addresses: self.addresses.clone(),
            outputs,
            found_dependent_bytes: self.found_dependent_bytes,
        }
    }

    /// Splits flag outputs in the dataflow with position `index` into individual bytes.
    pub fn split_flag_output(&mut self, index: usize) -> usize {
        let output = self.outputs.remove(index);
        let mut num = 0;
        match output.target {
            Dest::Reg(r, size) if r.is_flags() => {
                for byte in size.start_byte..=size.end_byte {
                    let mut inputs = output.inputs.clone();
                    let s = Source::Dest(Dest::Reg(r, Size::new(byte, byte)));
                    if !inputs.contains(&s) {
                        inputs.push(s);
                    }

                    num += 1;
                    self.outputs.push(Dataflow {
                        target: Dest::Reg(r, Size::new(byte, byte)),
                        inputs,
                        unobservable_external_inputs: output.unobservable_external_inputs,
                        computation: None,
                    });
                }
            },
            _ => unimplemented!(),
        }

        num
    }

    /// Maps each source and destination in the dataflows and memory accesses to new values.
    pub fn map(
        &self, instr: Instruction, map_flows: impl Fn(FlowValueLocation, &Source<A>) -> Option<Source<A>>,
        map_address_computations: impl Fn(usize, &AddressComputation) -> Option<AddressComputation>,
    ) -> Dataflows<A, C>
    where
        C: Clone,
    {
        let addresses = self.addresses.map(instr, &map_flows, map_address_computations);
        let outputs = self
            .outputs
            .iter()
            .enumerate()
            .map(|(output_index, flow)| Dataflow {
                target: map_flows(FlowValueLocation::Output(output_index), &Source::Dest(flow.target))
                    .unwrap()
                    .unwrap_dest(),
                inputs: Inputs::unsorted(
                    flow.inputs
                        .iter()
                        .enumerate()
                        .flat_map(|(input_index, input)| {
                            map_flows(
                                FlowValueLocation::InputForOutput {
                                    output_index,
                                    input_index,
                                },
                                input,
                            )
                        })
                        .collect::<Vec<_>>(),
                ),
                unobservable_external_inputs: flow.unobservable_external_inputs,
                computation: flow.computation.clone(),
            })
            .collect::<Vec<_>>();

        Dataflows {
            addresses,
            outputs,
            found_dependent_bytes: self.found_dependent_bytes,
        }
    }

    /// Adds an immediate value to all outputs in `output_indices`.
    /// Returns a list containing the locations of the inserted [`Source::Imm`]s.
    pub fn insert_imm_value(&mut self, output_indices: impl Iterator<Item = usize>, part_index: usize) -> Vec<FlowInputLocation> {
        let mut result = Vec::new();
        for index in output_indices {
            let values = &mut self.outputs[index].inputs;

            result.push(FlowInputLocation::InputForOutput {
                output_index: index,
                input_index: values.len(),
            });
            values.push(Source::Imm(part_index));
        }

        result
    }

    /// Adds an immediate value to all memory accesses and outputs in `locations`.
    /// Returns a list containing the locations of the inserted [`Source::Imm`]s.
    pub fn insert_memory_imms(
        &mut self, locations: &[FlowOutputLocation], offset: i64, part_index: usize,
    ) -> Vec<FlowInputLocation>
    where
        C: Debug,
    {
        let mut result = Vec::new();

        for &location in locations.iter() {
            match location {
                FlowOutputLocation::Output(index) => {
                    let inputs = &mut self.outputs[index].inputs;
                    result.push(location.input(inputs.len()));
                    inputs.push(Source::Imm(part_index));
                },
                FlowOutputLocation::MemoryAccess(index) => {
                    let access = &mut self.addresses[index];
                    assert!(
                        access.inputs.iter().all(|input| !matches!(input, Source::Imm(_))),
                        "Memory access {index} already contains an immediate value: {self:?}"
                    );

                    result.push(FlowInputLocation::MemoryAddress {
                        memory_index: index,
                        input_index: access.inputs.len(),
                    });

                    access.inputs.push(Source::Imm(part_index));
                    access.calculation.offset = access.calculation.offset.wrapping_sub(offset);
                    access.calculation.add_constant_term();
                },
            }
        }

        result
    }

    /// Returns a list of dataflows that overlap with the list provided in `output_dataflows`.
    pub fn overlapping_outputs<'a>(
        &'a self, output_dataflows: &'a [&'a Dataflow<A, C>],
    ) -> impl Iterator<Item = &'a Dataflow<A, C>> {
        self.output_dataflows().filter(|other_output| {
            output_dataflows
                .iter()
                .any(|output_dataflow| other_output.target.overlaps(&output_dataflow.target))
        })
    }
}

#[derive(Debug)]
struct FlowGroup<'a, A: Arch> {
    inputs: &'a Inputs<A>,
    target: Option<&'a Dest<A>>,
    location: FlowOutputLocation,
}

impl<'a, A: Arch> FlowGroup<'a, A> {
    pub fn location(&self) -> FlowOutputLocation {
        self.location
    }

    pub fn iter_with_locations(&self) -> impl Iterator<Item = (FlowInputLocation, &'a Source<A>)> {
        let location = self.location;
        self.inputs
            .iter()
            .enumerate()
            .map(move |(index, el)| (location.input(index), el))
    }

    pub fn target(&self) -> Option<&'a Dest<A>> {
        self.target
    }
}

impl<A: Arch, C: Computation> Display for Dataflows<A, C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{:?} {:02X?}", self.instr(), self.instr().bytes())?;

        for (index, access) in self.addresses.iter().enumerate() {
            write!(
                f,
                "{:10} = ",
                format!(
                    "Addr{}(m{})",
                    match access.kind {
                        AccessKind::Executable => "X ",
                        AccessKind::Input => "R ",
                        AccessKind::InputOutput => "RW",
                    },
                    index
                )
            )?;

            let names = access.inputs.iter().map(|input| format!("{}", input)).collect::<Vec<_>>();

            writeln!(f, "{}", access.calculation.display(&names))?;
        }

        for output in self.output_dataflows() {
            match &output.computation {
                Some(computation) => {
                    let names = output.inputs.iter().map(|input| input.to_string()).collect::<Vec<_>>();

                    writeln!(
                        f,
                        "{:10} := {}",
                        format!("{}", output.target.clone()),
                        computation.display(&names)
                    )?;
                },
                None => {
                    writeln!(f, "{:10} := {}", format!("{}", output.target.clone()), output.inputs)?;
                },
            }
        }

        Ok(())
    }
}