|
| 1 | +import idaapi |
| 2 | + |
| 3 | +from .vector import Vector |
| 4 | + |
| 5 | + |
| 6 | +class FlatGraphVector(Vector): |
| 7 | + type = 'flatgraph_editdistance' |
| 8 | + type_version = 0 |
| 9 | + |
| 10 | + def __init__(self, *args, **kwargs): |
| 11 | + super(FlatGraphVector, self).__init__(*args, **kwargs) |
| 12 | + self.flow_chart = idaapi.FlowChart(idaapi.get_func(self.offset)) |
| 13 | + self.visited = set() |
| 14 | + self.items = list[self.flow_chart.size] |
| 15 | + |
| 16 | + def _bb_size(self, bb): |
| 17 | + if bb.endEA > bb.startEA: |
| 18 | + return bb.endEA - bb.startEA |
| 19 | + |
| 20 | + raise ValueError("while flattening graph, a basicblock that ends before " |
| 21 | + "it starts encountered at {:x}".format(self.offset)) |
| 22 | + |
| 23 | + def _bb_value(self, bb): |
| 24 | + # TODO: this should be something that's uncorellated with the order of |
| 25 | + # basic blocks |
| 26 | + return self._bb_size(bb) |
| 27 | + |
| 28 | + def _append_bbs(self, *bbs): |
| 29 | + self.items.extend(map(self._bb_value, bbs)) |
| 30 | + |
| 31 | + def _find_head(self): |
| 32 | + def is_head(bb): |
| 33 | + return len(bb.preds()) == 0 |
| 34 | + |
| 35 | + heads = filter(is_head, self.flow_chart) |
| 36 | + if len(heads) == 1: |
| 37 | + return heads[0] |
| 38 | + |
| 39 | + msg = ("flattening graphs with head count other than 1 is not supported, " |
| 40 | + "got {} head-count for {:x}".format(len(heads), self.offset)) |
| 41 | + raise ValueError(msg) |
| 42 | + |
| 43 | + def _sort_siblings(self, siblings): |
| 44 | + return sorted(siblings, key=self._bb_size) |
| 45 | + |
| 46 | + def _recurse_bb(self, bb): |
| 47 | + if bb in self.visited: |
| 48 | + return [] |
| 49 | + |
| 50 | + self.visited.add(bb) |
| 51 | + siblings = self._sort_siblings(bb.succs()) |
| 52 | + self._append_bbs(*siblings) |
| 53 | + |
| 54 | + for sibling in siblings: |
| 55 | + self._recurse_siblings(sibling) |
| 56 | + |
| 57 | + def _data(self): |
| 58 | + head = self._find_head() |
| 59 | + self._recurse_bb(head) |
| 60 | + return self.items |
0 commit comments