pcode-graph 4.2.1__tar.gz → 4.3.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.
Files changed (64) hide show
  1. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/PKG-INFO +1 -1
  2. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/cli.py +24 -8
  3. pcode_graph-4.3.0/pcode_graph/lief_importer.py +459 -0
  4. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/maker.py +4 -2
  5. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/translator.py +76 -10
  6. pcode_graph-4.3.0/tests/lief_importer_test.py +193 -0
  7. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/translator_test.py +65 -1
  8. pcode_graph-4.2.1/pcode_graph/lief_importer.py +0 -312
  9. pcode_graph-4.2.1/tests/lief_importer_test.py +0 -40
  10. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/.github/workflows/release.yml +0 -0
  11. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/.github/workflows/test.yml +0 -0
  12. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/.gitignore +0 -0
  13. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/CHANGELOG +0 -0
  14. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/LICENSE +0 -0
  15. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/README.md +0 -0
  16. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/__init__.py +0 -0
  17. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/__main__.py +0 -0
  18. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/alias_analysis.py +0 -0
  19. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/cfg.py +0 -0
  20. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/def_use.py +0 -0
  21. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/interning.py +0 -0
  22. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/load_store.py +0 -0
  23. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/native_pcode.py +0 -0
  24. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/pass_base.py +0 -0
  25. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/passes.py +0 -0
  26. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/program.py +0 -0
  27. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/analysis/unreachable.py +0 -0
  28. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/arch.py +0 -0
  29. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/asm.py +0 -0
  30. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/basic_blocks.py +0 -0
  31. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/bit_utils.py +0 -0
  32. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/characterization.py +0 -0
  33. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/checker.py +0 -0
  34. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/emulator.py +0 -0
  35. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/gnn_exporter.py +0 -0
  36. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/graph.py +0 -0
  37. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/log.py +0 -0
  38. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/nx_exporter.py +0 -0
  39. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/pcode.py +0 -0
  40. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/registers.py +0 -0
  41. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/simplifier.py +0 -0
  42. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/torch_utils.py +0 -0
  43. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/view.py +0 -0
  44. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pcode_graph/visitor.py +0 -0
  45. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/pyproject.toml +0 -0
  46. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/requirements.txt +0 -0
  47. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/__init__.py +0 -0
  48. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/analysis_test.py +0 -0
  49. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/basic_block_test.py +0 -0
  50. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/callother_test.py +0 -0
  51. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/charac_test.py +0 -0
  52. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/cli_test.py +0 -0
  53. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/conftest.py +0 -0
  54. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/def_use_test.py +0 -0
  55. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/emulator_test.py +0 -0
  56. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/exporter_test.py +0 -0
  57. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/fixtures.py +0 -0
  58. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/helpers.py +0 -0
  59. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/load_store_test.py +0 -0
  60. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/maker_test.py +0 -0
  61. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/memory_state_test.py +0 -0
  62. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/memory_test.py +0 -0
  63. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/tests/utils_test.py +0 -0
  64. {pcode_graph-4.2.1 → pcode_graph-4.3.0}/todo.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pcode_graph
