pcode-graph 4.2.0__py3-none-any.whl → 4.3.0__py3-none-any.whl
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/analysis/alias_analysis.py +26 -4
- pcode_graph/cli.py +24 -8
- pcode_graph/lief_importer.py +196 -49
- pcode_graph/maker.py +4 -2
- pcode_graph/translator.py +76 -10
- {pcode_graph-4.2.0.dist-info → pcode_graph-4.3.0.dist-info}/METADATA +1 -1
- {pcode_graph-4.2.0.dist-info → pcode_graph-4.3.0.dist-info}/RECORD +10 -10
- {pcode_graph-4.2.0.dist-info → pcode_graph-4.3.0.dist-info}/WHEEL +0 -0
- {pcode_graph-4.2.0.dist-info → pcode_graph-4.3.0.dist-info}/entry_points.txt +0 -0
- {pcode_graph-4.2.0.dist-info → pcode_graph-4.3.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -148,6 +148,8 @@ class MemoryAnalyzer(PassBase):
|
|
|
148
148
|
|
|
149
149
|
self.stack_pointer = STACK_POINTERS.get(program.arch)
|
|
150
150
|
self._output_values: dict[OpIndex, AbstractValue] = {}
|
|
151
|
+
# Unevaluated definitions met by _evaluate_from
|
|
152
|
+
self._missing: list[OpIndex] | None = None
|
|
151
153
|
self._loads: dict[OpIndex, MemoryAccess] = {}
|
|
152
154
|
self._stores: dict[OpIndex, MemoryAccess | None] = {}
|
|
153
155
|
|
|
@@ -163,7 +165,6 @@ class MemoryAnalyzer(PassBase):
|
|
|
163
165
|
if not self.program.reachable(index):
|
|
164
166
|
continue
|
|
165
167
|
if op.output is not None:
|
|
166
|
-
# Evaluating in program order bounds the recursion depth
|
|
167
168
|
self._output_value(index, wrap(op.output))
|
|
168
169
|
if op.opcode == OpCode.LOAD:
|
|
169
170
|
access = self._compute_access(index, op.output.size)
|
|
@@ -198,10 +199,31 @@ class MemoryAnalyzer(PassBase):
|
|
|
198
199
|
if op.output is None or wrap(op.output) != var:
|
|
199
200
|
return None
|
|
200
201
|
if index not in self._output_values:
|
|
202
|
+
if op.opcode not in ADDRESS_OPCODES:
|
|
203
|
+
self._output_values[index] = None
|
|
204
|
+
elif self._missing is None:
|
|
205
|
+
self._evaluate_from(index)
|
|
206
|
+
else:
|
|
207
|
+
# Evaluated later by _evaluate_from
|
|
208
|
+
self._missing.append(index)
|
|
209
|
+
return self._output_values.get(index)
|
|
210
|
+
|
|
211
|
+
def _evaluate_from(self, root: OpIndex) -> None:
|
|
212
|
+
"""Evaluates the given operation after its dependencies, without recursion."""
|
|
213
|
+
|
|
214
|
+
pending = [root]
|
|
215
|
+
while pending:
|
|
216
|
+
index = pending[-1]
|
|
201
217
|
# Breaks cycles in loops
|
|
202
|
-
self._output_values
|
|
203
|
-
self.
|
|
204
|
-
|
|
218
|
+
self._output_values.setdefault(index, None)
|
|
219
|
+
self._missing = []
|
|
220
|
+
value = self._evaluate(index, self.program.operations[index])
|
|
221
|
+
if self._missing:
|
|
222
|
+
pending += self._missing
|
|
223
|
+
else:
|
|
224
|
+
self._output_values[index] = value
|
|
225
|
+
pending.pop()
|
|
226
|
+
self._missing = None
|
|
205
227
|
|
|
206
228
|
def _evaluate(self, index: OpIndex, op: PcodeOp) -> AbstractValue:
|
|
207
229
|
if op.opcode not in ADDRESS_OPCODES:
|
pcode_graph/cli.py
CHANGED
|
@@ -21,6 +21,7 @@ Options:
|
|
|
21
21
|
-b, --base-address <int> Consider the given assembly starts at given address [Default: 0].
|
|
22
22
|
-D, --dataflow-only Only extract dataflow graph (and no control flow), this implies -F.
|
|
23
23
|
-F, --flat-cfg Disable basic block nodes in the graph.
|
|
24
|
+
-I, --include-data Translate the whole content of code sections, do not use ARM mapping symbols to exclude data/thumb.
|
|
24
25
|
-o, --output <path> Where to write the output.
|
|
25
26
|
-h, --help This help.
|
|
26
27
|
-d, --debug Debug mode: do no catch exceptions.
|
|
@@ -83,9 +84,11 @@ def main():
|
|
|
83
84
|
else:
|
|
84
85
|
output = sys.stdout
|
|
85
86
|
|
|
87
|
+
exclude_arm_data = not args["--include-data"]
|
|
88
|
+
|
|
86
89
|
if args["functions"]:
|
|
87
90
|
assert binary, "Command 'functions' requires a binary file"
|
|
88
|
-
for f in iter_functions(binary):
|
|
91
|
+
for f in iter_functions(binary, exclude_arm_data):
|
|
89
92
|
print(
|
|
90
93
|
f"{hex(f.address)}: {f.name}: {len(f.content)} bytes", file=output
|
|
91
94
|
)
|
|
@@ -101,9 +104,10 @@ def main():
|
|
|
101
104
|
if function_name or chunk_begin_end:
|
|
102
105
|
if function_name:
|
|
103
106
|
# Lift function
|
|
104
|
-
function = get_function(binary, function_name)
|
|
107
|
+
function = get_function(binary, function_name, exclude_arm_data)
|
|
105
108
|
start_address = function.address
|
|
106
109
|
code = function.content
|
|
110
|
+
excluded = function.excluded
|
|
107
111
|
else:
|
|
108
112
|
# Lift piece of code
|
|
109
113
|
if not re.search("[a-fA-FxX]", chunk_begin_end):
|
|
@@ -113,25 +117,37 @@ def main():
|
|
|
113
117
|
start_address, end_address = [
|
|
114
118
|
int(a, 16) for a in chunk_begin_end.split(":")
|
|
115
119
|
]
|
|
116
|
-
|
|
120
|
+
chunk = lookup_chunk(
|
|
121
|
+
binary, start_address, end_address, exclude_arm_data
|
|
122
|
+
)
|
|
123
|
+
code = chunk.content
|
|
124
|
+
excluded = chunk.excluded
|
|
117
125
|
if args["asm"]:
|
|
118
|
-
print(
|
|
126
|
+
print(
|
|
127
|
+
translator.dump_asm(
|
|
128
|
+
code, start_address, False, excluded=excluded
|
|
129
|
+
),
|
|
130
|
+
file=output,
|
|
131
|
+
)
|
|
119
132
|
sys.exit(0)
|
|
120
|
-
operations = translator.translate(code, start_address)
|
|
133
|
+
operations = translator.translate(code, start_address, excluded)
|
|
121
134
|
else:
|
|
122
135
|
# Lift everything
|
|
123
|
-
for section in iter_code_sections(binary):
|
|
136
|
+
for section in iter_code_sections(binary, exclude_arm_data):
|
|
124
137
|
if args["asm"]:
|
|
125
138
|
print(f"; Section at {hex(section.address)}", file=output)
|
|
126
139
|
print(
|
|
127
140
|
translator.dump_asm(
|
|
128
|
-
section.content,
|
|
141
|
+
section.content,
|
|
142
|
+
section.address,
|
|
143
|
+
False,
|
|
144
|
+
excluded=section.excluded,
|
|
129
145
|
),
|
|
130
146
|
file=output,
|
|
131
147
|
)
|
|
132
148
|
else:
|
|
133
149
|
operations += translator.translate(
|
|
134
|
-
section.content, section.address
|
|
150
|
+
section.content, section.address, section.excluded
|
|
135
151
|
)
|
|
136
152
|
if args["asm"]:
|
|
137
153
|
sys.exit(0)
|
pcode_graph/lief_importer.py
CHANGED
|
@@ -1,26 +1,45 @@
|
|
|
1
|
+
from bisect import bisect_right
|
|
2
|
+
from collections import defaultdict
|
|
3
|
+
from collections.abc import Iterator
|
|
1
4
|
from dataclasses import dataclass
|
|
2
5
|
from pathlib import Path
|
|
3
|
-
from
|
|
6
|
+
from operator import itemgetter
|
|
7
|
+
import re
|
|
4
8
|
from loguru import logger
|
|
5
9
|
from pypcode import OpCode
|
|
6
10
|
from pcode_graph.arch import Arch
|
|
7
11
|
import lief
|
|
8
|
-
from pcode_graph.translator import
|
|
12
|
+
from pcode_graph.translator import (
|
|
13
|
+
AddressRange,
|
|
14
|
+
ChunkOps,
|
|
15
|
+
ExcludedRanges,
|
|
16
|
+
Translator,
|
|
17
|
+
)
|
|
9
18
|
|
|
10
19
|
lief.disable_leak_warning()
|
|
11
20
|
|
|
12
21
|
|
|
22
|
+
#: ARM/AArch64 ELF mapping symbols: $a (A32 code), $x (A64 code), $t (Thumb
|
|
23
|
+
#: code) and $d (data), optionally suffixed by ".<anything>".
|
|
24
|
+
MAPPING_SYMBOL = re.compile(r"^\$([adtx])(\..*)?$")
|
|
25
|
+
#: Only A32 and A64 code is lifted, Thumb code is excluded like data.
|
|
26
|
+
LIFTED_MAPPING_KINDS = {"a", "x"}
|
|
27
|
+
#: ELF machines whose mapping symbols are read. RISC-V also uses ``$x`` and
|
|
28
|
+
#: ``$d`` mapping symbols, with other semantics.
|
|
29
|
+
MAPPING_SYMBOL_MACHINES = {lief.ELF.ARCH.ARM, lief.ELF.ARCH.AARCH64}
|
|
30
|
+
|
|
31
|
+
|
|
13
32
|
@dataclass
|
|
14
33
|
class ChunkCode:
|
|
15
34
|
address: int
|
|
16
35
|
content: bytes
|
|
36
|
+
#: Address ranges not to lift, see ``Translator.iter_operations``.
|
|
37
|
+
excluded: ExcludedRanges = ()
|
|
17
38
|
|
|
18
39
|
|
|
19
|
-
@dataclass
|
|
20
|
-
class FunctionCode:
|
|
40
|
+
@dataclass(kw_only=True)
|
|
41
|
+
class FunctionCode(ChunkCode):
|
|
21
42
|
name: str
|
|
22
|
-
address: int
|
|
23
|
-
content: bytes
|
|
24
43
|
|
|
25
44
|
|
|
26
45
|
@dataclass
|
|
@@ -121,7 +140,90 @@ def get_architecture(binary: Path | lief.Binary) -> Arch:
|
|
|
121
140
|
return arch
|
|
122
141
|
|
|
123
142
|
|
|
124
|
-
def
|
|
143
|
+
def _is_relocatable(binary: lief.Binary) -> bool:
|
|
144
|
+
return (
|
|
145
|
+
isinstance(binary, lief.ELF.Binary)
|
|
146
|
+
and binary.header.file_type == lief.ELF.Header.FILE_TYPE.REL
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _symbol_address(
|
|
151
|
+
symbol: lief.ELF.Symbol,
|
|
152
|
+
section: lief.ELF.Section,
|
|
153
|
+
relocatable: bool,
|
|
154
|
+
) -> int:
|
|
155
|
+
"""In relocatable objects, symbol values are offsets in their section,
|
|
156
|
+
whereas in executables and shared libraries they are virtual addresses."""
|
|
157
|
+
|
|
158
|
+
return section.virtual_address + symbol.value if relocatable else symbol.value
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def read_excluded_ranges(binary: lief.Binary) -> dict[int, list[AddressRange]]:
|
|
162
|
+
"""Reads ARM/AArch64 ELF mapping symbols and returns (by section
|
|
163
|
+
index) the sorted disjoint address ranges containing data or Thumb code
|
|
164
|
+
(which must not be lifted.)
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
if (
|
|
168
|
+
not isinstance(binary, lief.ELF.Binary)
|
|
169
|
+
or binary.header.machine_type not in MAPPING_SYMBOL_MACHINES
|
|
170
|
+
):
|
|
171
|
+
return {}
|
|
172
|
+
|
|
173
|
+
relocatable = _is_relocatable(binary)
|
|
174
|
+
sections = list(binary.sections)
|
|
175
|
+
markers: dict[int, list[tuple[int, bool]]] = defaultdict(list)
|
|
176
|
+
|
|
177
|
+
for symbol in binary.symtab_symbols:
|
|
178
|
+
match = MAPPING_SYMBOL.match(symbol.name)
|
|
179
|
+
if match is None or not 0 < symbol.shndx < len(sections):
|
|
180
|
+
continue
|
|
181
|
+
address = _symbol_address(symbol, sections[symbol.shndx], relocatable)
|
|
182
|
+
markers[symbol.shndx].append((address, match[1] in LIFTED_MAPPING_KINDS))
|
|
183
|
+
|
|
184
|
+
if not markers:
|
|
185
|
+
logger.warning("No mapping symbols found, inline data will be lifted")
|
|
186
|
+
|
|
187
|
+
excluded: dict[int, list[AddressRange]] = {}
|
|
188
|
+
for section_index, section_markers in markers.items():
|
|
189
|
+
section = sections[section_index]
|
|
190
|
+
ranges: list[AddressRange] = []
|
|
191
|
+
data_start: int | None = None
|
|
192
|
+
# The section end closes the last range
|
|
193
|
+
section_end = (section.virtual_address + section.size, True)
|
|
194
|
+
for address, is_code in sorted(section_markers) + [section_end]:
|
|
195
|
+
if is_code and data_start is not None:
|
|
196
|
+
if address > data_start:
|
|
197
|
+
ranges.append((data_start, address))
|
|
198
|
+
data_start = None
|
|
199
|
+
elif not is_code and data_start is None:
|
|
200
|
+
data_start = address
|
|
201
|
+
excluded[section_index] = ranges
|
|
202
|
+
|
|
203
|
+
return excluded
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def iter_valid_ranges(
|
|
207
|
+
ranges: ExcludedRanges,
|
|
208
|
+
start_address: int,
|
|
209
|
+
end_address: int,
|
|
210
|
+
) -> list[AddressRange]:
|
|
211
|
+
|
|
212
|
+
clipped: list[AddressRange] = []
|
|
213
|
+
# First range ending after start_address
|
|
214
|
+
index = bisect_right(ranges, start_address, key=itemgetter(1))
|
|
215
|
+
while index < len(ranges) and ranges[index][0] < end_address:
|
|
216
|
+
start, end = ranges[index]
|
|
217
|
+
clipped.append((max(start, start_address), min(end, end_address)))
|
|
218
|
+
index += 1
|
|
219
|
+
return clipped
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def iter_code_sections(
|
|
223
|
+
binary: Path | lief.Binary, exclude_arm_data: bool
|
|
224
|
+
) -> Iterator[ChunkCode]:
|
|
225
|
+
"""Yields executable sections. With ``exclude_arm_data``, data and Thumb
|
|
226
|
+
code ranges given by ARM mapping symbols are excluded from lifting."""
|
|
125
227
|
|
|
126
228
|
if isinstance(binary, Path):
|
|
127
229
|
binary = parse_binary(binary)
|
|
@@ -145,84 +247,116 @@ def iter_code_sections(binary: Path | lief.Binary) -> Iterator[ChunkCode]:
|
|
|
145
247
|
yield ChunkCode(section.virtual_address, section.content.tobytes())
|
|
146
248
|
|
|
147
249
|
elif binary.format == lief.Binary.FORMATS.ELF:
|
|
148
|
-
|
|
250
|
+
excluded = read_excluded_ranges(binary) if exclude_arm_data else {}
|
|
251
|
+
for index, section in enumerate(binary.sections):
|
|
149
252
|
if section.has(lief.ELF.Section.FLAGS.EXECINSTR): # type: ignore
|
|
150
|
-
yield ChunkCode(
|
|
253
|
+
yield ChunkCode(
|
|
254
|
+
section.virtual_address,
|
|
255
|
+
section.content.tobytes(),
|
|
256
|
+
excluded.get(index, ()),
|
|
257
|
+
)
|
|
151
258
|
|
|
152
259
|
|
|
153
|
-
def get_function(
|
|
260
|
+
def get_function(
|
|
261
|
+
binary: Path | lief.Binary, name: str, exclude_arm_data: bool
|
|
262
|
+
) -> FunctionCode:
|
|
154
263
|
|
|
155
264
|
if isinstance(binary, Path):
|
|
156
265
|
binary = parse_binary(binary)
|
|
157
266
|
|
|
158
|
-
for f in iter_functions(binary):
|
|
267
|
+
for f in iter_functions(binary, exclude_arm_data):
|
|
159
268
|
if f.name == name:
|
|
160
269
|
return f
|
|
161
270
|
|
|
162
271
|
raise LookupError(f"Function {name} not found in {binary}")
|
|
163
272
|
|
|
164
273
|
|
|
165
|
-
def iter_functions(
|
|
274
|
+
def iter_functions(
|
|
275
|
+
binary: Path | lief.Binary, exclude_arm_data: bool
|
|
276
|
+
) -> Iterator[FunctionCode]:
|
|
277
|
+
"""Yields functions from the ELF symbol table. With ``exclude_arm_data``,
|
|
278
|
+
data and Thumb code ranges given by ARM mapping symbols are excluded from
|
|
279
|
+
lifting. ARM Thumb functions are always skipped."""
|
|
166
280
|
|
|
167
281
|
if isinstance(binary, Path):
|
|
168
282
|
binary = parse_binary(binary)
|
|
169
283
|
|
|
170
|
-
cache: dict[
|
|
284
|
+
cache: dict[int, tuple[bytes, int]] = {}
|
|
171
285
|
sym: lief.ELF.Symbol
|
|
172
286
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
287
|
+
relocatable = _is_relocatable(binary)
|
|
288
|
+
excluded = read_excluded_ranges(binary) if exclude_arm_data else {}
|
|
289
|
+
is_arm32 = binary.header.machine_type == lief.ELF.ARCH.ARM # type: ignore
|
|
290
|
+
sections = list(binary.sections)
|
|
291
|
+
thumb_functions: list[str] = []
|
|
176
292
|
|
|
177
293
|
for sym in binary.symtab_symbols: # type: ignore
|
|
178
294
|
if sym.type != lief.ELF.Symbol.TYPE.FUNC or sym.size == 0:
|
|
179
295
|
continue
|
|
180
|
-
|
|
181
|
-
|
|
296
|
+
# Sections are identified by index, as names may be duplicated
|
|
297
|
+
section_index = sym.shndx
|
|
298
|
+
if not 0 < section_index < len(sections):
|
|
299
|
+
continue
|
|
300
|
+
if is_arm32 and sym.value & 1:
|
|
301
|
+
thumb_functions.append(sym.name)
|
|
182
302
|
continue
|
|
183
303
|
|
|
184
|
-
|
|
185
|
-
if
|
|
186
|
-
cache[
|
|
304
|
+
section = sections[section_index]
|
|
305
|
+
if section_index not in cache:
|
|
306
|
+
cache[section_index] = (bytes(section.content), section.virtual_address)
|
|
187
307
|
|
|
188
|
-
section_content, section_address = cache[
|
|
189
|
-
|
|
308
|
+
section_content, section_address = cache[section_index]
|
|
309
|
+
address = _symbol_address(sym, section, relocatable)
|
|
310
|
+
offset = address - section_address
|
|
190
311
|
if offset < 0 or offset + sym.size > len(section_content):
|
|
191
|
-
logger.warning(f"Skip function {sym.name}: out of section {
|
|
312
|
+
logger.warning(f"Skip function {sym.name}: out of section {section.name}")
|
|
192
313
|
continue
|
|
193
314
|
|
|
194
315
|
assert isinstance(sym.name, str)
|
|
195
316
|
yield FunctionCode(
|
|
196
|
-
|
|
197
|
-
section_address + offset,
|
|
317
|
+
address,
|
|
198
318
|
section_content[offset : offset + sym.size],
|
|
319
|
+
iter_valid_ranges(excluded.get(section_index, ()), address, address + sym.size),
|
|
320
|
+
name=sym.name,
|
|
199
321
|
)
|
|
200
322
|
|
|
323
|
+
if thumb_functions:
|
|
324
|
+
logger.warning(
|
|
325
|
+
f"Skip {len(thumb_functions)} Thumb functions, Thumb code is not supported"
|
|
326
|
+
)
|
|
327
|
+
logger.debug(f"Skipped Thumb functions: {', '.join(thumb_functions)}")
|
|
328
|
+
|
|
201
329
|
|
|
202
330
|
def lookup_chunk(
|
|
203
331
|
binary: Path | lief.Binary,
|
|
204
332
|
start_address: int,
|
|
205
333
|
end_address: int,
|
|
206
|
-
|
|
334
|
+
exclude_arm_data: bool,
|
|
335
|
+
) -> ChunkCode:
|
|
207
336
|
"""Returns the code at given address from the given binary.
|
|
208
337
|
|
|
209
338
|
Args:
|
|
210
339
|
binary (Path | lief.Binary): Binary to read.
|
|
211
340
|
start_address (int): Address of the first instruction to return.
|
|
212
341
|
end_address (int): Address of the first instruction after the returned chunk.
|
|
342
|
+
exclude_arm_data (bool): Exclude ranges given by ARM mapping symbols.
|
|
213
343
|
|
|
214
344
|
Returns:
|
|
215
|
-
ChunkCode: A piece of binary code.
|
|
345
|
+
ChunkCode: A piece of binary code, with the ranges not to lift.
|
|
216
346
|
"""
|
|
217
347
|
|
|
218
|
-
for section in iter_code_sections(binary):
|
|
348
|
+
for section in iter_code_sections(binary, exclude_arm_data):
|
|
219
349
|
if (
|
|
220
350
|
section.address <= start_address
|
|
221
351
|
and section.address + len(section.content) >= end_address
|
|
222
352
|
):
|
|
223
353
|
offset = start_address - section.address
|
|
224
354
|
size = end_address - start_address
|
|
225
|
-
return
|
|
355
|
+
return ChunkCode(
|
|
356
|
+
start_address,
|
|
357
|
+
section.content[offset : offset + size],
|
|
358
|
+
iter_valid_ranges(section.excluded, start_address, end_address),
|
|
359
|
+
)
|
|
226
360
|
|
|
227
361
|
raise LookupError("Cannot find a section containing given range")
|
|
228
362
|
|
|
@@ -230,14 +364,21 @@ def lookup_chunk(
|
|
|
230
364
|
def collect_functions(
|
|
231
365
|
binary: Path | lief.Binary,
|
|
232
366
|
translator: Translator,
|
|
367
|
+
exclude_arm_data: bool,
|
|
233
368
|
) -> Iterator[FunctionOps]:
|
|
234
369
|
|
|
235
370
|
logger.debug(f"Extract functions")
|
|
236
371
|
|
|
237
|
-
for function in iter_functions(binary):
|
|
372
|
+
for function in iter_functions(binary, exclude_arm_data):
|
|
238
373
|
|
|
239
|
-
instructions = list(
|
|
240
|
-
|
|
374
|
+
instructions = list(
|
|
375
|
+
translator.disassemble(
|
|
376
|
+
function.content, function.address, function.excluded
|
|
377
|
+
)
|
|
378
|
+
)
|
|
379
|
+
operations = translator.translate(
|
|
380
|
+
function.content, function.address, function.excluded
|
|
381
|
+
)
|
|
241
382
|
yield FunctionOps(
|
|
242
383
|
len(instructions),
|
|
243
384
|
function.address,
|
|
@@ -251,26 +392,36 @@ def collect_basic_blocks(
|
|
|
251
392
|
translator: Translator,
|
|
252
393
|
min_instructions: int,
|
|
253
394
|
max_instructions: int,
|
|
395
|
+
exclude_arm_data: bool,
|
|
254
396
|
) -> Iterator[ChunkOps]:
|
|
255
397
|
"""Extracts the P-Code operations of basic blocks found in a binary, using LIEF library."""
|
|
256
398
|
|
|
257
399
|
logger.debug(f"Extract basic blocks")
|
|
258
400
|
|
|
259
401
|
# Extract P-Code operations of executable sections
|
|
260
|
-
for section in iter_code_sections(binary):
|
|
402
|
+
for section in iter_code_sections(binary, exclude_arm_data):
|
|
261
403
|
|
|
262
404
|
# Slice into basic blocks
|
|
263
405
|
num_instructions = 0
|
|
264
406
|
operations = []
|
|
265
|
-
|
|
407
|
+
bb_start_address = next_address = section.address # Set on first instruction
|
|
266
408
|
|
|
267
409
|
# First disassemble to translate into P-Code one instruction at a time,
|
|
268
410
|
# in order to avoid consuming too much RAM.
|
|
269
|
-
for instr in translator.disassemble(
|
|
411
|
+
for instr in translator.disassemble(
|
|
412
|
+
section.content, section.address, section.excluded
|
|
413
|
+
):
|
|
414
|
+
|
|
415
|
+
if num_instructions == 0 or instr.address != next_address:
|
|
416
|
+
# New basic block, or gap (excluded range or undecodable
|
|
417
|
+
# bytes) dropping the unterminated one
|
|
418
|
+
bb_start_address = instr.address
|
|
419
|
+
num_instructions = 0
|
|
420
|
+
operations = []
|
|
421
|
+
next_address = instr.address + instr.length
|
|
270
422
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
instr_code = section.content[instr_start_offset:instr_end_offset]
|
|
423
|
+
instr_offset = instr.address - section.address
|
|
424
|
+
instr_code = section.content[instr_offset : instr_offset + instr.length]
|
|
274
425
|
|
|
275
426
|
instr_ops = translator.translate(instr_code, instr.address)
|
|
276
427
|
|
|
@@ -290,23 +441,19 @@ def collect_basic_blocks(
|
|
|
290
441
|
continue
|
|
291
442
|
|
|
292
443
|
if min_instructions <= num_instructions <= max_instructions:
|
|
293
|
-
yield ChunkOps(
|
|
294
|
-
num_instructions,
|
|
295
|
-
section.address + bb_start_offset,
|
|
296
|
-
# section.content[bb_start_offset:instr_end_offset],
|
|
297
|
-
operations,
|
|
298
|
-
)
|
|
444
|
+
yield ChunkOps(num_instructions, bb_start_address, operations)
|
|
299
445
|
|
|
300
|
-
bb_start_offset = instr_end_offset
|
|
301
446
|
num_instructions = 0
|
|
302
|
-
operations = []
|
|
303
447
|
|
|
304
448
|
|
|
305
449
|
def collect_chunks(
|
|
306
450
|
binary: Path | lief.Binary,
|
|
307
451
|
translator: Translator,
|
|
452
|
+
exclude_arm_data: bool,
|
|
308
453
|
) -> Iterator[ChunkOps]:
|
|
309
454
|
"""Extracts the P-Code operations of the sections found in a binary, using LIEF library."""
|
|
310
455
|
|
|
311
|
-
for section in iter_code_sections(binary):
|
|
312
|
-
yield from translator.iter_operations(
|
|
456
|
+
for section in iter_code_sections(binary, exclude_arm_data):
|
|
457
|
+
yield from translator.iter_operations(
|
|
458
|
+
section.content, section.address, excluded=section.excluded
|
|
459
|
+
)
|
pcode_graph/maker.py
CHANGED
|
@@ -18,7 +18,7 @@ from pcode_graph.graph import CDG, Edge, EdgeKinds, NodeIndex, NodeKinds, Node
|
|
|
18
18
|
from pcode_graph.pcode import from_native_opcode
|
|
19
19
|
from pcode_graph.registers import SPECIAL_REGISTERS
|
|
20
20
|
from pcode_graph.simplifier import GraphSimplifier
|
|
21
|
-
from pcode_graph.translator import Translator
|
|
21
|
+
from pcode_graph.translator import ExcludedRanges, Translator
|
|
22
22
|
|
|
23
23
|
from pypcode import OpCode
|
|
24
24
|
from loguru import logger
|
|
@@ -389,6 +389,7 @@ def make_graph_from_binary(
|
|
|
389
389
|
code: bytes,
|
|
390
390
|
base_address: int,
|
|
391
391
|
flags: MakerFlags | None = None,
|
|
392
|
+
excluded: ExcludedRanges = (),
|
|
392
393
|
) -> CDG:
|
|
393
394
|
"""Makes a CDG graph from a piece of binary code.
|
|
394
395
|
|
|
@@ -397,12 +398,13 @@ def make_graph_from_binary(
|
|
|
397
398
|
code (bytes): The binary code to translate.
|
|
398
399
|
base_address (int): The address of the first instruction of the given code.
|
|
399
400
|
flags (MakerFlags): determines what to put in the graph.
|
|
401
|
+
excluded (ExcludedRanges): address ranges not to lift, such as inline data.
|
|
400
402
|
|
|
401
403
|
Returns:
|
|
402
404
|
CDG: the graph built.
|
|
403
405
|
"""
|
|
404
406
|
|
|
405
|
-
operations = translator.translate(code, base_address)
|
|
407
|
+
operations = translator.translate(code, base_address, excluded)
|
|
406
408
|
prg = Program(arch=translator.arch, operations=operations)
|
|
407
409
|
run_analyses(prg)
|
|
408
410
|
return make_graph(prg, flags)
|
pcode_graph/translator.py
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
|
+
from collections.abc import Iterator, Sequence
|
|
1
2
|
from dataclasses import dataclass
|
|
2
|
-
from typing import
|
|
3
|
+
from typing import NamedTuple
|
|
3
4
|
from loguru import logger
|
|
4
5
|
import pypcode
|
|
5
6
|
from pcode_graph.arch import Arch
|
|
6
7
|
|
|
8
|
+
#: ``[start, end)`` address range.
|
|
9
|
+
type AddressRange = tuple[int, int]
|
|
10
|
+
#: Sorted, disjoint address ranges that must not be lifted, such as inline data
|
|
11
|
+
#: in code sections.
|
|
12
|
+
type ExcludedRanges = Sequence[AddressRange]
|
|
13
|
+
|
|
7
14
|
|
|
8
15
|
@dataclass(slots=True)
|
|
9
16
|
class ChunkOps:
|
|
@@ -40,6 +47,8 @@ class Instruction:
|
|
|
40
47
|
class LiftStats:
|
|
41
48
|
total_bytes: int = 0
|
|
42
49
|
lifted_bytes: int = 0
|
|
50
|
+
#: Bytes ignored because they lie in excluded ranges.
|
|
51
|
+
excluded_bytes: int = 0
|
|
43
52
|
skipped_bytes: int = 0
|
|
44
53
|
truncated_bytes: int = 0
|
|
45
54
|
num_instructions: int = 0
|
|
@@ -48,7 +57,8 @@ class LiftStats:
|
|
|
48
57
|
|
|
49
58
|
@property
|
|
50
59
|
def coverage(self) -> float:
|
|
51
|
-
|
|
60
|
+
code_bytes = self.total_bytes - self.excluded_bytes
|
|
61
|
+
return self.lifted_bytes / code_bytes if code_bytes else 1.0
|
|
52
62
|
|
|
53
63
|
|
|
54
64
|
class ArchParams(NamedTuple):
|
|
@@ -115,6 +125,26 @@ def get_pcode_context_arch(context: pypcode.Context) -> Arch:
|
|
|
115
125
|
raise ValueError(f"Unsupported context with {processor=} and {size=}")
|
|
116
126
|
|
|
117
127
|
|
|
128
|
+
def iter_code_ranges(
|
|
129
|
+
size: int, base_address: int, excluded: ExcludedRanges
|
|
130
|
+
) -> Iterator[AddressRange]:
|
|
131
|
+
"""Yields the ``[start, end)`` offsets of ``[0, size)`` outside excluded ranges."""
|
|
132
|
+
|
|
133
|
+
cursor = 0
|
|
134
|
+
for start_address, end_address in excluded:
|
|
135
|
+
if start_address - base_address >= size:
|
|
136
|
+
break
|
|
137
|
+
start = max(start_address - base_address, cursor)
|
|
138
|
+
end = min(end_address - base_address, size)
|
|
139
|
+
if end <= start:
|
|
140
|
+
continue
|
|
141
|
+
if start > cursor:
|
|
142
|
+
yield cursor, start
|
|
143
|
+
cursor = end
|
|
144
|
+
if cursor < size:
|
|
145
|
+
yield cursor, size
|
|
146
|
+
|
|
147
|
+
|
|
118
148
|
class Translator:
|
|
119
149
|
|
|
120
150
|
def __init__(self, arch_context: pypcode.Context | Arch):
|
|
@@ -127,11 +157,16 @@ class Translator:
|
|
|
127
157
|
|
|
128
158
|
self.alignment, self.max_instr_size = ARCH_PARAMETERS[self.arch]
|
|
129
159
|
|
|
130
|
-
def translate(
|
|
160
|
+
def translate(
|
|
161
|
+
self,
|
|
162
|
+
data: bytes,
|
|
163
|
+
base_address: int,
|
|
164
|
+
excluded: ExcludedRanges = (),
|
|
165
|
+
) -> list[pypcode.PcodeOp]:
|
|
131
166
|
"""Translates a piece of code into P-Code operations."""
|
|
132
167
|
|
|
133
168
|
ops = []
|
|
134
|
-
for chunk in self.iter_operations(data, base_address):
|
|
169
|
+
for chunk in self.iter_operations(data, base_address, excluded=excluded):
|
|
135
170
|
ops += chunk.operations
|
|
136
171
|
return ops
|
|
137
172
|
|
|
@@ -142,13 +177,15 @@ class Translator:
|
|
|
142
177
|
window: int = 4096,
|
|
143
178
|
max_instructions: int = 1024,
|
|
144
179
|
stats: LiftStats | None = None,
|
|
180
|
+
excluded: ExcludedRanges = (),
|
|
145
181
|
) -> Iterator[ChunkOps]:
|
|
146
182
|
"""Translates a piece of code into P-Code, handling errors and avoiding
|
|
147
183
|
out-of-memory for big sections.
|
|
148
184
|
|
|
149
185
|
Each ChunkOps covers a contiguous range: undecodable bytes are skipped,
|
|
150
186
|
``instruction_alignment`` at a time. ``window`` and ``max_instructions``
|
|
151
|
-
both bound the memory of a single call.
|
|
187
|
+
both bound the memory of a single call. Bytes in ``excluded`` address
|
|
188
|
+
ranges are not lifted.
|
|
152
189
|
"""
|
|
153
190
|
|
|
154
191
|
assert window > 1 and max_instructions > 1
|
|
@@ -156,6 +193,22 @@ class Translator:
|
|
|
156
193
|
stats = LiftStats()
|
|
157
194
|
stats.total_bytes += len(data)
|
|
158
195
|
|
|
196
|
+
code_bytes = 0
|
|
197
|
+
for start, end in iter_code_ranges(len(data), base_address, excluded):
|
|
198
|
+
code_bytes += end - start
|
|
199
|
+
yield from self._iter_code_operations(
|
|
200
|
+
data[start:end], base_address + start, window, max_instructions, stats
|
|
201
|
+
)
|
|
202
|
+
stats.excluded_bytes += len(data) - code_bytes
|
|
203
|
+
|
|
204
|
+
def _iter_code_operations(
|
|
205
|
+
self,
|
|
206
|
+
data: bytes,
|
|
207
|
+
base_address: int,
|
|
208
|
+
window: int,
|
|
209
|
+
max_instructions: int,
|
|
210
|
+
stats: LiftStats,
|
|
211
|
+
) -> Iterator[ChunkOps]:
|
|
159
212
|
offset = 0
|
|
160
213
|
padded_data = data
|
|
161
214
|
if self.arch in {Arch.mips_32, Arch.mips_64}:
|
|
@@ -224,17 +277,30 @@ class Translator:
|
|
|
224
277
|
stats.resyncs += 1
|
|
225
278
|
offset += self.alignment
|
|
226
279
|
|
|
227
|
-
def disassemble(
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
280
|
+
def disassemble(
|
|
281
|
+
self,
|
|
282
|
+
code: bytes,
|
|
283
|
+
base_address: int,
|
|
284
|
+
excluded: ExcludedRanges = (),
|
|
285
|
+
) -> Iterator[Instruction]:
|
|
286
|
+
"""Disassembles code, stopping at the first undecodable instruction of
|
|
287
|
+
each range outside ``excluded``."""
|
|
288
|
+
|
|
289
|
+
for start, end in iter_code_ranges(len(code), base_address, excluded):
|
|
290
|
+
data = self.context.disassemble(
|
|
291
|
+
code[start:end], base_address=base_address + start
|
|
292
|
+
)
|
|
293
|
+
for i in data.instructions:
|
|
294
|
+
yield Instruction(i.addr.offset, i.length, i.mnem, i.body)
|
|
231
295
|
|
|
232
296
|
def dump_asm(
|
|
233
297
|
self,
|
|
234
298
|
code: bytes,
|
|
235
299
|
base_address: int,
|
|
236
300
|
print_address: bool = True,
|
|
301
|
+
excluded: ExcludedRanges = (),
|
|
237
302
|
) -> str:
|
|
238
303
|
return "\n".join(
|
|
239
|
-
i.dump(print_address)
|
|
304
|
+
i.dump(print_address)
|
|
305
|
+
for i in self.disassemble(code, base_address, excluded)
|
|
240
306
|
)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: pcode_graph
|
|
3
|
-
Version: 4.
|
|
3
|
+
Version: 4.3.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
|
|
@@ -6,22 +6,22 @@ pcode_graph/basic_blocks.py,sha256=bgVkXS2lNWsCxsVM8L7vQQdgZuhW_s61XBQ0iliknXQ,7
|
|
|
6
6
|
pcode_graph/bit_utils.py,sha256=rEEfiJevPc-QMYVryZVwWPBOufC3MyA3bZZ8y9Q4aLU,405
|
|
7
7
|
pcode_graph/characterization.py,sha256=2JcM6wxCABaItCxKUnXDkGQj1SLgTvmtxLfnGqFPUg8,3183
|
|
8
8
|
pcode_graph/checker.py,sha256=OieaYXDnk0QHhYVO12ckzCNPH16DQ3vb0Q9pOO7TR-0,9293
|
|
9
|
-
pcode_graph/cli.py,sha256=
|
|
9
|
+
pcode_graph/cli.py,sha256=kHH7VdIRvE3uzhB-_kcRN7TBKvAYMWTynpmjm85YZm0,7881
|
|
10
10
|
pcode_graph/emulator.py,sha256=7r1aMoTKDc6j_cT8V2vCcts4Mg2FMmvdoP8Y3H12RDY,13366
|
|
11
11
|
pcode_graph/gnn_exporter.py,sha256=fd0Mz_2NJaQhYQ196nE7CEM0U1cG_9pjCA4yPrJnJHk,7356
|
|
12
12
|
pcode_graph/graph.py,sha256=grGdl7zW4lwp9Mt2bXjZASC9jAHUvnXIEHrt5m805SI,7474
|
|
13
|
-
pcode_graph/lief_importer.py,sha256=
|
|
13
|
+
pcode_graph/lief_importer.py,sha256=RvWUBUNgJu8k0el6rMgUFTkysfBpTh-93xsgq72dmmk,15927
|
|
14
14
|
pcode_graph/log.py,sha256=qo6gh8bHsl-4-dnzsbHsB5rGism-MtjLJmQ-uBQwOIk,1035
|
|
15
|
-
pcode_graph/maker.py,sha256=
|
|
15
|
+
pcode_graph/maker.py,sha256=L-MnIeTVTGkJLirfVC8E-sAdhXJeeTdfDujc7rZRPuA,16264
|
|
16
16
|
pcode_graph/nx_exporter.py,sha256=lSczsuuyD9XNE_8PgqCEvPdbMMXSdKLLt6YNPsGF-Zk,629
|
|
17
17
|
pcode_graph/pcode.py,sha256=vjqS4MBOiRJ7g4REXCRVgpS2Cp9uJcV_ACmgK8qOUS8,4599
|
|
18
18
|
pcode_graph/registers.py,sha256=Grw4Ypr8GldG5nR1YeDG4rMf13gvzugSngvq2y51xjk,58328
|
|
19
19
|
pcode_graph/simplifier.py,sha256=4aD6RJ5hhSqV8mI3ACjDWAzmUXRVO83UytZ9L-sINys,6761
|
|
20
20
|
pcode_graph/torch_utils.py,sha256=GwVjWKL5Lqhm94b69o-rCilzNRu237gyJo6T6xWQHQc,966
|
|
21
|
-
pcode_graph/translator.py,sha256=
|
|
21
|
+
pcode_graph/translator.py,sha256=AaEaaeSIKq5M4Hx1r3ij-1Wh6eZsu3a2nBn2Uj6nxoQ,9756
|
|
22
22
|
pcode_graph/view.py,sha256=Qj935NNo7n0-ecGMusEy_QLb6yx3pckLAbztji9Po2U,2452
|
|
23
23
|
pcode_graph/visitor.py,sha256=bxaQ9q0lTw8ysPOrta5G7LeHZYnq3IBxMafM_-8FruM,6990
|
|
24
|
-
pcode_graph/analysis/alias_analysis.py,sha256=
|
|
24
|
+
pcode_graph/analysis/alias_analysis.py,sha256=7GcN62AYvRN2nI1iUBoUeGQExSWPNnHEw4Kqhx0dVM4,12429
|
|
25
25
|
pcode_graph/analysis/cfg.py,sha256=PhMLzMcNhvNTNjO7MvhffKFUWzG_UFf8tO7r5hlQ_Zc,4484
|
|
26
26
|
pcode_graph/analysis/def_use.py,sha256=XkBZpb4aaO1gJMdQDbd-kjsR-MbcPUnYKChzbAX_YX4,4300
|
|
27
27
|
pcode_graph/analysis/interning.py,sha256=a6RcoeYH6JeoX-bAsebAjnFDzx8N5kTJPXsq8QLygAc,322
|
|
@@ -31,8 +31,8 @@ pcode_graph/analysis/pass_base.py,sha256=IeG5NiEz_Mez-ftjPA2GmC_oT7j7gPAQ6fRClGh
|
|
|
31
31
|
pcode_graph/analysis/passes.py,sha256=aRzbEqP5uoXZxPcwQppMOZQencOhI8A6xUbyEQoeEKQ,429
|
|
32
32
|
pcode_graph/analysis/program.py,sha256=VjSSgoASXma7Oj0nSXRGJdpnDmPmHKzMatBZC5HRD_M,10097
|
|
33
33
|
pcode_graph/analysis/unreachable.py,sha256=Poza5XjP5Nf9fAR_5srGLU2E0Jsl7pmk3m3QEYBgDgo,505
|
|
34
|
-
pcode_graph-4.
|
|
35
|
-
pcode_graph-4.
|
|
36
|
-
pcode_graph-4.
|
|
37
|
-
pcode_graph-4.
|
|
38
|
-
pcode_graph-4.
|
|
34
|
+
pcode_graph-4.3.0.dist-info/METADATA,sha256=X02GZSzOMY1Iz7p2VIhNRf91zfQlPjyKjj5dGsWM2HY,6675
|
|
35
|
+
pcode_graph-4.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
36
|
+
pcode_graph-4.3.0.dist-info/entry_points.txt,sha256=7pTTgqjYSRYwmBdA0GwJYXPfOmdk8I_mGsJOHHx-PXQ,45
|
|
37
|
+
pcode_graph-4.3.0.dist-info/licenses/LICENSE,sha256=iVkUrjpGBX_59jOK6a7mKkvjHUCGfiCFQRgrziEh-nY,1066
|
|
38
|
+
pcode_graph-4.3.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|