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
use std::collections::HashMap;
use std::hash::Hash;

use termion::color;

use SyntaxedSSARender;
use yaxpeax_arch::{Arch, Colorize, ColorSettings, LengthedInstruction};
use arch::display::BaseDisplay;
use arch::CommentQuery;
use arch::FunctionQuery;
use arch::FunctionRepr;
use arch::InstructionSpan;
use arch::pic17;
use arch::pic17::{ContextRead, PartialInstructionContext};
use yaxpeax_pic17::{Opcode, Operand, PIC17};
use analyses::control_flow;
use analyses::control_flow::{ControlFlowGraph, Determinant};
use memory::MemoryRange;
use data::ValueLocations;
use data::Direction;
use std::fmt;

use analyses::static_single_assignment::SSA;

// TODO: should this whole thing be deleted lol
impl <T> SyntaxedSSARender<PIC17, T, pic17::Function> for yaxpeax_pic17::Instruction where T: pic17::PartialInstructionContext {
    fn render_with_ssa_values(
        &self,
        address: <PIC17 as Arch>::Address,
        colors: Option<&ColorSettings>,
        context: Option<&T>,
        function_table: &HashMap<<PIC17 as Arch>::Address, pic17::Function>,
        ssa: &SSA<PIC17>) -> String {

        fn render_function(address: <PIC17 as Arch>::Address, function_table: &HashMap<<PIC17 as Arch>::Address, pic17::Function>) -> String {
            match function_table.get(&address) {
                Some(fn_dec) => {
                    format!("{}{}{}",
                        color::Fg(&color::LightYellow as &dyn color::Color),
                        // TODO: show values
                        fn_dec.decl_string(false),
                        color::Fg(&color::Reset as &dyn color::Color)
                    )
                },
                None => { format!("#{:08x}", address) }
            }
        }

        fn render_operand<T: PartialInstructionContext>(_address: <PIC17 as Arch>::Address, operand: &Operand, context: Option<&T>, _ssa: &SSA<PIC17>, _direction: Direction) -> String {
            match operand {
                Operand::ImmediateU8(i) => {
                    format!("#{:02x}", i)
                },
                Operand::ImmediateU32(i) => {
                    format!("#{:08x}", i)
                },
                Operand::File(f) => {
                    let name = match ::arch::pic17::cpu::try_debank(*f, context) {
                        Some(num) => ::arch::pic17::named_file(num).to_string(),
                        None => format!("[banked 0x{:02x}]", f)
                    };
                    format!("{}{}{}",
                        color::Fg(color::Yellow),
                        name,
                        color::Fg(color::Reset)
                    )
                },
                Operand::W => {
                    format!("{}W{}",
                        color::Fg(color::Yellow),
                        color::Fg(color::Reset)
                    )
                },
                _ => { "".to_owned() }
            }
        }

        let mut result = String::new();
        self.opcode.colorize(&colors, &mut result).expect("can append colorized opcode");

        match self.opcode {
            Opcode::LCALL => {
                result.push_str(" ");

                let control_flow = self.control_flow(context);
                match control_flow.dest {
                    Some(control_flow::Target::Absolute(addr)) => {
                        result.push_str(&render_function(addr * 2, function_table));
                    }
                    Some(control_flow::Target::Indeterminate) => {
                        match self.operands[0] {
                            Operand::ImmediateU8(i) => {
                                // TODO: distinguish from pclath==0 lcall and pclath==??? lcall
                                result.push_str(&format!("#{:08x}", (i as u16) * 2));
                            },
                            // LCALL's first operand is always a u8
                            _ => { unreachable!(); }
                        }
                    },
                    // LCALL always has control flow, and either it's
                    // an absolute destination, or unknown (contextual)
                    _ => { unreachable!(); }
                }
            },
            Opcode::CALL |
            Opcode::GOTO => {
                match self.operands[0] {
                    Operand::ImmediateU32(i) => {
                        result.push(' ');
                        result.push_str(&render_function((i as u16) * 2, function_table));
                    },
                    _ => {
                        unreachable!()
                    }
                };
            },
            _ => {
                let (rw0, rw1) = match self.opcode {
                    _ => { (Direction::Read, Direction::Read) }
                };
                match self.operands[0] {
                    Operand::Nothing => { return result; },
                    x @ _ => {
                        result.push(' ');
                        result.push_str(&render_operand(address, &x, context, ssa, rw0));
                    }
                };
                match self.operands[1] {
                    Operand::Nothing => { return result; },
                    x @ _ => {
                        result.push(',');
                        result.push(' ');
                        result.push_str(&render_operand(address, &x, context, ssa, rw1));
                    }
                };
            }
        };
        result
    }
}

