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
use yaxpeax_arch::Arch;
use yaxpeax_arch::Decoder;
use arch::DecodeFrom;
use analyses::control_flow;
use analyses::static_single_assignment::SSA;
use analyses::xrefs;
use memory::MemoryRepr;
use self::analyses::data_flow::DefaultCallingConvention;

use petgraph::graphmap::GraphMap;

use std::collections::HashMap;
use std::collections::HashSet;
use yaxpeax_x86::x86_64;
use std::rc::Rc;
use std::cell::RefCell;
use std::cell::Ref;
use num_traits::Zero;

use arch::{BaseUpdate, CommentQuery, FunctionLayout, FunctionImpl, FunctionQuery, Symbol, SymbolQuery, Library};
use data::ValueLocations;
use data::modifier::InstructionModifiers;
use timing::Timings;

use ContextRead;
use ContextWrite;

pub mod analyses;
pub mod cpu;
#[cfg(target_os = "linux")]
pub mod debug;
pub mod display;
pub mod semantic;

impl<M: MemoryRepr<Self> + ?Sized> DecodeFrom<M> for x86_64 {
    fn decode_with_decoder_into<'mem>(
        decoder: &Self::Decoder,
        cursor: &crate::memory::repr::ReadCursor<'mem, Self, M>,
        instr: &mut Self::Instruction
    ) -> Result<(), Self::DecodeError> {
        let mut reader = cursor.to_reader();
        decoder.decode_into(instr, &mut reader)
    }
}

// TODO: DataMemo needs to be updated to serialize symbolic expression graphs
// #[derive(Serialize, Deserialize)]
#[allow(non_camel_case_types)]
pub struct x86_64Data {
//    #[serde(skip)]
    pub timings: Timings<<x86_64 as Arch>::Address>,
    pub preferred_addr: <x86_64 as Arch>::Address,
    pub contexts: MergedContextTable,
    pub cfg: control_flow::ControlFlowGraph<<x86_64 as Arch>::Address>,
    pub ssa: HashMap<<x86_64 as Arch>::Address, (
        control_flow::ControlFlowGraph<<x86_64 as Arch>::Address>,
        SSA<x86_64>
    )>,
}

pub struct DisplayCtx<'a> {
    functions: Ref<'a, HashMap<<x86_64 as Arch>::Address, FunctionImpl<<x86_64 as ValueLocations>::Location>>>,
    comments: &'a HashMap<<x86_64 as Arch>::Address, String>,
    symbols: &'a HashMap<<x86_64 as Arch>::Address, Symbol>,
}

impl FunctionQuery<<x86_64 as Arch>::Address> for x86_64Data {
    type Function = FunctionImpl<<x86_64 as ValueLocations>::Location>;
    // TODO: !!!
    fn function_at(&self, _addr: <x86_64 as Arch>::Address) -> Option<&Self::Function> {
        unimplemented!("FunctionQuery::function_at for x86_64Data");
    }
    fn all_functions(&self) -> Vec<&Self::Function> {
        unimplemented!("FunctionQuery::all_functions for x86_64Data");
    }
}

impl CommentQuery<<x86_64 as Arch>::Address> for MergedContextTable {
    fn comment_for(&self, addr: <x86_64 as Arch>::Address) -> Option<&str> {
        self.comments.get(&addr).map(String::as_ref)
    }
}

impl FunctionQuery<<x86_64 as Arch>::Address> for MergedContextTable {
    type Function = FunctionImpl<<x86_64 as ValueLocations>::Location>;
    // TODO: !!!
    fn function_at(&self, _addr: <x86_64 as Arch>::Address) -> Option<&Self::Function> {
        unimplemented!("FunctionQuery::function_at for MergedContextTable");
    }
    fn all_functions(&self) -> Vec<&Self::Function> {
        unimplemented!("FunctionQuery::all_functions for MergedContextTable");
    }
}

