pcode-graph 3.0.2__tar.gz → 4.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/CHANGELOG +13 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/PKG-INFO +3 -4
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/README.md +1 -3
- pcode_graph-3.0.2/pcode_graph/memory.py → pcode_graph-4.1.0/pcode_graph/analysis/alias_analysis.py +59 -56
- pcode_graph-4.1.0/pcode_graph/analysis/cfg.py +119 -0
- pcode_graph-4.1.0/pcode_graph/analysis/def_use.py +116 -0
- pcode_graph-4.1.0/pcode_graph/analysis/load_store.py +164 -0
- pcode_graph-4.1.0/pcode_graph/analysis/native_pcode.py +78 -0
- pcode_graph-4.1.0/pcode_graph/analysis/pass_base.py +9 -0
- pcode_graph-4.1.0/pcode_graph/analysis/passes.py +16 -0
- pcode_graph-4.1.0/pcode_graph/analysis/program.py +281 -0
- pcode_graph-4.1.0/pcode_graph/analysis/unreachable.py +17 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/arch.py +4 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/basic_blocks.py +2 -13
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/characterization.py +43 -52
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/checker.py +11 -9
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/cli.py +7 -7
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/graph.py +4 -9
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/maker.py +45 -49
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/pcode.py +2 -2
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/view.py +2 -2
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pyproject.toml +2 -1
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/analysis_test.py +30 -15
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/fixtures.py +2 -2
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/helpers.py +8 -6
- pcode_graph-4.1.0/tests/load_store_test.py +110 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/maker_test.py +30 -35
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/memory_test.py +74 -44
- pcode_graph-3.0.2/pcode_graph/analysis.py +0 -528
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/.github/workflows/release.yml +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/.github/workflows/test.yml +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/.gitignore +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/LICENSE +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/__init__.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/__main__.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/asm.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/bit_utils.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/emulator.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/gnn_exporter.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/lief_importer.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/log.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/nx_exporter.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/registers.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/simplifier.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/torch_utils.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/translator.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/pcode_graph/visitor.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/requirements.txt +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/__init__.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/basic_block_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/callother_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/charac_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/cli_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/conftest.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/emulator_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/exporter_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/lief_importer_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/translator_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/tests/utils_test.py +0 -0
- {pcode_graph-3.0.2 → pcode_graph-4.1.0}/todo.md +0 -0
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
# 4.1.0
|
|
2
|
+
|
|
3
|
+
- Replace networkx by igraph to speed up graph characteristics computation.
|
|
4
|
+
|
|
5
|
+
# 4.0.0
|
|
6
|
+
|
|
7
|
+
- New memory model to avoid quadratic edges generation in many-stores code:
|
|
8
|
+
- Remove ReadMemory and WrittenMemory nodes
|
|
9
|
+
- Now STORE nodes have no more data output: memory writes are implicit
|
|
10
|
+
- LOAD and STORE nodes are inserted to deal with indirect accesses in Pcode operations
|
|
11
|
+
- Memory analysis is now run unconditionally
|
|
12
|
+
|
|
13
|
+
|
|
1
14
|
# 3.0.2
|
|
2
15
|
|
|
3
16
|
- Improve simplifier complexity (for graph with many edges.)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: pcode_graph
|
|
3
|
-
Version:
|
|
3
|
+
Version: 4.1.0
|
|
4
4
|
Summary: Build, display and vectorize semantic graphs from binary code
|
|
5
5
|
Project-URL: Homepage, https://github.com/quarkslab/pcode_graph
|
|
6
6
|
Project-URL: Issues, https://github.com/quarkslab/pcode_graph/issues
|
|
@@ -12,6 +12,7 @@ Classifier: Programming Language :: Python :: 3
|
|
|
12
12
|
Classifier: Topic :: Security
|
|
13
13
|
Requires-Python: >=3.12
|
|
14
14
|
Requires-Dist: docopt
|
|
15
|
+
Requires-Dist: igraph~=1.0.0
|
|
15
16
|
Requires-Dist: keystone-engine~=0.9.2
|
|
16
17
|
Requires-Dist: lief~=1.0.0
|
|
17
18
|
Requires-Dist: loguru
|
|
@@ -150,9 +151,7 @@ graph = make_graph_from_asm(assembler, translator, asm)
|
|
|
150
151
|
|
|
151
152
|
### Pointer alias analysis
|
|
152
153
|
|
|
153
|
-
Addresses are resolved relatively to the stack pointer at entry, to link each
|
|
154
|
-
|
|
155
|
-
A part from this, no advanced alias analysis is performed and no assumption is made about the used ABI.
|
|
154
|
+
Addresses are resolved relatively to the stack pointer at entry, or as absolute constants, to link each LOAD to the values written by the STOREs. Stack and absolute addresses are supposed not to alias each other. Apart from this, no advanced alias analysis is performed and no assumption is made about the used ABI: calls to unknown code and stores to unresolved addresses may write anywhere.
|
|
156
155
|
|
|
157
156
|
### View the graph
|
|
158
157
|
|
|
@@ -123,9 +123,7 @@ graph = make_graph_from_asm(assembler, translator, asm)
|
|
|
123
123
|
|
|
124
124
|
### Pointer alias analysis
|
|
125
125
|
|
|
126
|
-
Addresses are resolved relatively to the stack pointer at entry, to link each
|
|
127
|
-
|
|
128
|
-
A part from this, no advanced alias analysis is performed and no assumption is made about the used ABI.
|
|
126
|
+
Addresses are resolved relatively to the stack pointer at entry, or as absolute constants, to link each LOAD to the values written by the STOREs. Stack and absolute addresses are supposed not to alias each other. Apart from this, no advanced alias analysis is performed and no assumption is made about the used ABI: calls to unknown code and stores to unresolved addresses may write anywhere.
|
|
129
127
|
|
|
130
128
|
### View the graph
|
|
131
129
|
|
pcode_graph-3.0.2/pcode_graph/memory.py → pcode_graph-4.1.0/pcode_graph/analysis/alias_analysis.py
RENAMED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
"""Summary analysis of stack memory accesses.
|
|
1
|
+
"""Summary analysis of stack and static memory accesses.
|
|
2
2
|
|
|
3
3
|
LOAD and STORE addresses are resolved relatively to the stack pointer value at the entry
|
|
4
|
-
of the code, so that loads can be linked to the stores they read.
|
|
5
|
-
spilled variables, as found in code compiled without optimization (-O0)
|
|
4
|
+
of the code, or as absolute constants, so that loads can be linked to the stores they read.
|
|
5
|
+
This mainly targets spilled variables, as found in code compiled without optimization (-O0),
|
|
6
|
+
and global variables.
|
|
6
7
|
|
|
7
8
|
No assumption is made on the use of the stack: calls to unknown code and stores to
|
|
8
|
-
unresolved addresses may write anywhere, so the loads they reach
|
|
9
|
+
unresolved addresses may write anywhere, so the loads they reach remain unresolved.
|
|
10
|
+
Stack and absolute addresses are supposed not to alias each other.
|
|
9
11
|
"""
|
|
10
12
|
|
|
11
13
|
from dataclasses import dataclass, field
|
|
@@ -13,11 +15,13 @@ import heapq
|
|
|
13
15
|
|
|
14
16
|
from pypcode import OpCode, PcodeOp
|
|
15
17
|
|
|
18
|
+
from pcode_graph.analysis.pass_base import PassBase
|
|
16
19
|
from pcode_graph.arch import Arch
|
|
17
|
-
from pcode_graph.analysis import (
|
|
20
|
+
from pcode_graph.analysis.program import (
|
|
18
21
|
EntryIndex,
|
|
22
|
+
Memory,
|
|
19
23
|
OpIndex,
|
|
20
|
-
|
|
24
|
+
Program,
|
|
21
25
|
UnknownCodeIndex,
|
|
22
26
|
Var,
|
|
23
27
|
VarKinds,
|
|
@@ -49,50 +53,57 @@ class StackAddress:
|
|
|
49
53
|
# Known constant, stack address or unknown value
|
|
50
54
|
AbstractValue = int | StackAddress | None
|
|
51
55
|
|
|
56
|
+
# Tracked memory byte: (is relative to the stack, offset or absolute address)
|
|
57
|
+
MemoryByte = tuple[bool, int]
|
|
58
|
+
|
|
52
59
|
|
|
53
60
|
@dataclass(frozen=True, slots=True)
|
|
54
|
-
class
|
|
61
|
+
class MemoryAccess:
|
|
62
|
+
in_stack: bool
|
|
55
63
|
offset: int
|
|
56
64
|
size: int
|
|
57
65
|
|
|
58
66
|
@property
|
|
59
|
-
def
|
|
60
|
-
return
|
|
67
|
+
def bytes(self) -> list[MemoryByte]:
|
|
68
|
+
return [
|
|
69
|
+
(self.in_stack, offset)
|
|
70
|
+
for offset in range(self.offset, self.offset + self.size)
|
|
71
|
+
]
|
|
61
72
|
|
|
62
73
|
|
|
63
74
|
@dataclass(frozen=True, slots=True)
|
|
64
|
-
class
|
|
65
|
-
# Definitions of tracked bytes
|
|
66
|
-
tracked: dict[
|
|
75
|
+
class MemoryState:
|
|
76
|
+
# Definitions of tracked bytes
|
|
77
|
+
tracked: dict[MemoryByte, frozenset[OpIndex]]
|
|
67
78
|
|
|
68
79
|
# Definitions of untracked bytes
|
|
69
80
|
default: frozenset[OpIndex]
|
|
70
81
|
|
|
71
|
-
def read(self, access:
|
|
82
|
+
def read(self, access: MemoryAccess) -> frozenset[OpIndex]:
|
|
72
83
|
return frozenset().union(
|
|
73
|
-
*(self.tracked.get(
|
|
84
|
+
*(self.tracked.get(byte, self.default) for byte in access.bytes)
|
|
74
85
|
)
|
|
75
86
|
|
|
76
|
-
def write(self, access:
|
|
87
|
+
def write(self, access: MemoryAccess, index: OpIndex) -> "MemoryState":
|
|
77
88
|
written = frozenset({index})
|
|
78
89
|
tracked = dict(self.tracked)
|
|
79
|
-
for
|
|
80
|
-
tracked[
|
|
81
|
-
return
|
|
90
|
+
for byte in access.bytes:
|
|
91
|
+
tracked[byte] = written
|
|
92
|
+
return MemoryState(tracked, self.default)
|
|
82
93
|
|
|
83
|
-
def clobber(self) -> "
|
|
94
|
+
def clobber(self) -> "MemoryState":
|
|
84
95
|
unknown = {UnknownWriteIndex}
|
|
85
|
-
return
|
|
86
|
-
{
|
|
96
|
+
return MemoryState(
|
|
97
|
+
{byte: defs | unknown for byte, defs in self.tracked.items()},
|
|
87
98
|
self.default | unknown,
|
|
88
99
|
)
|
|
89
100
|
|
|
90
|
-
def merge(self, other: "
|
|
91
|
-
return
|
|
101
|
+
def merge(self, other: "MemoryState") -> "MemoryState":
|
|
102
|
+
return MemoryState(
|
|
92
103
|
{
|
|
93
|
-
|
|
94
|
-
| other.tracked.get(
|
|
95
|
-
for
|
|
104
|
+
byte: self.tracked.get(byte, self.default)
|
|
105
|
+
| other.tracked.get(byte, other.default)
|
|
106
|
+
for byte in self.tracked.keys() | other.tracked.keys()
|
|
96
107
|
},
|
|
97
108
|
self.default | other.default,
|
|
98
109
|
)
|
|
@@ -102,34 +113,23 @@ ADDRESS_OPCODES = {OpCode.COPY, OpCode.INT_ADD, OpCode.INT_SUB, OpCode.INT_OR}
|
|
|
102
113
|
CALL_OPCODES = {OpCode.CALL, OpCode.CALLIND, OpCode.CALLOTHER}
|
|
103
114
|
|
|
104
115
|
|
|
105
|
-
|
|
106
|
-
class StackMemory:
|
|
107
|
-
"""Results of the stack memory analysis."""
|
|
108
|
-
|
|
109
|
-
# Maps a stack-reading LOAD to possible STORE definitions
|
|
110
|
-
load_defs: dict[OpIndex, set[OpIndex]] = field(default_factory=dict)
|
|
111
|
-
|
|
112
|
-
# Maps a load to defining stores if reading exactly the values written by them
|
|
113
|
-
forwarded_loads: dict[OpIndex, list[OpIndex]] = field(default_factory=dict)
|
|
114
|
-
|
|
116
|
+
class MemoryAnalyzer(PassBase):
|
|
115
117
|
|
|
116
|
-
def
|
|
117
|
-
|
|
118
|
+
def __init__(self, program: Program) -> None:
|
|
119
|
+
super().__init__(program)
|
|
118
120
|
|
|
119
|
-
|
|
120
|
-
class StackMemoryAnalyzer:
|
|
121
|
-
|
|
122
|
-
def __init__(self, program: RichPcodeList) -> None:
|
|
123
|
-
self.program = program
|
|
124
121
|
self.stack_pointer = STACK_POINTERS.get(program.arch)
|
|
125
|
-
self.result = StackMemory()
|
|
126
122
|
self._output_values: dict[OpIndex, AbstractValue] = {}
|
|
127
|
-
self._loads: dict[OpIndex,
|
|
128
|
-
self._stores: dict[OpIndex,
|
|
123
|
+
self._loads: dict[OpIndex, MemoryAccess] = {}
|
|
124
|
+
self._stores: dict[OpIndex, MemoryAccess | None] = {}
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def result(self) -> Memory:
|
|
128
|
+
return self.program.memory
|
|
129
129
|
|
|
130
|
-
def __call__(self)
|
|
130
|
+
def __call__(self):
|
|
131
131
|
if self.stack_pointer is None or not self.program.basic_blocks:
|
|
132
|
-
return
|
|
132
|
+
return
|
|
133
133
|
|
|
134
134
|
for index, op in enumerate(self.program.operations):
|
|
135
135
|
if not self.program.reachable(index):
|
|
@@ -145,7 +145,7 @@ class StackMemoryAnalyzer:
|
|
|
145
145
|
self._stores[index] = self._compute_access(index, op.inputs[2].size)
|
|
146
146
|
|
|
147
147
|
self._collect_load_defs(self._compute_reads())
|
|
148
|
-
|
|
148
|
+
|
|
149
149
|
|
|
150
150
|
def value_of(self, index: OpIndex, var: Var) -> AbstractValue:
|
|
151
151
|
"""Evaluates the given variable when read by the given operation."""
|
|
@@ -202,14 +202,17 @@ class StackMemoryAnalyzer:
|
|
|
202
202
|
return value
|
|
203
203
|
return None
|
|
204
204
|
|
|
205
|
-
def _compute_access(self, index: OpIndex, size: int) ->
|
|
205
|
+
def _compute_access(self, index: OpIndex, size: int) -> MemoryAccess | None:
|
|
206
206
|
address = self.value_of(index, wrap(self.program.operations[index].inputs[1]))
|
|
207
|
-
|
|
208
|
-
|
|
207
|
+
match address:
|
|
208
|
+
case StackAddress(offset):
|
|
209
|
+
return MemoryAccess(True, offset, size)
|
|
210
|
+
case int(absolute):
|
|
211
|
+
return MemoryAccess(False, absolute, size)
|
|
209
212
|
return None
|
|
210
213
|
|
|
211
|
-
def _apply(self, index: OpIndex, state:
|
|
212
|
-
"""Returns the
|
|
214
|
+
def _apply(self, index: OpIndex, state: MemoryState) -> MemoryState:
|
|
215
|
+
"""Returns the memory state after the given operation."""
|
|
213
216
|
|
|
214
217
|
op = self.program.operations[index]
|
|
215
218
|
if op.opcode == OpCode.STORE:
|
|
@@ -225,8 +228,8 @@ class StackMemoryAnalyzer:
|
|
|
225
228
|
"""Computes the definitions of the bytes read by each resolved load."""
|
|
226
229
|
|
|
227
230
|
blocks = self.program.basic_blocks
|
|
228
|
-
block_inputs: list[
|
|
229
|
-
block_inputs[0] =
|
|
231
|
+
block_inputs: list[MemoryState | None] = [None] * len(blocks)
|
|
232
|
+
block_inputs[0] = MemoryState({}, frozenset({EntryIndex}))
|
|
230
233
|
reads: dict[OpIndex, frozenset[OpIndex]] = {}
|
|
231
234
|
pending = [0]
|
|
232
235
|
queued = {0}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from typing import override
|
|
2
|
+
|
|
3
|
+
from pypcode import OpCode, PcodeOp
|
|
4
|
+
|
|
5
|
+
from pcode_graph.analysis.pass_base import PassBase
|
|
6
|
+
from pcode_graph.bit_utils import unsigned_to_signed
|
|
7
|
+
from pcode_graph.pcode import from_native_opcode
|
|
8
|
+
|
|
9
|
+
from .program import (
|
|
10
|
+
BasicBlock,
|
|
11
|
+
EntryIndex,
|
|
12
|
+
ExitIndex,
|
|
13
|
+
OpIndex,
|
|
14
|
+
Program,
|
|
15
|
+
UnknownCodeIndex,
|
|
16
|
+
Address,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CFGBuilder(PassBase):
|
|
21
|
+
|
|
22
|
+
def __init__(self, program: Program) -> None:
|
|
23
|
+
super().__init__(program)
|
|
24
|
+
|
|
25
|
+
# First P-Code operation for each instruction address
|
|
26
|
+
self.addresses: dict[Address, OpIndex] = {}
|
|
27
|
+
|
|
28
|
+
def __call__(self):
|
|
29
|
+
# First collects instruction addresses encoded in IMARK operations
|
|
30
|
+
for i, op in enumerate(self.program.operations):
|
|
31
|
+
if op.opcode == OpCode.IMARK:
|
|
32
|
+
self.addresses[op.inputs[0].offset] = i
|
|
33
|
+
|
|
34
|
+
# Successors of jumping operations
|
|
35
|
+
self._jumps: dict[OpIndex, list[OpIndex]] = {}
|
|
36
|
+
for index, op in enumerate(self.program.operations):
|
|
37
|
+
self.visit(from_native_opcode(op.opcode), index, op)
|
|
38
|
+
|
|
39
|
+
op_count = len(self.program.operations)
|
|
40
|
+
leaders = {0} | {index + 1 for index in self._jumps}
|
|
41
|
+
for targets in self._jumps.values():
|
|
42
|
+
leaders.update(target for target in targets if target >= 0)
|
|
43
|
+
sorted_leaders = sorted(leaders - {op_count}) if op_count else []
|
|
44
|
+
|
|
45
|
+
self.program.basic_blocks = []
|
|
46
|
+
self.program.block_indexes = []
|
|
47
|
+
for start, end in zip(sorted_leaders, sorted_leaders[1:] + [op_count]):
|
|
48
|
+
self.program.block_indexes.extend(
|
|
49
|
+
[len(self.program.basic_blocks)] * (end - start)
|
|
50
|
+
)
|
|
51
|
+
self.program.basic_blocks.append(BasicBlock(start, end))
|
|
52
|
+
|
|
53
|
+
for block_index, block in enumerate(self.program.basic_blocks):
|
|
54
|
+
last_index = block.last_op_index
|
|
55
|
+
for successor in self._jumps.get(
|
|
56
|
+
last_index, [self._next_index(last_index)]
|
|
57
|
+
):
|
|
58
|
+
if successor >= 0:
|
|
59
|
+
successor = self.program.block_indexes[successor]
|
|
60
|
+
self.program.basic_blocks[successor].pred_blocks.add(block_index)
|
|
61
|
+
block.succ_blocks.append(successor)
|
|
62
|
+
|
|
63
|
+
if self.program.basic_blocks:
|
|
64
|
+
self.program.basic_blocks[0].pred_blocks.add(EntryIndex)
|
|
65
|
+
|
|
66
|
+
def _next_index(self, index: OpIndex) -> OpIndex:
|
|
67
|
+
return index + 1 if index + 1 < len(self.program.operations) else ExitIndex
|
|
68
|
+
|
|
69
|
+
def _get_jump_target(self, index: OpIndex, op: PcodeOp) -> OpIndex:
|
|
70
|
+
address = op.inputs[0]
|
|
71
|
+
match address.space.name:
|
|
72
|
+
case "ram":
|
|
73
|
+
return self.addresses.get(address.offset, UnknownCodeIndex)
|
|
74
|
+
case "const":
|
|
75
|
+
# Relative jump inside the current instruction
|
|
76
|
+
target = index + unsigned_to_signed(address.offset, address.size)
|
|
77
|
+
assert 0 <= target < len(self.program.operations)
|
|
78
|
+
return target
|
|
79
|
+
case "register" | "unique":
|
|
80
|
+
return UnknownCodeIndex
|
|
81
|
+
case _ as name:
|
|
82
|
+
raise ValueError(f"Unexpected address space for jump address: {name}")
|
|
83
|
+
|
|
84
|
+
@override
|
|
85
|
+
def visit_default(self, index: OpIndex, op: PcodeOp) -> None:
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
@override
|
|
89
|
+
def visit_branch(self, index: OpIndex, op: PcodeOp) -> None:
|
|
90
|
+
self._jumps[index] = [self._get_jump_target(index, op)]
|
|
91
|
+
|
|
92
|
+
@override
|
|
93
|
+
def visit_branchind(self, index: OpIndex, op: PcodeOp) -> None:
|
|
94
|
+
self._jumps[index] = [self._get_jump_target(index, op)]
|
|
95
|
+
|
|
96
|
+
@override
|
|
97
|
+
def visit_return(self, index: OpIndex, op: PcodeOp) -> None:
|
|
98
|
+
self._jumps[index] = [self._get_jump_target(index, op)]
|
|
99
|
+
|
|
100
|
+
@override
|
|
101
|
+
def visit_call(self, index: OpIndex, op: PcodeOp) -> None:
|
|
102
|
+
target = self._get_jump_target(index, op)
|
|
103
|
+
if target == UnknownCodeIndex:
|
|
104
|
+
# Calling an unseen function: we suppose it returns here after
|
|
105
|
+
self._jumps[index] = [target, self._next_index(index)]
|
|
106
|
+
else:
|
|
107
|
+
self._jumps[index] = [target]
|
|
108
|
+
|
|
109
|
+
@override
|
|
110
|
+
def visit_callind(self, index: OpIndex, op: PcodeOp) -> None:
|
|
111
|
+
self.visit_call(index, op)
|
|
112
|
+
|
|
113
|
+
@override
|
|
114
|
+
def visit_cbranch(self, index: OpIndex, op: PcodeOp) -> None:
|
|
115
|
+
self._jumps[index] = [self._get_jump_target(index, op), self._next_index(index)]
|
|
116
|
+
|
|
117
|
+
@override
|
|
118
|
+
def visit_callother(self, index: OpIndex, op: PcodeOp) -> None:
|
|
119
|
+
self._jumps[index] = [UnknownCodeIndex, self._next_index(index)]
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import heapq
|
|
2
|
+
|
|
3
|
+
from .pass_base import PassBase
|
|
4
|
+
from .program import (
|
|
5
|
+
BasicBlock,
|
|
6
|
+
BlockIndex,
|
|
7
|
+
Definitions,
|
|
8
|
+
EntryIndex,
|
|
9
|
+
Var,
|
|
10
|
+
VarKinds,
|
|
11
|
+
wrap,
|
|
12
|
+
split,
|
|
13
|
+
apply_operation,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ReachingDefBuilder(PassBase):
|
|
18
|
+
|
|
19
|
+
def __call__(self):
|
|
20
|
+
self.program.reaching_defs = [{} for _ in self.program.operations]
|
|
21
|
+
if not self.program.basic_blocks:
|
|
22
|
+
return
|
|
23
|
+
|
|
24
|
+
block_inputs: list[Definitions] = [{} for _ in self.program.basic_blocks]
|
|
25
|
+
|
|
26
|
+
# Initialize
|
|
27
|
+
for index in range(len(self.program.operations)):
|
|
28
|
+
if not self.program.reachable(index):
|
|
29
|
+
continue
|
|
30
|
+
for var in self.program.iter_inputs(index):
|
|
31
|
+
if var.kind == VarKinds.Register:
|
|
32
|
+
for byte in split(var):
|
|
33
|
+
block_inputs[0][byte] = {EntryIndex}
|
|
34
|
+
|
|
35
|
+
# Block effects are computed once, on demand, as (generated defs, killed variables)
|
|
36
|
+
effects: dict[BlockIndex, tuple[Definitions, set[Var]]] = {}
|
|
37
|
+
|
|
38
|
+
# Each reachable block is processed at least once, lowest index first:
|
|
39
|
+
# follows the code layout, close to a reverse post-order.
|
|
40
|
+
# The list is sorted, so it is already a valid heap.
|
|
41
|
+
pending = [
|
|
42
|
+
index
|
|
43
|
+
for index, block in enumerate(self.program.basic_blocks)
|
|
44
|
+
if block.reachable
|
|
45
|
+
]
|
|
46
|
+
queued = set(pending)
|
|
47
|
+
|
|
48
|
+
while pending:
|
|
49
|
+
block_index = heapq.heappop(pending)
|
|
50
|
+
queued.remove(block_index)
|
|
51
|
+
|
|
52
|
+
if block_index not in effects:
|
|
53
|
+
effects[block_index] = self._compute_effect(
|
|
54
|
+
self.program.basic_blocks[block_index]
|
|
55
|
+
)
|
|
56
|
+
generated, killed = effects[block_index]
|
|
57
|
+
outputs = self._apply_effect(block_inputs[block_index], generated, killed)
|
|
58
|
+
|
|
59
|
+
for successor in self.program.basic_blocks[block_index].succ_blocks:
|
|
60
|
+
if successor < 0:
|
|
61
|
+
continue
|
|
62
|
+
changed = self._merge_definitions(block_inputs[successor], outputs)
|
|
63
|
+
if changed and successor not in queued:
|
|
64
|
+
heapq.heappush(pending, successor)
|
|
65
|
+
queued.add(successor)
|
|
66
|
+
|
|
67
|
+
for block, inputs in zip(self.program.basic_blocks, block_inputs):
|
|
68
|
+
if block.reachable:
|
|
69
|
+
self._expand_block(block, inputs)
|
|
70
|
+
|
|
71
|
+
def _compute_effect(self, block: BasicBlock) -> tuple[Definitions, set[Var]]:
|
|
72
|
+
generated: Definitions = {}
|
|
73
|
+
killed: set[Var] = set()
|
|
74
|
+
for index in block.op_indexes:
|
|
75
|
+
op = self.program.operations[index]
|
|
76
|
+
if op.output:
|
|
77
|
+
written = {index}
|
|
78
|
+
for byte in split(wrap(op.output)):
|
|
79
|
+
generated[byte] = written
|
|
80
|
+
killed.add(byte)
|
|
81
|
+
return generated, killed
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def _apply_effect(
|
|
85
|
+
inputs: Definitions, generated: Definitions, killed: set[Var]
|
|
86
|
+
) -> Definitions:
|
|
87
|
+
# Sets are never modified in place, so they can be shared
|
|
88
|
+
outputs = dict(generated)
|
|
89
|
+
for var, defs in inputs.items():
|
|
90
|
+
if var in killed:
|
|
91
|
+
continue
|
|
92
|
+
outputs[var] = outputs[var] | defs if var in outputs else defs
|
|
93
|
+
return outputs
|
|
94
|
+
|
|
95
|
+
def _expand_block(self, block: BasicBlock, inputs: Definitions):
|
|
96
|
+
"""Computes the definitions reaching each operation of the block."""
|
|
97
|
+
|
|
98
|
+
current = inputs
|
|
99
|
+
for index in block.op_indexes:
|
|
100
|
+
self.program.reaching_defs[index] = current
|
|
101
|
+
current = apply_operation(current, index, self.program.operations[index])
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def _merge_definitions(target: Definitions, source: Definitions) -> bool:
|
|
105
|
+
"""Adds source definitions to target ones, returns True if target changed."""
|
|
106
|
+
|
|
107
|
+
changed = False
|
|
108
|
+
for var, defs in source.items():
|
|
109
|
+
target_defs = target.get(var)
|
|
110
|
+
if target_defs is None:
|
|
111
|
+
target[var] = set(defs)
|
|
112
|
+
changed = True
|
|
113
|
+
elif not defs <= target_defs:
|
|
114
|
+
target_defs |= defs
|
|
115
|
+
changed = True
|
|
116
|
+
return changed
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Rewrites direct accesses to "ram" varnodes into explicit LOAD and STORE operations.
|
|
2
|
+
|
|
3
|
+
P-Code may read or write a static memory address directly, as for PC-relative accesses.
|
|
4
|
+
Once rewritten, memory is only accessed through LOAD and STORE.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
from pypcode import OpCode, PcodeOp
|
|
11
|
+
|
|
12
|
+
from .native_pcode import (
|
|
13
|
+
CONST_SPACE,
|
|
14
|
+
JUMP_OPCODES,
|
|
15
|
+
RELATIVE_JUMP_OPCODES,
|
|
16
|
+
UNIQUE_SPACE,
|
|
17
|
+
SyntheticOperation,
|
|
18
|
+
SyntheticVarnode,
|
|
19
|
+
is_data_input,
|
|
20
|
+
)
|
|
21
|
+
from .program import Program
|
|
22
|
+
|
|
23
|
+
from .pass_base import PassBase
|
|
24
|
+
from pcode_graph.bit_utils import signed_to_unsigned, unsigned_to_signed
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _relative_jump_target(index: int, operation: PcodeOp) -> int | None:
|
|
28
|
+
if operation.opcode not in RELATIVE_JUMP_OPCODES:
|
|
29
|
+
return None
|
|
30
|
+
address = operation.inputs[0]
|
|
31
|
+
if address.space.name != "const":
|
|
32
|
+
return None
|
|
33
|
+
return index + unsigned_to_signed(address.offset, address.size)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class LoadStoreInserter(PassBase):
|
|
37
|
+
|
|
38
|
+
def __init__(self, program: Program) -> None:
|
|
39
|
+
|
|
40
|
+
super().__init__(program)
|
|
41
|
+
|
|
42
|
+
self.pointer_size = self.program.arch.pointer_size
|
|
43
|
+
self.next_unique_offset = max(
|
|
44
|
+
(
|
|
45
|
+
varnode.offset + varnode.size
|
|
46
|
+
for operation in self.operations
|
|
47
|
+
for varnode in [operation.output, *operation.inputs]
|
|
48
|
+
if varnode is not None and varnode.space.name == "unique"
|
|
49
|
+
),
|
|
50
|
+
default=0,
|
|
51
|
+
)
|
|
52
|
+
# Temporaries holding the value of static addresses, by (address, size)
|
|
53
|
+
self.cached_values: dict[tuple[int, int], SyntheticVarnode] = {}
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def operations(self):
|
|
57
|
+
return self.program.operations
|
|
58
|
+
|
|
59
|
+
def __call__(self):
|
|
60
|
+
jump_targets = {
|
|
61
|
+
index: target
|
|
62
|
+
for index, operation in enumerate(self.operations)
|
|
63
|
+
if (target := _relative_jump_target(index, operation)) is not None
|
|
64
|
+
}
|
|
65
|
+
reached_by_jump = set(jump_targets.values())
|
|
66
|
+
|
|
67
|
+
expansions: list[list[Any]] = []
|
|
68
|
+
for index, operation in enumerate(self.operations):
|
|
69
|
+
# Cached values are only reused inside straight-line code
|
|
70
|
+
if index in reached_by_jump or operation.opcode == OpCode.IMARK:
|
|
71
|
+
self.cached_values.clear()
|
|
72
|
+
expansions.append(self._expand(operation))
|
|
73
|
+
if operation.opcode in JUMP_OPCODES:
|
|
74
|
+
self.cached_values.clear()
|
|
75
|
+
|
|
76
|
+
starts = [0]
|
|
77
|
+
for expansion in expansions:
|
|
78
|
+
starts.append(starts[-1] + len(expansion))
|
|
79
|
+
|
|
80
|
+
# Relative jumps inside an instruction are shifted by inserted operations
|
|
81
|
+
for index, target in jump_targets.items():
|
|
82
|
+
expansion = expansions[index]
|
|
83
|
+
(position,) = [
|
|
84
|
+
position
|
|
85
|
+
for position, operation in enumerate(expansion)
|
|
86
|
+
if operation.opcode in RELATIVE_JUMP_OPCODES
|
|
87
|
+
]
|
|
88
|
+
jump = expansion[position]
|
|
89
|
+
offset = starts[target] - (starts[index] + position)
|
|
90
|
+
address = jump.inputs[0]
|
|
91
|
+
if offset != unsigned_to_signed(address.offset, address.size):
|
|
92
|
+
new_address = SyntheticVarnode(
|
|
93
|
+
CONST_SPACE, signed_to_unsigned(offset, address.size), address.size
|
|
94
|
+
)
|
|
95
|
+
expansion[position] = SyntheticOperation(
|
|
96
|
+
jump.opcode, [new_address, *jump.inputs[1:]], jump.output
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
self.program.operations = cast(
|
|
100
|
+
list[PcodeOp], [op for expansion in expansions for op in expansion]
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def _expand(self, operation: PcodeOp) -> list[Any]:
|
|
104
|
+
"""Returns the operations replacing the given one."""
|
|
105
|
+
|
|
106
|
+
expansion: list[Any] = []
|
|
107
|
+
inputs = list(operation.inputs)
|
|
108
|
+
changed = False
|
|
109
|
+
for position, varnode in enumerate(operation.inputs):
|
|
110
|
+
if varnode.space.name != "ram" or not is_data_input(
|
|
111
|
+
operation.opcode, position
|
|
112
|
+
):
|
|
113
|
+
continue
|
|
114
|
+
key = (varnode.offset, varnode.size)
|
|
115
|
+
temporary = self.cached_values.get(key)
|
|
116
|
+
if temporary is None:
|
|
117
|
+
temporary = self._new_temporary(varnode.size)
|
|
118
|
+
expansion.append(
|
|
119
|
+
SyntheticOperation(
|
|
120
|
+
OpCode.LOAD,
|
|
121
|
+
[self._space_id(), self._address(varnode.offset)],
|
|
122
|
+
temporary,
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
self.cached_values[key] = temporary
|
|
126
|
+
inputs[position] = temporary # type: ignore
|
|
127
|
+
changed = True
|
|
128
|
+
|
|
129
|
+
output = operation.output
|
|
130
|
+
store = None
|
|
131
|
+
if output is not None and output.space.name == "ram":
|
|
132
|
+
written = range(output.offset, output.offset + output.size)
|
|
133
|
+
for address, size in list(self.cached_values):
|
|
134
|
+
if address < written.stop and written.start < address + size:
|
|
135
|
+
del self.cached_values[(address, size)]
|
|
136
|
+
temporary = self._new_temporary(output.size)
|
|
137
|
+
self.cached_values[(output.offset, output.size)] = temporary
|
|
138
|
+
store = SyntheticOperation(
|
|
139
|
+
OpCode.STORE,
|
|
140
|
+
[self._space_id(), self._address(output.offset), temporary],
|
|
141
|
+
None,
|
|
142
|
+
)
|
|
143
|
+
output = temporary
|
|
144
|
+
changed = True
|
|
145
|
+
|
|
146
|
+
expansion.append(
|
|
147
|
+
SyntheticOperation(operation.opcode, inputs, output)
|
|
148
|
+
if changed
|
|
149
|
+
else operation
|
|
150
|
+
)
|
|
151
|
+
if store is not None:
|
|
152
|
+
expansion.append(store)
|
|
153
|
+
return expansion
|
|
154
|
+
|
|
155
|
+
def _new_temporary(self, size: int) -> SyntheticVarnode:
|
|
156
|
+
temporary = SyntheticVarnode(UNIQUE_SPACE, self.next_unique_offset, size)
|
|
157
|
+
self.next_unique_offset += size
|
|
158
|
+
return temporary
|
|
159
|
+
|
|
160
|
+
def _space_id(self) -> SyntheticVarnode:
|
|
161
|
+
return SyntheticVarnode(CONST_SPACE, 0, self.pointer_size)
|
|
162
|
+
|
|
163
|
+
def _address(self, address: int) -> SyntheticVarnode:
|
|
164
|
+
return SyntheticVarnode(CONST_SPACE, address, self.pointer_size)
|