3
- Version: 4.2.1
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
@@ -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
- code = lookup_chunk(binary, start_address, end_address)
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(translator.dump_asm(code, start_address, False), file=output)
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, section.address, False
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)
@@ -0,0 +1,459 @@
1
+ from bisect import bisect_right
2
+ from collections import defaultdict
3
+ from collections.abc import Iterator
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from operator import itemgetter
7
+ import re
8
+ from loguru import logger
9
+ from pypcode import OpCode
10
+ from pcode_graph.arch import Arch
11
+ import lief
12
+ from pcode_graph.translator import (
13
+ AddressRange,
14
+ ChunkOps,
15
+ ExcludedRanges,
16
+ Translator,
17
+ )
18
+
19
+ lief.disable_leak_warning()
20
+
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
+
32
+ @dataclass
33
+ class ChunkCode:
34
+ address: int
35
+ content: bytes
36
+ #: Address ranges not to lift, see ``Translator.iter_operations``.
37
+ excluded: ExcludedRanges = ()
38
+
39
+
40
+ @dataclass(kw_only=True)
41
+ class FunctionCode(ChunkCode):
42
+ name: str
43
+
44
+
45
+ @dataclass
46
+ class FunctionOps(ChunkOps):
47
+ function_name: str
48
+
49
+
50
+ def try_parse_binary(binary_path: Path) -> lief.Binary | None:
51
+ """Parses the given file, or returns None if LIEF does not recognize its format."""
52
+
53
+ assert binary_path.is_file(), f"{binary_path} is not a file"
54
+ logger.debug(f"Parse {binary_path}")
55
+ binary = lief.parse(binary_path.as_posix())
56
+ return binary if isinstance(binary, lief.Binary) else None
57
+
58
+
59
+ def parse_binary(binary_path: Path) -> lief.Binary:
60
+ binary = try_parse_binary(binary_path)
61
+ assert binary is not None, f"{binary_path} is not a supported binary"
62
+ return binary
63
+
64
+
65
+ def get_architecture(binary: Path | lief.Binary) -> Arch:
66
+ """Guesses the architecture of given binary."""
67
+
68
+ if isinstance(binary, Path):
69
+ binary = parse_binary(binary)
70
+
71
+ # ELF
72
+ if isinstance(binary, lief.ELF.Binary):
73
+
74
+ match binary.header.machine_type:
75
+ case lief.ELF.ARCH.ARM:
76
+ arch = Arch.arm_32
77
+ case lief.ELF.ARCH.AARCH64:
78
+ arch = Arch.arm_64
79
+ case lief.ELF.ARCH.X86_64:
80
+ arch = Arch.x86_64
81
+ case lief.ELF.ARCH.I386:
82
+ arch = Arch.x86_32
83
+ case lief.ELF.ARCH.MIPS:
84
+ if binary.header.identity_data != lief.ELF.Header.ELF_DATA.MSB:
85
+ raise ValueError("Unsupported edianness")
86
+ if binary.header.identity_class == lief.ELF.Header.CLASS.ELF64:
87
+ arch = Arch.mips_64
88
+ else:
89
+ flags = set(binary.header.flags_list)
90
+ _P = lief.ELF.PROCESSOR_FLAGS
91
+ if _P.MIPS_ABI2 in flags or bool(
92
+ flags
93
+ & {
94
+ _P.MIPS_ARCH_3, _P.MIPS_ARCH_4, _P.MIPS_ARCH_5, _P.MIPS_ARCH_64, _P.MIPS_ARCH_64R2, _P.MIPS_ARCH_64R6, # type: ignore # fmt: skip
95
+ }
96
+ ):
97
+ arch = Arch.mips_64
98
+ else:
99
+ arch = Arch.mips_32
100
+ case _ as v:
101
+ raise ValueError(f"Unsupported CPU type {v}")
102
+
103
+ # Mach-O
104
+ elif isinstance(binary, lief.MachO.FatBinary):
105
+ arch = None
106
+ for sub_binary in binary:
107
+ match sub_binary.header.cpu_type:
108
+ case lief.MachO.Header.CPU_TYPE.ARM64:
109
+ arch = Arch.arm_64
110
+ case lief.MachO.Header.CPU_TYPE.X86_64:
111
+ arch = Arch.x86_64
112
+ case _:
113
+ continue
114
+ break
115
+ else:
116
+ raise ValueError(f"No sub binary found with supported architecture")
117
+
118
+ elif isinstance(binary, lief.MachO.Binary):
119
+ match binary.header.cpu_type:
120
+ case lief.MachO.Header.CPU_TYPE.ARM64:
121
+ arch = Arch.arm_64
122
+ case lief.MachO.Header.CPU_TYPE.X86_64:
123
+ arch = Arch.x86_64
124
+ case _ as v:
125
+ raise ValueError(f"Unsupported CPU type {v}")
126
+
127
+ # PE
128
+ elif isinstance(binary, lief.PE.Binary):
129
+ match binary.header.machine:
130
+ case lief.PE.Header.MACHINE_TYPES.ARM64:
131
+ arch = Arch.arm_64
132
+ case lief.PE.Header.MACHINE_TYPES.AMD64:
133
+ arch = Arch.x86_64
134
+ case _ as v:
135
+ raise ValueError(f"Unsupported CPU type {v}")
136
+
137
+ else:
138
+ raise ValueError("Unsupported binary format")
139
+
140
+ return arch
141
+
142
+
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."""
227
+
228
+ if isinstance(binary, Path):
229
+ binary = parse_binary(binary)
230
+
231
+ if binary.format == lief.Binary.FORMATS.MACHO:
232
+ flags = {
233
+ lief.MachO.Section.FLAGS.PURE_INSTRUCTIONS, # type: ignore
234
+ lief.MachO.Section.FLAGS.SOME_INSTRUCTIONS, # type: ignore
235
+ }
236
+ for section in binary.sections:
237
+ if flags.intersection(section.flags_list): # type: ignore
238
+ yield ChunkCode(section.virtual_address, section.content.tobytes())
239
+
240
+ elif binary.format == lief.Binary.FORMATS.PE:
241
+ for section in binary.sections:
242
+ if section.has_characteristic( # type: ignore
243
+ lief.PE.Section.CHARACTERISTICS.CNT_CODE
244
+ ) and section.has_characteristic( # type: ignore
245
+ lief.PE.Section.CHARACTERISTICS.MEM_EXECUTE
246
+ ):
247
+ yield ChunkCode(section.virtual_address, section.content.tobytes())
248
+
249
+ elif binary.format == lief.Binary.FORMATS.ELF:
250
+ excluded = read_excluded_ranges(binary) if exclude_arm_data else {}
251
+ for index, section in enumerate(binary.sections):
252
+ if section.has(lief.ELF.Section.FLAGS.EXECINSTR): # type: ignore
253
+ yield ChunkCode(
254
+ section.virtual_address,
255
+ section.content.tobytes(),
256
+ excluded.get(index, ()),
257
+ )
258
+
259
+
260
+ def get_function(
261
+ binary: Path | lief.Binary, name: str, exclude_arm_data: bool
262
+ ) -> FunctionCode:
263
+
264
+ if isinstance(binary, Path):
265
+ binary = parse_binary(binary)
266
+
267
+ for f in iter_functions(binary, exclude_arm_data):
268
+ if f.name == name:
269
+ return f
270
+
271
+ raise LookupError(f"Function {name} not found in {binary}")
272
+
273
+
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."""
280
+
281
+ if isinstance(binary, Path):
282
+ binary = parse_binary(binary)
283
+
284
+ cache: dict[int, tuple[bytes, int]] = {}
285
+ sym: lief.ELF.Symbol
286
+
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] = []
292
+
293
+ for sym in binary.symtab_symbols: # type: ignore
294
+ if sym.type != lief.ELF.Symbol.TYPE.FUNC or sym.size == 0:
295
+ continue
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)
302
+ continue
303
+
304
+ section = sections[section_index]
305
+ if section_index not in cache:
306
+ cache[section_index] = (bytes(section.content), section.virtual_address)
307
+
308
+ section_content, section_address = cache[section_index]
309
+ address = _symbol_address(sym, section, relocatable)
310
+ offset = address - section_address
311
+ if offset < 0 or offset + sym.size > len(section_content):
312
+ logger.warning(f"Skip function {sym.name}: out of section {section.name}")
313
+ continue
314
+
315
+ assert isinstance(sym.name, str)
316
+ yield FunctionCode(
317
+ address,
318
+ section_content[offset : offset + sym.size],
319
+ iter_valid_ranges(excluded.get(section_index, ()), address, address + sym.size),
320
+ name=sym.name,
321
+ )
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
+
329
+
330
+ def lookup_chunk(
331
+ binary: Path | lief.Binary,
332
+ start_address: int,
333
+ end_address: int,
334
+ exclude_arm_data: bool,
335
+ ) -> ChunkCode:
336
+ """Returns the code at given address from the given binary.
337
+
338
+ Args:
339
+ binary (Path | lief.Binary): Binary to read.
340
+ start_address (int): Address of the first instruction to return.
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.
343
+
344
+ Returns:
345
+ ChunkCode: A piece of binary code, with the ranges not to lift.
346
+ """
347
+
348
+ for section in iter_code_sections(binary, exclude_arm_data):
349
+ if (
350
+ section.address <= start_address
351
+ and section.address + len(section.content) >= end_address
352
+ ):
353
+ offset = start_address - section.address
354
+ size = end_address - start_address
355
+ return ChunkCode(
356
+ start_address,
357
+ section.content[offset : offset + size],
358
+ iter_valid_ranges(section.excluded, start_address, end_address),
359
+ )
360
+
361
+ raise LookupError("Cannot find a section containing given range")
362
+
363
+
364
+ def collect_functions(
365
+ binary: Path | lief.Binary,
366
+ translator: Translator,
367
+ exclude_arm_data: bool,
368
+ ) -> Iterator[FunctionOps]:
369
+
370
+ logger.debug(f"Extract functions")
371
+
372
+ for function in iter_functions(binary, exclude_arm_data):
373
+
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
+ )
382
+ yield FunctionOps(
383
+ len(instructions),
384
+ function.address,
385
+ operations,
386
+ function.name,
387
+ )
388
+
389
+
390
+ def collect_basic_blocks(
391
+ binary: Path | lief.Binary,
392
+ translator: Translator,
393
+ min_instructions: int,
394
+ max_instructions: int,
395
+ exclude_arm_data: bool,
396
+ ) -> Iterator[ChunkOps]:
397
+ """Extracts the P-Code operations of basic blocks found in a binary, using LIEF library."""
398
+
399
+ logger.debug(f"Extract basic blocks")
400
+
401
+ # Extract P-Code operations of executable sections
402
+ for section in iter_code_sections(binary, exclude_arm_data):
403
+
404
+ # Slice into basic blocks
405
+ num_instructions = 0
406
+ operations = []
407
+ bb_start_address = next_address = section.address # Set on first instruction
408
+
409
+ # First disassemble to translate into P-Code one instruction at a time,
410
+ # in order to avoid consuming too much RAM.
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
422
+
423
+ instr_offset = instr.address - section.address
424
+ instr_code = section.content[instr_offset : instr_offset + instr.length]
425
+
426
+ instr_ops = translator.translate(instr_code, instr.address)
427
+
428
+ num_instructions += 1
429
+
430
+ if num_instructions <= max_instructions:
431
+ operations += instr_ops
432
+
433
+ last_op = instr_ops[-1]
434
+ if last_op.opcode not in {
435
+ OpCode.BRANCH,
436
+ OpCode.BRANCHIND,
437
+ OpCode.CBRANCH,
438
+ OpCode.RETURN,
439
+ }:
440
+ # Not at the end of a basic block
441
+ continue
442
+
443
+ if min_instructions <= num_instructions <= max_instructions:
444
+ yield ChunkOps(num_instructions, bb_start_address, operations)
445
+
446
+ num_instructions = 0
447
+
448
+
449
+ def collect_chunks(
450
+ binary: Path | lief.Binary,
451
+ translator: Translator,
452
+ exclude_arm_data: bool,
453
+ ) -> Iterator[ChunkOps]:
454
+ """Extracts the P-Code operations of the sections found in a binary, using LIEF library."""
455
+
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
+ )
@@ -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)