impl SymbolQuery<<x86_64 as Arch>::Address> for x86_64Data {
    fn symbol_for(&self, addr: <x86_64 as Arch>::Address) -> Option<&Symbol> {
        self.contexts.symbols.get(&addr)
    }
    fn symbol_addr(&self, sym: &Symbol) -> Option<<x86_64 as Arch>::Address> {
        for (k, v) in self.contexts.symbols.iter() {
            if v == sym {
                return Some(*k);
            }
        }

        None
    }
}

impl<'a> FunctionQuery<<x86_64 as Arch>::Address> for DisplayCtx<'a> {
    type Function = FunctionImpl<<x86_64 as ValueLocations>::Location>;
    fn function_at(&self, addr: <x86_64 as Arch>::Address) -> Option<&Self::Function> {
        self.functions.function_at(addr)
    }
    fn all_functions(&self) -> Vec<&Self::Function> {
        self.functions.all_functions()
    }
}

impl<'a> CommentQuery<<x86_64 as Arch>::Address> for DisplayCtx<'a> {
    fn comment_for(&self, addr: <x86_64 as Arch>::Address) -> Option<&str> {
        self.comments.get(&addr).map(String::as_ref)
    }
}

impl<'a> SymbolQuery<<x86_64 as Arch>::Address> for DisplayCtx<'a> {
    fn symbol_for(&self, addr: <x86_64 as Arch>::Address) -> Option<&Symbol> {
        self.symbols.get(&addr)
    }
    fn symbol_addr(&self, sym: &Symbol) -> Option<<x86_64 as Arch>::Address> {
        for (k, v) in self.symbols.iter() {
            if v == sym {
                return Some(*k);
            }
        }

        None
    }
}