impl <F: FunctionRepr, T> BaseDisplay<F, T> for PIC17 where T: FunctionQuery<<PIC17 as Arch>::Address, Function=F> + CommentQuery<<PIC17 as Arch>::Address> {
    fn render_frame<Data: Iterator<Item=u8> + ?Sized, W: fmt::Write>(
        dest: &mut W,
        addr: u16,
        _instr: &<PIC17 as Arch>::Instruction,
        bytes: &mut Data,
        ctx: Option<&T>,
    ) -> fmt::Result {
        if let Some(ctx) = ctx {
            if let Some(comment) = ctx.comment_for(addr) {
                writeln!(dest, "{:04x}: {}{}{}",
                    addr,
                    color::Fg(&color::Blue as &dyn color::Color),
                    comment,
                    color::Fg(&color::Reset as &dyn color::Color)
                )?;
            }
            if let Some(fn_dec) = ctx.function_at(addr) {
                writeln!(dest, "      {}{}{}",
                    color::Fg(&color::LightYellow as &dyn color::Color),
                    // TODO: show values
                    fn_dec.decl_string(false),
                    color::Fg(&color::Reset as &dyn color::Color)
                )?;
            }
        }
        write!(
            dest,
//            "{:04x}: {}{}: |{}|",
            "{:04x}: {}{}: | |",
            addr,
            bytes.next().map(|x| format!("{:02x}", x)).unwrap_or("  ".to_owned()),
            bytes.next().map(|x| format!("{:02x}", x)).unwrap_or("  ".to_owned()),
            //ctx.map(|c| c.indicator_tag()).unwrap_or("   ".to_owned())
        )
    }
}

pub fn render_instruction_with_ssa_values<T>(
    address: <PIC17 as Arch>::Address,
    instr: &<PIC17 as Arch>::Instruction,
    colors: Option<&ColorSettings>,
    ctx: Option<&T>,
    function_table: &HashMap<u16, pic17::Function>,
    ssa: &SSA<PIC17>
) where
    T: pic17::PartialInstructionContext,
    <PIC17 as ValueLocations>::Location: Eq + Hash,
    <PIC17 as Arch>::Address: Eq + Hash,
    <PIC17 as Arch>::Instruction: SyntaxedSSARender<PIC17, T, pic17::Function> {
    println!(" {}", instr.render_with_ssa_values(address, colors, ctx, function_table, ssa))
}

pub fn show_linear_with_blocks<M: MemoryRange<PIC17>>(
    _data: &M,
    _ctx: &pic17::MergedContextTable,
    _function_table: &HashMap<<PIC17 as Arch>::Address, pic17::Function>,
    cfg: &ControlFlowGraph<<PIC17 as Arch>::Address>,
    start_addr: <PIC17 as Arch>::Address,
    end_addr: <PIC17 as Arch>::Address,
    _colors: Option<&ColorSettings>) {
    let continuation = start_addr;
    while continuation < end_addr {
        // Do we have a block here?
        let block = cfg.get_block(continuation);
        // now, get_block doesn't consult if it's something we've explored
        // in the cfg or just free unused space, so let's check that...
        if cfg.graph.contains_node(block.start) {
        }

        // TODO:
        let _end = if block.end < end_addr {
            block.end
        } else {
            end_addr
        };
        // haha actually we don't do anything one way or the other.
        // so just use the end of this block as an indication of where
        // to stop linear disassembly here
        //
        // start at continuation because this linear disassembly
        // might start at the middle of a preexisting block
        unimplemented!("\
        arch::display::show_linear(data, ctx, continuation, end, function_table, colors);\
        ");

        // and continue on right after this block

        // continuation = block.end + <PIC17 as Arch>::Address::from(1u16);
    }
}

pub fn show_functions(
    _data: &[u8],
    _ctx: &pic17::MergedContextTable,
    _cfg: &ControlFlowGraph<<PIC17 as Arch>::Address>,
    _addr: <PIC17 as Arch>::Address) {

}

pub fn show_function_by_ssa<M: MemoryRange<PIC17>>(
    data: &M,
    colors: Option<&ColorSettings>,
    ctx: &pic17::MergedContextTable,
    function_table: &HashMap<<PIC17 as Arch>::Address, pic17::Function>,
    cfg: &ControlFlowGraph<<PIC17 as Arch>::Address>,
    addr: <PIC17 as Arch>::Address,
    ssa: &SSA<PIC17>) {

    let fn_graph = cfg.get_function(addr, function_table);

    let mut blocks: Vec<<PIC17 as Arch>::Address> = fn_graph.blocks.keys().cloned().collect();
    blocks.sort();

    for blockaddr in blocks.iter() {
        let block = cfg.get_block(*blockaddr);
        if block.start == 0x00 { continue; }

        if ssa.phi.contains_key(&block.start) {
            println!("phi: {:?}", ssa.phi[&block.start].keys());
        }

        let mut iter = PIC17::instructions_spanning(data, block.start, block.end);
        while let Some((address, instr)) = iter.next() {
            let mut instr_string = String::new();
            PIC17::render_frame(
                &mut instr_string,
                address,
                instr,
                &mut data.range(address..(address + instr.len())).unwrap(),
                Some(ctx),
            ).unwrap();
            print!("{}", instr_string);
            render_instruction_with_ssa_values(
                address,
                instr,
                colors,
                Some(&ctx.at(&address)),
                function_table,
                ssa
            );
        }
    }
}