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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/*
 * Panopticon - A libre disassembler
 * Copyright (C) 2014, 2015  Panopticon authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

//! A basic block is a sequence of Mnemonics that aren't interrupted by incoming or outgoing
//! jumps/branches.
//!
//! Basic blocks always occupy a continuous byte range.


use {Bound, Mnemonic, Statement};
use std::cmp::{max, min};
use std::slice::Iter;

/// An iterator over every Statement in every Mnemonic in a BasicBlock
pub struct StatementIterator<'a> {
    mnemonics: Iter<'a, Mnemonic>,
    statements: Option<Iter<'a, Statement>>,
}

impl<'a> StatementIterator<'a> {
    /// Create a new statement iterator from `mnemonics`
    pub fn new(mnemonics: &'a[Mnemonic]) -> Self {
        StatementIterator {
            mnemonics: mnemonics.iter(),
            statements: None,
        }
    }
    fn get_next(&mut self) -> Option<&'a Statement> {
        let mut statement = None;
        while statement.is_none() {
            let mnemonic = self.mnemonics.next();
            match mnemonic {
                // termination
                None => return None,
                Some(mnemonic) => {
                    let mut statements = mnemonic.instructions.iter();
                    statement = statements.next();
                    self.statements = Some(statements);
                }
            }
        }
        return statement
    }
}

impl<'a> Iterator for StatementIterator<'a> {
    type Item = &'a Statement;
    fn next(&mut self) ->  Option<Self::Item> {
        match self.statements {
            None => (),
            Some(ref mut iter) => {
                match iter.next() {
                    None => (),
                    some => return some
                }
            }
        }
        self.get_next()
    }
}

/// A basic block: a continiuous sequence of mnemonics without any branches in between.
#[derive(PartialEq,Eq,Debug,Serialize,Deserialize,Clone)]
pub struct BasicBlock {
    /// Area the basic block occupies in memory.
    pub area: Bound,
    /// List of mnemonics in to order of execution.
    pub mnemonics: Vec<Mnemonic>,
}

impl BasicBlock {
    /// Returns a new, empty basic block.
    pub fn new() -> BasicBlock {
        BasicBlock { area: Bound::new(0, 0), mnemonics: Vec::new() }
    }

    /// Moves `ms` into a new basic block. Panics if the mnemonics do not occupy a continuous
    /// address range.
    pub fn from_vec(ms: Vec<Mnemonic>) -> BasicBlock {
        let a = ms.iter()
            .fold(
                None, |acc: Option<Bound>, m| if acc == None {
                    return Some(m.area.clone());
                } else {
                    let r1 = &acc.unwrap();
                    let r2 = &m.area;
                    return Some(Bound::new(min(r1.start, r2.start), max(r1.end, r2.end)));
                }
            );
        return BasicBlock { area: a.unwrap_or(Bound::new(0, 0)), mnemonics: ms };
    }

    /// Calls `f` on all RREIL instructions starting from the last.
    pub fn execute_backwards<'a, F>(&'a self, mut f: F)
    where
        F: FnMut(&'a Statement),
    {
        for mne in self.mnemonics.iter().rev() {
            for i in mne.instructions.iter().rev() {
                f(&i);
            }
        }
    }

    /// Calls `f` on all RREIL instructions starting from the first.
    pub fn execute<'a, F>(&'a self, mut f: F)
    where
        F: FnMut(&'a Statement),
    {
        for mne in self.mnemonics.iter() {
            for i in mne.instructions.iter() {
                f(&i);
            }
        }
    }

    /// Calls `f` on all RREIL instructions starting from the first.
    pub fn rewrite<'a, F>(&'a mut self, mut f: F)
    where
        F: FnMut(&'a mut Statement),
    {
        for mne in self.mnemonics.iter_mut() {
            for i in mne.instructions.iter_mut() {
                f(i);
            }
        }
    }

    /// Return a slice of this BasicBlock's mnemonics
    pub fn mnemonics(&self) -> &[Mnemonic] {
        self.mnemonics.as_slice()
    }

    /// Return a mutable slice of this BasicBlock's mnemonics
    pub fn mnemonics_mut(&mut self) -> &mut [Mnemonic] {
        self.mnemonics.as_mut()
    }

    /// Returns an iterator over every statement in every mnemonic in this basic block
    pub fn statements(&self) -> StatementIterator {
        StatementIterator::new(self.mnemonics())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use {Bound, Lvalue, Mnemonic, Operation, Rvalue, Statement};
    use std::borrow::Cow;

    #[test]
    fn construct() {
        let ops1 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i1 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne1 = Mnemonic::new(
            0..10,
            "op1".to_string(),
            "{s} nog".to_string(),
            ops1.iter(),
            i1.iter(),
        )
                .ok()
                .unwrap();

        let ops2 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i2 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne2 = Mnemonic::new(
            10..13,
            "op3".to_string(),
            "{s} nog".to_string(),
            ops2.iter(),
            i2.iter(),
        )
                .ok()
                .unwrap();

        let ops3 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i3 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne3 = Mnemonic::new(
            13..20,
            "op3".to_string(),
            "{s} nog".to_string(),
            ops3.iter(),
            i3.iter(),
        )
                .ok()
                .unwrap();

        let ms = vec![mne1, mne2, mne3];
        let bb1 = BasicBlock::from_vec(ms);

        assert_eq!(bb1.area, Bound::new(0, 20));

        let bb2 = BasicBlock::new();
        assert!(bb1 != bb2);

        let bb3 = BasicBlock::new();
        assert_eq!(bb3, bb2);
    }

    #[test]
    fn execute() {
        let ops1 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i1 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne1 = Mnemonic::new(
            0..10,
            "op1".to_string(),
            "{s} nog".to_string(),
            ops1.iter(),
            i1.iter(),
        )
                .ok()
                .unwrap();

        let ops2 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i2 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne2 = Mnemonic::new(
            10..13,
            "op3".to_string(),
            "{s} nog".to_string(),
            ops2.iter(),
            i2.iter(),
        )
                .ok()
                .unwrap();

        let ms = vec![mne1, mne2];
        let bb = BasicBlock::from_vec(ms);
        let mut vs2 = i1;
        let mut vs1 = Vec::<Statement>::new();

        bb.execute(|i| vs1.push(i.clone()));

        for i in i2.iter() {
            vs2.push(i.clone());
        }

        assert_eq!(vs1, vs2);
    }

    #[test]
    fn rewrite() {
        let ops1 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i1 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne1 = Mnemonic::new(
            0..10,
            "op1".to_string(),
            "{s} nog".to_string(),
            ops1.iter(),
            i1.iter(),
        )
                .ok()
                .unwrap();

        let ops2 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i2 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne2 = Mnemonic::new(
            10..13,
            "op3".to_string(),
            "{s} nog".to_string(),
            ops2.iter(),
            i2.iter(),
        )
                .ok()
                .unwrap();

        let ms = vec![mne1, mne2];
        let mut bb = BasicBlock::from_vec(ms);

        bb.rewrite(
            |i| {
                *i = match &i.assignee {
                    &Lvalue::Variable { name: ref n, size: ref w, subscript: _ } => {
                        Statement {
                            op: i.op.clone(),
                            assignee: Lvalue::Variable { name: n.clone(), size: *w, subscript: None },
                        }
                    }
                    _ => i.clone(),
                };
            }
        );

        let mut ok = true;

        bb.execute(
            |i| match i.assignee {
                Lvalue::Variable { subscript: None, .. } => ok &= true,
                _ => ok = false,
            }
        );

        assert!(ok);
    }

    #[test]
    fn statement_iterator() {
        let ops1 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i1 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne1 = Mnemonic::new(
            0..10,
            "op1".to_string(),
            "{s} nog".to_string(),
            ops1.iter(),
            i1.iter(),
        )
            .ok()
            .unwrap();

        let ops2 = vec![
            Rvalue::new_u8(1),
            Rvalue::Variable {
                name: Cow::Borrowed("a"),
                offset: 0,
                size: 3,
                subscript: None,
            },
        ];
        let i2 = vec![
            Statement {
                op: Operation::Add(Rvalue::new_u8(1), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(2) },
            },
            Statement {
                op: Operation::Add(Rvalue::new_u8(4), Rvalue::new_u8(2)),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(1) },
            },
            Statement {
                op: Operation::Phi(
                    vec![
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(2),
                        },
                        Rvalue::Variable {
                            name: Cow::Borrowed("a"),
                            offset: 0,
                            size: 8,
                            subscript: Some(1),
                        },
                    ]
                ),
                assignee: Lvalue::Variable { name: Cow::Borrowed("a"), size: 8, subscript: Some(3) },
            },
        ];
        let mne2 = Mnemonic::new(
            10..13,
            "op3".to_string(),
            "{s} nog".to_string(),
            ops2.iter(),
            i2.iter(),
        )
                .ok()
                .unwrap();

        let nstatements = i2.len() + i1.len();
        let ms = vec![mne1, mne2];
        let bb1 = BasicBlock::from_vec(ms);

        assert_eq!(bb1.area, Bound::new(0, 13));

        let statements = bb1.statements().collect::<Vec<_>>();
        assert_eq!(statements.len(), nstatements);
    }
}