rsleigh 0.4.2

SLEIGH (.slaspec) parser and Rust decoder/P-code emitter codegen — Ghidra-compatible disassembly in pure Rust
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
use std::ops::Range;

use crate::{
    AttachNumberId, AttachVarnodeId, Number, NumberNonZeroUnsigned, NumberUnsigned, Sleigh, Span,
};

use super::{
    disassembly, BitrangeId, ContextId, InstNext, InstStart, SpaceId, TableId, TokenFieldId,
    UserFunctionId, VarnodeId,
};

#[derive(Clone, Copy, Debug)]
pub enum ExportLen {
    /// value that is known at Dissassembly time
    Const(NumberNonZeroUnsigned),
    /// value that can be know at execution time
    Value(NumberNonZeroUnsigned),
    /// References/registers and other mem locations, all with the same size
    Reference(NumberNonZeroUnsigned),
    /// If each table exports a diferent type, could happen in individual
    /// constructors, if it exports a sub_table that export Multiple
    Multiple(NumberNonZeroUnsigned),
}

impl ExportLen {
    pub fn len(&self) -> NumberNonZeroUnsigned {
        match self {
            Self::Const(len) | Self::Value(len) | Self::Reference(len) | Self::Multiple(len) => {
                *len
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct Execution {
    pub(crate) variables: Box<[Variable]>,
    pub(crate) blocks: Box<[Block]>,
    pub(crate) export: Option<ExportLen>,

    // TODO make this a const, the first block is always the entry block
    //entry_block have no name and is not on self.labels
    pub entry_block: BlockId,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BlockId(pub usize);

#[derive(Clone, Debug)]
pub struct Block {
    //None is entry block, NOTE name may not be unique due to macro expansions
    pub name: Option<Box<str>>,
    pub next: Option<BlockId>,
    pub statements: Box<[Statement]>,
}

#[derive(Clone, Debug)]
pub enum Statement {
    Delayslot(NumberUnsigned),
    Export(Export),
    CpuBranch(CpuBranch),
    LocalGoto(LocalGoto),
    UserCall(UserCall),
    Build(Build),
    Declare(VariableId),
    Assignment(Assignment),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct VariableId(pub usize);

#[derive(Clone, Debug)]
pub struct Variable {
    pub(crate) name: Box<str>,
    pub len_bits: NumberNonZeroUnsigned,
    pub location: Option<Span>,
}

#[derive(Clone, Debug)]
pub enum Expr {
    Value(ExprElement),
    Op(ExprBinaryOp),
}
impl Expr {
    pub fn len_bits(&self, sleigh: &Sleigh, execution: &Execution) -> NumberNonZeroUnsigned {
        match self {
            Expr::Value(value) => value.len_bits(sleigh, execution),
            Expr::Op(op) => op.len_bits,
        }
    }
}

#[derive(Clone, Debug)]
pub struct ExprBinaryOp {
    pub location: Span,
    pub len_bits: NumberNonZeroUnsigned,
    pub op: Binary,
    pub left: Box<Expr>,
    pub right: Box<Expr>,
}

#[derive(Clone, Debug)]
pub enum ExprElement {
    Value { location: Span, value: ExprValue },
    UserCall(UserCall),
    Reference(Reference),
    Op(ExprUnaryOp),
    New(ExprNew),
    CPool(ExprCPool),
}
impl ExprElement {
    fn len_bits(&self, sleigh: &Sleigh, execution: &Execution) -> NumberNonZeroUnsigned {
        match self {
            Self::Value { value, .. } => value.len_bits(sleigh, execution),
            Self::UserCall(_x) => {
                // User functions don't declare return size in SLEIGH;
                // default to address size.
                NumberNonZeroUnsigned::new(sleigh.addr_bytes().get() as u64 * 8).unwrap()
            }
            Self::Reference(x) => x.len_bits,
            Self::Op(x) => x.len_bits(sleigh, execution),
            Self::New(_x) => {
                // ExprNew only appears in JVM/WASM specs — default to 64 bits.
                NumberNonZeroUnsigned::new(64).unwrap()
            }
            Self::CPool(_x) => {
                // ExprCPool only appears in JVM/WASM specs — default to 64 bits.
                NumberNonZeroUnsigned::new(64).unwrap()
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct Reference {
    pub location: Span,
    pub len_bits: NumberNonZeroUnsigned,
    pub value: ReferencedValue,
}

#[derive(Clone, Debug)]
pub struct ExprUnaryOp {
    pub location: Span,
    pub op: Unary,
    pub input: Box<Expr>,
}

impl ExprUnaryOp {
    pub fn len_bits(&self, sleigh: &Sleigh, execution: &Execution) -> NumberNonZeroUnsigned {
        match &self.op {
            Unary::TakeLsb(len) => (len.get() * 8).try_into().unwrap(),
            Unary::TrunkLsb { trunk: _, bits } => *bits,
            Unary::BitRange { range: _, bits } => *bits,
            Unary::Dereference(mem) => mem.len_bytes,
            Unary::Zext(bits)
            | Unary::Sext(bits)
            | Unary::Popcount(bits)
            | Unary::Lzcount(bits)
            | Unary::FloatNan(bits)
            | Unary::SignTrunc(bits)
            | Unary::Float2Float(bits)
            | Unary::Int2Float(bits) => *bits,
            Unary::Negation
            | Unary::BitNegation
            | Unary::Negative
            | Unary::FloatNegative
            | Unary::FloatAbs
            | Unary::FloatSqrt
            | Unary::FloatCeil
            | Unary::FloatFloor
            | Unary::FloatRound => self.input.len_bits(sleigh, execution),
        }
    }
}

#[derive(Clone, Debug)]
pub struct ExprNew {
    pub location: Span,
    pub first: Box<Expr>,
    pub second: Option<Box<Expr>>,
}

#[derive(Clone, Debug)]
pub struct ExprCPool {
    pub location: Span,
    pub params: Box<[Expr]>,
}

#[derive(Clone, Debug)]
pub struct UserCall {
    pub location: Span,
    pub function: UserFunctionId,
    pub params: Box<[Expr]>,
}

#[derive(Clone, Debug)]
pub enum ExprValue {
    /// Simple Int value
    Int(ExprNumber),
    /// Context/TokenField value translated into a Int
    IntDynamic(ExprDynamicInt),
    InstStart(InstStart),
    InstNext(InstNext),
    /// simple TokenField, no attachment
    TokenField(ExprTokenField),
    /// simple Context, no attachment
    Context(ExprContext),
    /// A Varnode Value
    Varnode(VarnodeId),
    /// A Context/TokenField translated into a varnode
    VarnodeDynamic(ExprVarnodeDynamic),
    /// Dynamic Int from Context or TokenField
    Bitrange(ExprBitrange),
    Table(TableId),
    DisVar(ExprDisVar),
    ExeVar(VariableId),
}

impl ExprValue {
    pub fn len_bits(&self, sleigh: &Sleigh, execution: &Execution) -> NumberNonZeroUnsigned {
        match self {
            Self::Int(x) => x.size,
            Self::TokenField(x) => x.size,
            Self::InstStart(_) | Self::InstNext(_) => {
                (sleigh.addr_bytes().get() * 8).try_into().unwrap()
            }
            Self::Varnode(x) => (sleigh.varnode(*x).len_bytes.get() * 8).try_into().unwrap(),
            Self::Context(x) => sleigh.context(x.id).bitrange.bits.len(),
            Self::Bitrange(x) => sleigh.bitrange(x.id).bits.len(),
            Self::Table(x) => sleigh.table(*x).export.unwrap().len(),
            Self::DisVar(x) => x.size,
            Self::ExeVar(x) => execution.variable(*x).len_bits,
            Self::IntDynamic(ExprDynamicInt { bits, .. }) => *bits,
            Self::VarnodeDynamic(ExprVarnodeDynamic { attach_id, .. }) => {
                sleigh.attach_varnode(*attach_id).len_bytes(sleigh)
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct ExprNumber {
    pub size: NumberNonZeroUnsigned,
    pub number: Number,
}

#[derive(Clone, Debug)]
pub struct ExprDynamicInt {
    pub attach_id: AttachNumberId,
    pub attach_value: DynamicValueType,
    pub bits: NumberNonZeroUnsigned,
}

#[derive(Clone, Debug)]
pub struct ExprVarnodeDynamic {
    pub attach_id: AttachVarnodeId,
    pub attach_value: DynamicValueType,
}

#[derive(Clone, Debug)]
pub struct ExprTokenField {
    pub size: NumberNonZeroUnsigned,
    pub id: TokenFieldId,
}

#[derive(Clone, Debug)]
pub enum ExprVarnode {
    Static(VarnodeId),
    Dynamic {
        attach_id: AttachVarnodeId,
        attach_value: DynamicValueType,
    },
}

/// Only used for types with attachment values to Varnodes/Ints
#[derive(Copy, Clone, Debug)]
pub enum DynamicValueType {
    TokenField(TokenFieldId),
    Context(ContextId),
}

#[derive(Clone, Debug)]
pub struct ExprContext {
    pub size: NumberNonZeroUnsigned,
    pub id: ContextId,
}

#[derive(Clone, Debug)]
pub struct ExprBitrange {
    pub size: NumberNonZeroUnsigned,
    pub id: BitrangeId,
}

#[derive(Clone, Debug)]
pub struct ExprDisVar {
    pub size: NumberNonZeroUnsigned,
    pub id: disassembly::VariableId,
}

#[derive(Clone, Debug)]
pub enum ReferencedValue {
    //only if translate into varnode
    TokenField(RefTokenField),
    InstStart(RefInstStart),
    InstNext(RefInstNext),
    Table(RefTable),
}

#[derive(Clone, Debug)]
pub struct RefTokenField {
    pub location: Span,
    pub id: TokenFieldId,
}

#[derive(Clone, Debug)]
pub struct RefInstStart {
    pub location: Span,
    pub data: InstStart,
}

#[derive(Clone, Debug)]
pub struct RefInstNext {
    pub location: Span,
    pub data: InstNext,
}

#[derive(Clone, Debug)]
pub struct RefTable {
    pub location: Span,
    pub id: TableId,
}

#[derive(Clone, Debug)]
pub struct CpuBranch {
    pub cond: Option<Expr>,
    pub call: BranchCall,
    pub direct: bool,
    pub dst: Expr,
}

#[derive(Clone, Debug, Copy)]
pub enum BranchCall {
    Goto,
    Call,
    Return,
}

#[derive(Clone, Debug)]
pub struct LocalGoto {
    pub cond: Option<Expr>,
    pub dst: BlockId,
}

#[derive(Clone, Debug)]
pub struct Assignment {
    /// assigment location
    pub location: Span,
    /// left side of the assignment location
    pub var: AssignmentWrite,
    pub right: Expr,
}

#[derive(Clone, Debug)]
pub enum AssignmentWrite {
    Variable {
        value: AssignmentWriteVariable,
        op: Option<AssignmentOp>,
    },
    Memory {
        mem: MemoryLocation,
        addr: Expr,
    },
    // write to memory based on the table export
    TableExport {
        table_id: TableId,
        op: Option<AssignmentOp>,
        // number of bytes to write in case of memory reference
        size: Option<NumberNonZeroUnsigned>,
    },
}

#[derive(Clone, Debug)]
pub enum AssignmentWriteVariable {
    Varnode(VarnodeId),
    Bitrange(BitrangeId),
    DynVarnode {
        value_id: DynamicValueType,
        attach_id: AttachVarnodeId,
    },
    Variable(VariableId),
}

#[derive(Clone, Debug)]
pub enum AssignmentOp {
    TakeLsb(NumberNonZeroUnsigned),
    TrunkLsb(NumberUnsigned),
    BitRange(Range<NumberUnsigned>),
}

#[derive(Clone, Debug)]
pub struct Build {
    pub location: Span,
    pub table: TableId,
}

#[derive(Clone, Debug)]
pub enum Export {
    /// Reference to a memory
    /// NOTE not the same as deref a memory address
    /// a regular Expr Deref exports the result on a deref.
    /// a Export Deref export the location itself, and read/write is done a demand
    Reference { addr: Expr, memory: MemoryLocation },
    /// a value that translate into a varnode (AKA reference with extra steps)
    AttachVarnode {
        location: Span,
        attach_value: DynamicValueType,
        attach_id: AttachVarnodeId,
    },
    /// a subtable re-exported
    Table { location: Span, table_id: TableId },

    /// other complex expressions
    Value(Expr),
}

impl Export {
    pub fn len_bits(&self, sleigh: &Sleigh, execution: &Execution) -> NumberNonZeroUnsigned {
        match self {
            Export::Value(value) => value.len_bits(sleigh, execution),
            Export::Reference { addr: _, memory } => {
                (memory.len_bytes.get() * 8).try_into().unwrap()
            }
            Export::AttachVarnode { attach_id, .. } => {
                (sleigh.attach_varnodes_len_bytes(*attach_id).get() * 8)
                    .try_into()
                    .unwrap()
            }
            Export::Table { table_id, .. } => {
                let table = sleigh.table(*table_id);
                table.export.unwrap().len()
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct MemoryLocation {
    pub location: Span,
    pub space: SpaceId,
    pub len_bytes: NumberNonZeroUnsigned,
}

#[derive(Clone, Debug)]
pub enum Unary {
    TakeLsb(NumberNonZeroUnsigned),
    TrunkLsb {
        trunk: NumberUnsigned,
        bits: NumberNonZeroUnsigned,
    },
    // BitRange have an auto Sext to it
    BitRange {
        range: Range<NumberUnsigned>,
        bits: NumberNonZeroUnsigned,
    },
    Dereference(MemoryLocation),
    //Reference(AddrReference),
    Zext(NumberNonZeroUnsigned),
    Sext(NumberNonZeroUnsigned),
    Popcount(NumberNonZeroUnsigned),
    Lzcount(NumberNonZeroUnsigned),
    FloatNan(NumberNonZeroUnsigned),
    /// NOTE don't confuse signed truncation with regular truncation
    /// sleigh `trunc` function converts float into interger
    SignTrunc(NumberNonZeroUnsigned),
    Float2Float(NumberNonZeroUnsigned),
    Int2Float(NumberNonZeroUnsigned),

    /// output size is just the input size
    Negation,
    BitNegation,
    Negative,
    FloatNegative,
    FloatAbs,
    FloatSqrt,
    FloatCeil,
    FloatFloor,
    FloatRound,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Binary {
    //Binary Arithmetic
    Mult,
    Div,
    SigDiv,
    Rem,
    FloatDiv,
    FloatMult,
    Add,
    Sub,
    FloatAdd,
    FloatSub,
    Lsl,
    Lsr,
    Asr,
    BitAnd,
    BitXor,
    BitOr,
    //Binary Logical
    SigLess,
    SigGreater,
    SigRem,
    SigLessEq,
    SigGreaterEq,
    Less,
    Greater,
    LessEq,
    GreaterEq,
    FloatLess,
    FloatGreater,
    FloatLessEq,
    FloatGreaterEq,
    And,
    Xor,
    Or,
    Eq,
    Ne,
    FloatEq,
    FloatNe,
    //call functions
    Carry,
    SCarry,
    SBorrow,
}

impl Variable {
    pub fn name(&self) -> &str {
        &self.name
    }
}

impl Execution {
    pub fn variables(&self) -> &[Variable] {
        &self.variables
    }

    pub fn blocks(&self) -> &[Block] {
        &self.blocks
    }

    pub fn block(&self, id: BlockId) -> &Block {
        &self.blocks[id.0]
    }

    pub fn export_len(&self) -> Option<ExportLen> {
        self.export
    }

    pub fn export(&self) -> impl Iterator<Item = &Export> {
        self.blocks.iter().filter_map(|block| {
            block
                .statements
                .last()
                .and_then(|statement| match statement {
                    Statement::Export(export) => Some(export),
                    _ => None,
                })
        })
    }

    pub fn variable(&self, var: VariableId) -> &Variable {
        &self.variables[var.0]
    }
}