impl Default for x86_64Data {
    fn default() -> Self {
        x86_64Data {
            timings: Timings::new(),
            preferred_addr: <x86_64 as Arch>::Address::zero(),
            contexts: MergedContextTable::create_empty(),
            cfg: control_flow::ControlFlowGraph::new(),
            ssa: HashMap::new(),
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct MergedContextTable {
    pub user_contexts: HashMap<<x86_64 as Arch>::Address, Rc<()>>,
    pub computed_contexts: HashMap<<x86_64 as Arch>::Address, Rc<()>>,
    pub comments: HashMap<<x86_64 as Arch>::Address, String>,
    #[serde(skip)]
    pub call_graph: GraphMap<<x86_64 as Arch>::Address, (), petgraph::Directed>,
    #[serde(skip)]
    pub xrefs: xrefs::XRefCollection<<x86_64 as Arch>::Address>,
    pub symbols: HashMap<<x86_64 as Arch>::Address, Symbol>,
    #[serde(skip)]
    pub reverse_symbols: HashMap<Symbol, <x86_64 as Arch>::Address>,
    pub functions: Rc<RefCell<HashMap<<x86_64 as Arch>::Address, FunctionImpl<<x86_64 as ValueLocations>::Location>>>>,
    pub function_data: HashMap<<x86_64 as Arch>::Address, RefCell<InstructionModifiers<x86_64>>>,
    pub function_hints: Vec<<x86_64 as Arch>::Address>,
    functions_hinted: HashSet<<x86_64 as Arch>::Address>,
    pub default_abi: Option<DefaultCallingConvention>,
}

#[derive(Debug)]
pub struct MergedContext {
    pub computed: Option<Rc<()>>,
    pub user: Option<Rc<()>>
}

impl Default for MergedContextTable {
    fn default() -> Self {
        MergedContextTable::create_empty()
    }
}

impl MergedContextTable {
    pub fn fn_count(&self) -> usize {
        self.functions.borrow().len()
    }
    pub fn create_empty() -> MergedContextTable {
        MergedContextTable {
            user_contexts: HashMap::new(),
            computed_contexts: HashMap::new(),
            comments: HashMap::new(),
            call_graph: GraphMap::new(),
            xrefs: xrefs::XRefCollection::new(),
            functions: Rc::new(RefCell::new(HashMap::new())),
            function_hints: Vec::new(),
            functions_hinted: HashSet::new(),
            symbols: HashMap::new(),
            reverse_symbols: HashMap::new(),
            function_data: HashMap::new(),
            default_abi: Some(DefaultCallingConvention::Microsoft), //None,
        }
    }

    pub fn display_ctx(&self) -> DisplayCtx {
        DisplayCtx {
            functions: self.functions.borrow(),
            symbols: &self.symbols,
            comments: &self.comments,
        }
    }
}

/*
pub enum Value {
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    U128(u64, u64),
    U256(u64, u64, u64, u64),
    U512(u64, u64, u64, u64, u64, u64, u64, u64)
}

trait PartialInstructionContext {
    pub fn reg_value(reg: RegSpec) -> Option<Value>;
    pub fn mem_value(addr: u64, width: u8) -> Option<Value>;
}
*/

pub type Update = BaseUpdate<x86Update>;

#[derive(Debug)]
#[allow(non_camel_case_types)]
pub enum x86Update {
    AddXRef(xrefs::RefType, xrefs::RefAction, <x86_64 as Arch>::Address),
    RemoveXRef(xrefs::RefType, xrefs::RefAction, <x86_64 as Arch>::Address),
    FunctionHint
}

impl ContextRead<x86_64, MergedContext> for MergedContextTable {
    fn at(&self, address: &<x86_64 as Arch>::Address) -> MergedContext {
        MergedContext {
            user: self.user_contexts.get(address).map(|v| Rc::clone(v)),
            computed: self.computed_contexts.get(address).map(|v| Rc::clone(v))
        }
    }
}

impl ContextWrite<x86_64, Update> for MergedContextTable {
    fn put(&mut self, address: <x86_64 as Arch>::Address, update: Update) {
        // println!("Applying update: {} -> {:?}", address.stringy(), update);
        match update {
            BaseUpdate::Specialized(x86Update::FunctionHint) => {
                if !self.functions.borrow().contains_key(&address) && !self.functions_hinted.contains(&address) {
//                    println!("Function hint: {}", address.stringy());
                    self.functions_hinted.insert(address);
                    self.function_hints.push(address)
                }
            },
            BaseUpdate::Specialized(x86Update::AddXRef(tpe, action, dest)) => {
                // TODO: xrefs from non-code sources
                self.xrefs.insert_from_code(tpe, action, address, dest);
            },
            BaseUpdate::Specialized(x86Update::RemoveXRef(tpe, action, dest)) => {
                self.xrefs.delete_from_code(tpe, action, address, dest);
            }
            BaseUpdate::DefineSymbol(sym) => {
                //println!("address of {:?} recorded at {}", sym, address.stringy());
                if !self.symbols.contains_key(&address) {
                    match Symbol::to_function(&sym) {
                        Some(f) => {
                            if let Some(abi) = self.default_abi {
                                self.functions.borrow_mut().insert(address, f.implement_for(FunctionLayout::for_abi(abi)));
                            } else {
                                // TODO: indicate that the function should have been defined, but
                                // was not because we don't know an ABI to map it to?
                                self.functions.borrow_mut().insert(address, f.unimplemented());
                            }
                        }
                        None => { }
                    }
                    self.symbols.insert(address, sym.clone());
                    self.reverse_symbols.insert(sym, address);
                }
            }
            BaseUpdate::DefineFunction(f) => {
                if !self.functions.borrow().contains_key(&address) {
                    self.symbols.insert(address, Symbol(Library::This, f.name.clone()));
                    self.reverse_symbols.insert(Symbol(Library::This, f.name.clone()), address);
                    if let Some(abi) = self.default_abi {
                        self.functions.borrow_mut().insert(address, f.implement_for(FunctionLayout::for_abi(abi)));
                    } else {
                        // TODO: indicate that the function should have been defined, but was not
                        // because we don't know an ABI to map it to?
                        self.functions.borrow_mut().insert(address, f.unimplemented());
                    }
                }
            }
            BaseUpdate::AddCodeComment(comment) => {
                self.comments.insert(address, comment);
            }
            _ => { /* todo: the rest */ }
        }
    }
}