pcode-graph 4.0.0__tar.gz → 4.2.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 (63) hide show
  1. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/CHANGELOG +8 -0
  2. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/PKG-INFO +2 -1
  3. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/analysis/alias_analysis.py +80 -45
  4. pcode_graph-4.2.0/pcode_graph/analysis/def_use.py +115 -0
  5. pcode_graph-4.2.0/pcode_graph/analysis/interning.py +11 -0
  6. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/analysis/program.py +42 -29
  7. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/characterization.py +40 -49
  8. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pyproject.toml +2 -1
  9. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/analysis_test.py +1 -1
  10. pcode_graph-4.2.0/tests/def_use_test.py +98 -0
  11. pcode_graph-4.2.0/tests/memory_state_test.py +65 -0
  12. pcode_graph-4.0.0/pcode_graph/analysis/def_use.py +0 -116
  13. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/.github/workflows/release.yml +0 -0
  14. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/.github/workflows/test.yml +0 -0
  15. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/.gitignore +0 -0
  16. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/LICENSE +0 -0
  17. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/README.md +0 -0
  18. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/__init__.py +0 -0
  19. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/__main__.py +0 -0
  20. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/analysis/cfg.py +0 -0
  21. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/analysis/load_store.py +0 -0
  22. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/analysis/native_pcode.py +0 -0
  23. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/analysis/pass_base.py +0 -0
  24. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/analysis/passes.py +0 -0
  25. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/analysis/unreachable.py +0 -0
  26. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/arch.py +0 -0
  27. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/asm.py +0 -0
  28. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/basic_blocks.py +0 -0
  29. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/bit_utils.py +0 -0
  30. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/checker.py +0 -0
  31. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/cli.py +0 -0
  32. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/emulator.py +0 -0
  33. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/gnn_exporter.py +0 -0
  34. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/graph.py +0 -0
  35. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/lief_importer.py +0 -0
  36. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/log.py +0 -0
  37. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/maker.py +0 -0
  38. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/nx_exporter.py +0 -0
  39. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/pcode.py +0 -0
  40. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/registers.py +0 -0
  41. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/simplifier.py +0 -0
  42. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/torch_utils.py +0 -0
  43. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/translator.py +0 -0
  44. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/view.py +0 -0
  45. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/pcode_graph/visitor.py +0 -0
  46. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/requirements.txt +0 -0
  47. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/__init__.py +0 -0
  48. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/basic_block_test.py +0 -0
  49. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/callother_test.py +0 -0
  50. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/charac_test.py +0 -0
  51. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/cli_test.py +0 -0
  52. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/conftest.py +0 -0
  53. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/emulator_test.py +0 -0
  54. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/exporter_test.py +0 -0
  55. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/fixtures.py +0 -0
  56. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/helpers.py +0 -0
  57. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/lief_importer_test.py +0 -0
  58. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/load_store_test.py +0 -0
  59. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/maker_test.py +0 -0
  60. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/memory_test.py +0 -0
  61. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/translator_test.py +0 -0
  62. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/tests/utils_test.py +0 -0
  63. {pcode_graph-4.0.0 → pcode_graph-4.2.0}/todo.md +0 -0
@@ -1,3 +1,11 @@
1
+ # 4.2.0
2
+
3
+ - Optimize memory consumption and speed of analyses.
4
+
5
+ # 4.1.0
6
+
7
+ - Replace networkx by igraph to speed up graph characteristics computation.
8
+
1
9
  # 4.0.0
2
10
 
3
11
  - New memory model to avoid quadratic edges generation in many-stores code:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pcode_graph
3
- Version: 4.0.0
3
+ Version: 4.2.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
@@ -15,6 +15,7 @@ import heapq
15
15
 
16
16
  from pypcode import OpCode, PcodeOp
17
17
 
18
+ from pcode_graph.analysis.interning import Interner
18
19
  from pcode_graph.analysis.pass_base import PassBase
19
20
  from pcode_graph.arch import Arch
20
21
  from pcode_graph.analysis.program import (
@@ -71,42 +72,69 @@ class MemoryAccess:
71
72
  ]
72
73
 
73
74
 
74
- @dataclass(frozen=True, slots=True)
75
+ DefinitionSet = frozenset[OpIndex]
76
+
77
+
78
+ @dataclass(slots=True)
75
79
  class MemoryState:
80
+ """Definitions of memory bytes, updated in place.
81
+
82
+ A state must not be shared between blocks: copy it before updating it.
83
+ Definition sets are immutable and interned, so they can be shared.
84
+ """
85
+
76
86
  # Definitions of tracked bytes
77
- tracked: dict[MemoryByte, frozenset[OpIndex]]
87
+ tracked: dict[MemoryByte, DefinitionSet]
78
88
 
79
89
  # Definitions of untracked bytes
80
- default: frozenset[OpIndex]
90
+ default: DefinitionSet
81
91
 
82
- def read(self, access: MemoryAccess) -> frozenset[OpIndex]:
92
+ def copy(self) -> "MemoryState":
93
+ return MemoryState(dict(self.tracked), self.default)
94
+
95
+ def read(self, access: MemoryAccess) -> DefinitionSet:
83
96
  return frozenset().union(
84
97
  *(self.tracked.get(byte, self.default) for byte in access.bytes)
85
98
  )
86
99
 
87
- def write(self, access: MemoryAccess, index: OpIndex) -> "MemoryState":
88
- written = frozenset({index})
89
- tracked = dict(self.tracked)
100
+ def write(
101
+ self, access: MemoryAccess, index: OpIndex, intern: Interner[DefinitionSet]
102
+ ) -> None:
103
+ written = intern(frozenset({index}))
90
104
  for byte in access.bytes:
91
- tracked[byte] = written
92
- return MemoryState(tracked, self.default)
105
+ self.tracked[byte] = written
93
106
 
94
- def clobber(self) -> "MemoryState":
107
+ def clobber(self, intern: Interner[DefinitionSet]) -> None:
95
108
  unknown = {UnknownWriteIndex}
96
- return MemoryState(
97
- {byte: defs | unknown for byte, defs in self.tracked.items()},
98
- self.default | unknown,
99
- )
100
-
101
- def merge(self, other: "MemoryState") -> "MemoryState":
102
- return MemoryState(
103
- {
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()
107
- },
108
- self.default | other.default,
109
- )
109
+ for byte, defs in self.tracked.items():
110
+ self.tracked[byte] = intern(defs | unknown)
111
+ self.default = intern(self.default | unknown)
112
+
113
+ def merge(self, other: "MemoryState", intern: Interner[DefinitionSet]) -> bool:
114
+ """Adds the definitions of the other state, left unchanged.
115
+ Returns True if this state changed.
116
+ """
117
+
118
+ default_grows = not other.default <= self.default
119
+ changed = default_grows
120
+ for byte, theirs in other.tracked.items():
121
+ mine = self.tracked.get(byte)
122
+ if mine is None:
123
+ if not theirs <= self.default:
124
+ changed = True
125
+ elif not default_grows:
126
+ continue
127
+ self.tracked[byte] = intern(self.default | theirs)
128
+ elif mine is not theirs and not theirs <= mine:
129
+ self.tracked[byte] = intern(mine | theirs)
130
+ changed = True
131
+ for byte, mine in self.tracked.items():
132
+ if byte not in other.tracked and not other.default <= mine:
133
+ self.tracked[byte] = intern(mine | other.default)
134
+ changed = True
135
+ if default_grows:
136
+ self.default = intern(self.default | other.default)
137
+ return changed
110
138
 
111
139
 
112
140
  ADDRESS_OPCODES = {OpCode.COPY, OpCode.INT_ADD, OpCode.INT_SUB, OpCode.INT_OR}
@@ -145,7 +173,6 @@ class MemoryAnalyzer(PassBase):
145
173
  self._stores[index] = self._compute_access(index, op.inputs[2].size)
146
174
 
147
175
  self._collect_load_defs(self._compute_reads())
148
-
149
176
 
150
177
  def value_of(self, index: OpIndex, var: Var) -> AbstractValue:
151
178
  """Evaluates the given variable when read by the given operation."""
@@ -211,52 +238,60 @@ class MemoryAnalyzer(PassBase):
211
238
  return MemoryAccess(False, absolute, size)
212
239
  return None
213
240
 
214
- def _apply(self, index: OpIndex, state: MemoryState) -> MemoryState:
215
- """Returns the memory state after the given operation."""
241
+ def _apply(
242
+ self, index: OpIndex, state: MemoryState, intern: Interner[DefinitionSet]
243
+ ) -> None:
244
+ """Updates the memory state with the effect of the given operation."""
216
245
 
217
246
  op = self.program.operations[index]
218
247
  if op.opcode == OpCode.STORE:
219
248
  access = self._stores[index]
220
- return state.clobber() if access is None else state.write(access, index)
221
- if op.opcode in CALL_OPCODES and UnknownCodeIndex in self.program.succ_ops(
249
+ if access is None:
250
+ state.clobber(intern)
251
+ else:
252
+ state.write(access, index, intern)
253
+ elif op.opcode in CALL_OPCODES and UnknownCodeIndex in self.program.succ_ops(
222
254
  index
223
255
  ):
224
- return state.clobber()
225
- return state
256
+ state.clobber(intern)
226
257
 
227
- def _compute_reads(self) -> dict[OpIndex, frozenset[OpIndex]]:
258
+ def _compute_reads(self) -> dict[OpIndex, DefinitionSet]:
228
259
  """Computes the definitions of the bytes read by each resolved load."""
229
260
 
230
261
  blocks = self.program.basic_blocks
262
+ intern: Interner[DefinitionSet] = Interner()
231
263
  block_inputs: list[MemoryState | None] = [None] * len(blocks)
232
- block_inputs[0] = MemoryState({}, frozenset({EntryIndex}))
233
- reads: dict[OpIndex, frozenset[OpIndex]] = {}
264
+ block_inputs[0] = MemoryState({}, intern(frozenset({EntryIndex})))
265
+ reads: dict[OpIndex, DefinitionSet] = {}
234
266
  pending = [0]
235
267
  queued = {0}
236
268
 
237
269
  while pending:
238
270
  block_index = heapq.heappop(pending)
239
271
  queued.remove(block_index)
240
- state = block_inputs[block_index]
241
- assert state is not None
272
+ block_input = block_inputs[block_index]
273
+ assert block_input is not None
274
+ state = block_input.copy()
242
275
  for index in blocks[block_index].op_indexes:
243
276
  if index in self._loads:
244
- reads[index] = state.read(self._loads[index])
245
- state = self._apply(index, state)
277
+ reads[index] = intern(state.read(self._loads[index]))
278
+ self._apply(index, state, intern)
246
279
 
247
280
  for successor in blocks[block_index].succ_blocks:
248
281
  if successor < 0:
249
282
  continue
250
283
  previous = block_inputs[successor]
251
- merged = state if previous is None else previous.merge(state)
252
- if merged != previous:
253
- block_inputs[successor] = merged
254
- if successor not in queued:
255
- heapq.heappush(pending, successor)
256
- queued.add(successor)
284
+ if previous is None:
285
+ block_inputs[successor] = state.copy()
286
+ changed = True
287
+ else:
288
+ changed = previous.merge(state, intern)
289
+ if changed and successor not in queued:
290
+ heapq.heappush(pending, successor)
291
+ queued.add(successor)
257
292
  return reads
258
293
 
259
- def _collect_load_defs(self, reads: dict[OpIndex, frozenset[OpIndex]]) -> None:
294
+ def _collect_load_defs(self, reads: dict[OpIndex, DefinitionSet]) -> None:
260
295
  for index, definitions in reads.items():
261
296
  if UnknownWriteIndex in definitions:
262
297
  continue
@@ -0,0 +1,115 @@
1
+ import heapq
2
+
3
+ from .interning import Interner
4
+ from .pass_base import PassBase
5
+ from .program import (
6
+ BasicBlock,
7
+ Definitions,
8
+ EntryIndex,
9
+ LocalWriters,
10
+ OpIndex,
11
+ Var,
12
+ VarKinds,
13
+ wrap,
14
+ split,
15
+ )
16
+
17
+ DefinitionInterner = Interner[frozenset[OpIndex]]
18
+
19
+
20
+ class ReachingDefBuilder(PassBase):
21
+ """Computes reaching definitions at the entry of each block.
22
+
23
+ Identical definition sets are shared (interned) to reduce the memory retained by
24
+ the results on large functions.
25
+ """
26
+
27
+ def __call__(self) -> None:
28
+ block_count = len(self.program.basic_blocks)
29
+ block_inputs: list[Definitions] = [{} for _ in range(block_count)]
30
+ block_writers: list[LocalWriters] = [{} for _ in range(block_count)]
31
+ self.program.block_inputs = block_inputs
32
+ self.program.block_writers = block_writers
33
+ if not block_count:
34
+ return
35
+
36
+ intern: DefinitionInterner = Interner()
37
+ entry = intern(frozenset({EntryIndex}))
38
+ shared_temporaries: set[Var] = set()
39
+ for block_index, block in enumerate(self.program.basic_blocks):
40
+ if not block.reachable:
41
+ continue
42
+ writers = self._collect_writers(block)
43
+ block_writers[block_index] = writers
44
+ for index in block.op_indexes:
45
+ for var in self.program.iter_inputs(index):
46
+ if var.kind == VarKinds.Register:
47
+ for byte in split(var):
48
+ block_inputs[0][byte] = entry
49
+ elif var.kind == VarKinds.Unique:
50
+ # Temporary bytes read in a block before being written in it
51
+ for byte in split(var):
52
+ byte_writers = writers.get(byte)
53
+ if not byte_writers or byte_writers[0] >= index:
54
+ shared_temporaries.add(byte)
55
+
56
+ # Block effects: last writer of each byte written in the block
57
+ generated_by_block: list[Definitions] = [
58
+ {
59
+ byte: intern(frozenset((byte_writers[-1],)))
60
+ for byte, byte_writers in writers.items()
61
+ if byte.kind != VarKinds.Unique or byte in shared_temporaries
62
+ }
63
+ for writers in block_writers
64
+ ]
65
+
66
+ # Each reachable block is processed at least once, lowest index first:
67
+ # follows the code layout, close to a reverse post-order.
68
+ # The list is sorted, so it is already a valid heap.
69
+ pending = [
70
+ index
71
+ for index, block in enumerate(self.program.basic_blocks)
72
+ if block.reachable
73
+ ]
74
+ queued = set(pending)
75
+
76
+ while pending:
77
+ block_index = heapq.heappop(pending)
78
+ queued.remove(block_index)
79
+
80
+ outputs = block_inputs[block_index] | generated_by_block[block_index]
81
+ for successor in self.program.basic_blocks[block_index].succ_blocks:
82
+ if successor < 0:
83
+ continue
84
+ changed = self._merge_definitions(
85
+ block_inputs[successor], outputs, intern
86
+ )
87
+ if changed and successor not in queued:
88
+ heapq.heappush(pending, successor)
89
+ queued.add(successor)
90
+
91
+ def _collect_writers(self, block: BasicBlock) -> LocalWriters:
92
+ writers: LocalWriters = {}
93
+ for index in block.op_indexes:
94
+ output = self.program.operations[index].output
95
+ if output:
96
+ for byte in split(wrap(output)):
97
+ writers.setdefault(byte, []).append(index)
98
+ return writers
99
+
100
+ @staticmethod
101
+ def _merge_definitions(
102
+ target: Definitions, source: Definitions, intern: DefinitionInterner
103
+ ) -> bool:
104
+ """Adds source definitions to target ones, returns True if target changed."""
105
+
106
+ changed = False
107
+ for var, defs in source.items():
108
+ target_defs = target.get(var)
109
+ if target_defs is None:
110
+ target[var] = defs
111
+ changed = True
112
+ elif target_defs is not defs and not defs <= target_defs:
113
+ target[var] = intern(target_defs | defs)
114
+ changed = True
115
+ return changed
@@ -0,0 +1,11 @@
1
+ from collections.abc import Hashable
2
+
3
+
4
+ class Interner[T: Hashable]:
5
+ """Stores equal, unmutable shared instance to save memory, like identical strings."""
6
+
7
+ def __init__(self) -> None:
8
+ self._values: dict[T, T] = {}
9
+
10
+ def __call__(self, value: T) -> T:
11
+ return self._values.setdefault(value, value)
@@ -1,3 +1,4 @@
1
+ from bisect import bisect_left
1
2
  from dataclasses import dataclass, field
2
3
  from enum import Enum
3
4
  from functools import cache
@@ -72,23 +73,10 @@ def wrap(var: Varnode) -> Var:
72
73
 
73
74
 
74
75
  # Writing operations by variable byte (see split)
75
- Definitions = dict[Var, set[OpIndex]]
76
+ Definitions = dict[Var, frozenset[OpIndex]]
76
77
 
77
-
78
- def apply_operation(
79
- definitions: Definitions,
80
- index: OpIndex,
81
- op: PcodeOp,
82
- ) -> Definitions:
83
- """Returns the new definitions after the given operation is applied."""
84
-
85
- if op.output:
86
- result = dict(definitions)
87
- written = {index}
88
- for byte in split(wrap(op.output)):
89
- result[byte] = written
90
- return result
91
- return definitions
78
+ # Writing operations inside a block by variable byte, sorted by index
79
+ LocalWriters = dict[Var, list[OpIndex]]
92
80
 
93
81
 
94
82
  def split(var: Var) -> tuple[Var, ...]:
@@ -156,11 +144,15 @@ class Program:
156
144
  basic_blocks: list[BasicBlock] = field(default_factory=list)
157
145
  block_indexes: list[BlockIndex] = field(default_factory=list)
158
146
 
159
- # Reaching definitions. For each operation, by variable, list of:
160
- # - definitions (= writing operation index) that reach this operation,
147
+ # Reaching definitions at the entry of each block. By variable byte, set of:
148
+ # - definitions (= writing operation index) that reach the block,
161
149
  # - or EntryIndex (for initial definitions of inputs).
162
- # Sets are shared between operations: do not modify them.
163
- reaching_defs: list[Definitions] = field(default_factory=list)
150
+ # P-Code temporaries are only kept if read in a block before being written in it.
151
+ # Definitions inside a block are derived on demand from block_writers,
152
+ # which avoids storing a full copy of the definitions for each operation.
153
+ # Both are empty for unreachable blocks.
154
+ block_inputs: list[Definitions] = field(default_factory=list)
155
+ block_writers: list[LocalWriters] = field(default_factory=list)
164
156
 
165
157
  # Memory analysis results
166
158
  memory: Memory = field(default_factory=Memory)
@@ -232,25 +224,46 @@ class Program:
232
224
  def get_defs(self, index: OpIndex, var: Var) -> set[OpIndex]:
233
225
  """Returns all the operations defining the value at given operation of the given variable."""
234
226
 
235
- definitions = self.reaching_defs[index]
227
+ block_index = self.block_indexes[index]
228
+ inputs = self.block_inputs[block_index]
229
+ writers = self.block_writers[block_index]
236
230
  defs: set[OpIndex] = set()
237
231
  for byte in split(var):
238
- defs |= definitions.get(byte, set())
232
+ byte_writers = writers.get(byte)
233
+ if byte_writers:
234
+ position = bisect_left(byte_writers, index)
235
+ if position:
236
+ defs.add(byte_writers[position - 1])
237
+ continue
238
+ defs.update(inputs.get(byte, ()))
239
239
  return defs
240
240
 
241
- def get_exit_defs(self) -> Definitions:
241
+ def get_reaching_defs(self, index: OpIndex) -> Definitions:
242
+ """Returns all the definitions reaching the given operation.
243
+ P-Code temporaries written in other blocks are omitted if not read before being
244
+ written in this block.
245
+ """
246
+
247
+ return self._definitions_before(self.block_indexes[index], index)
248
+
249
+ def _definitions_before(self, block_index: BlockIndex, end: OpIndex) -> Definitions:
250
+ definitions = dict(self.block_inputs[block_index])
251
+ for byte, writers in self.block_writers[block_index].items():
252
+ position = bisect_left(writers, end)
253
+ if position:
254
+ definitions[byte] = frozenset((writers[position - 1],))
255
+ return definitions
256
+
257
+ def get_exit_defs(self) -> dict[Var, set[OpIndex]]:
242
258
  """Computes side effects of the program."""
243
259
 
244
- exit_defs: Definitions = {}
245
- for block in self.basic_blocks:
260
+ exit_defs: dict[Var, set[OpIndex]] = {}
261
+ for block_index, block in enumerate(self.basic_blocks):
246
262
  if not block.reachable or not {UnknownCodeIndex, ExitIndex}.intersection(
247
263
  block.succ_blocks
248
264
  ):
249
265
  continue
250
- index = block.last_op_index
251
- outputs = apply_operation(
252
- self.reaching_defs[index], index, self.operations[index]
253
- )
266
+ outputs = self._definitions_before(block_index, block.end)
254
267
  for byte, defs in outputs.items():
255
268
  if byte.kind == VarKinds.Unique:
256
269
  # Ignore P-Code temporary
@@ -1,10 +1,8 @@
1
1
  from enum import IntFlag, auto
2
- from typing import NamedTuple
3
- import networkx as nx
4
-
5
-
2
+ from typing import Callable, NamedTuple
3
+ import igraph
6
4
  from pcode_graph.nx_exporter import export_to_networkx
7
- from pcode_graph.graph import CDG, EdgeKinds, NodeKinds
5
+ from pcode_graph.graph import CDG, Edge, EdgeKinds, NodeKinds
8
6
  from pcode_graph.pcode import OpCodes
9
7
 
10
8
 
@@ -29,51 +27,37 @@ def count_edges(cdg: CDG) -> GraphCharacteristics:
29
27
  return GraphCharacteristics(data_only, len(cdg.edges) - data_only, len(cdg.edges))
30
28
 
31
29
 
32
- def get_graph_diameters(cdg: CDG) -> GraphCharacteristics:
33
- """Computes the diameter of the given graph."""
34
-
35
- n = len(cdg.nodes)
36
-
37
- def build_adjacency(edges):
38
- adj = [[] for _ in range(n)]
39
- for e in edges:
40
- adj[e.source_node].append(e.destination_node)
41
- return adj
42
-
43
- data_edges = []
44
- ctrl_edges = []
45
- for e in cdg.edges:
46
- if e.kind == EdgeKinds.Data:
47
- data_edges.append(e)
48
- else:
49
- ctrl_edges.append(e)
50
-
51
- def diameter(adjacency) -> int:
52
- # Compute graph diameter with BFS
53
- d = 0
54
- for src in range(n):
55
- dist = [-1] * n
56
- dist[src] = 0
57
- front = deque((src,))
58
- while front:
59
- current = front.popleft()
60
- for neigbor in adjacency[current]:
61
- if dist[neigbor] == -1:
62
- dist[neigbor] = dist[current] + 1
63
- front.append(neigbor)
64
- d = max(d, max(dist))
65
- return d
30
+ def get_graph_diameter(
31
+ cdg: CDG,
32
+ edge_filter: Callable[[Edge], bool] = lambda e: True,
33
+ ) -> int:
34
+ """Computes the undirected diameter of the given graph."""
35
+
36
+ undirected = igraph.Graph(
37
+ n=len(cdg.nodes),
38
+ edges=[
39
+ (edge.source_node, edge.destination_node)
40
+ for edge in cdg.edges
41
+ if edge_filter(edge)
42
+ ],
43
+ directed=True,
44
+ )
45
+ return undirected.diameter(directed=True, unconn=True)
46
+
66
47
 
48
+ def get_graph_diameters(
49
+ cdg: CDG,
50
+ ) -> GraphCharacteristics:
67
51
  return GraphCharacteristics(
68
- diameter(build_adjacency(data_edges)),
69
- diameter(build_adjacency(ctrl_edges)),
70
- diameter(build_adjacency(chain(data_edges, ctrl_edges))),
52
+ data_only=get_graph_diameter(cdg, lambda e: e.kind == EdgeKinds.Data),
53
+ control_only=get_graph_diameter(cdg, lambda e: e.kind != EdgeKinds.Data),
54
+ both=get_graph_diameter(cdg),
71
55
  )
72
56
 
73
57
 
74
58
  class FunctionCharacteristics(IntFlag):
75
59
  """Helps evaluating the level of difficulty of a function,
76
- regarding miscalleneous ML tasks."""
60
+ regarding miscellaneous ML tasks."""
77
61
 
78
62
  data = auto()
79
63
  condition = auto()
@@ -83,18 +67,25 @@ class FunctionCharacteristics(IntFlag):
83
67
  loop = auto()
84
68
 
85
69
 
70
+ def has_loops(cdg: CDG) -> bool:
71
+ """Returns True if the given graph has loops."""
72
+ edges = []
73
+ for edge in cdg.edges:
74
+ if edge.kind == EdgeKinds.Control:
75
+ edges.append((edge.source_node, edge.destination_node))
76
+ elif edge.kind == EdgeKinds.BasicBlockMembership:
77
+ # Reverse membership to create cycles
78
+ edges.append((edge.destination_node, edge.source_node))
79
+ return not igraph.Graph(n=len(cdg.nodes), edges=edges, directed=True).is_dag()
80
+
81
+
86
82
  def get_function_characteristics(graph: CDG) -> FunctionCharacteristics:
87
83
  """Characterizes a function regarding control flow features."""
88
84
 
89
85
  # Every function contains data-flow easiest level
90
86
  function_characteristics = FunctionCharacteristics.data
91
87
 
92
- ng = export_to_networkx(graph, False)
93
- try:
94
- nx.find_cycle(ng)
95
- except nx.NetworkXNoCycle:
96
- pass
97
- else:
88
+ if has_loops(graph):
98
89
  function_characteristics |= FunctionCharacteristics.loop
99
90
 
100
91
  for n in graph.nodes:
@@ -17,7 +17,8 @@ dependencies = [
17
17
  "pypcode>=4.0.1",
18
18
  "pyvis",
19
19
  "lief~=1.0.0",
20
- "docopt"
20
+ "docopt",
21
+ "igraph~=1.0.0"
21
22
  ]
22
23
 
23
24
  license = "MIT"
@@ -203,7 +203,7 @@ ldr x2, [sp, #0x10]
203
203
  ]
204
204
  assert all(
205
205
  var.kind in {VarKinds.Register, VarKinds.Unique}
206
- for var in prg.reaching_defs[6]
206
+ for var in prg.get_reaching_defs(6)
207
207
  )
208
208
  assert 3 not in set().union(*prg.get_exit_defs().values())
209
209
 
@@ -0,0 +1,98 @@
1
+ from pcode_graph.analysis.program import (
2
+ EntryIndex,
3
+ OpIndex,
4
+ Program,
5
+ Var,
6
+ VarKinds,
7
+ split,
8
+ wrap,
9
+ )
10
+ from tests.helpers import make_program_from_asm
11
+ from .fixtures import ArchContext, arm64, x86_64
12
+
13
+
14
+ def reference_reaching_defs(program: Program) -> list[dict[Var, set[OpIndex]]]:
15
+ """Naive operation-level fixed point, storing all definitions for each operation."""
16
+
17
+ entry = {
18
+ byte: {EntryIndex}
19
+ for index in range(len(program.operations))
20
+ if program.reachable(index)
21
+ for var in program.iter_inputs(index)
22
+ if var.kind == VarKinds.Register
23
+ for byte in split(var)
24
+ }
25
+ inputs: list[dict[Var, set[OpIndex]]] = [{} for _ in program.operations]
26
+ changed = True
27
+ while changed:
28
+ changed = False
29
+ for index, op in enumerate(program.operations):
30
+ if not program.reachable(index):
31
+ continue
32
+ merged: dict[Var, set[OpIndex]] = {}
33
+ for pred in program.pred_ops(index):
34
+ if pred == EntryIndex:
35
+ pred_outputs = entry
36
+ else:
37
+ pred_outputs = dict(inputs[pred])
38
+ output = program.operations[pred].output
39
+ if output:
40
+ pred_outputs.update(
41
+ {byte: {pred} for byte in split(wrap(output))}
42
+ )
43
+ for byte, defs in pred_outputs.items():
44
+ merged.setdefault(byte, set()).update(defs)
45
+ if merged != inputs[index]:
46
+ inputs[index] = merged
47
+ changed = True
48
+ return inputs
49
+
50
+
51
+ def check_against_reference(program: Program) -> None:
52
+ reference = reference_reaching_defs(program)
53
+ for index in range(len(program.operations)):
54
+ for var in program.iter_inputs(index):
55
+ expected = set().union(
56
+ *(reference[index].get(byte, set()) for byte in split(var))
57
+ )
58
+ assert program.get_defs(index, var) == expected, (index, var)
59
+
60
+
61
+ def test_matches_reference_with_shared_temporaries(x86_64: ArchContext):
62
+ program = make_program_from_asm(
63
+ """
64
+ loop:
65
+ cmovz rax, rbx
66
+ bsf rcx, rax
67
+ mov qword ptr [rsp + 8], rcx
68
+ mov dl, byte ptr [rsp + 8]
69
+ sub rbx, 1
70
+ jnz loop
71
+ ret
72
+ """,
73
+ x86_64,
74
+ )
75
+ # cmovz and bsf use P-Code temporaries across their internal blocks
76
+ assert any(
77
+ byte.kind == VarKinds.Unique
78
+ for inputs in program.block_inputs
79
+ for byte in inputs
80
+ )
81
+ check_against_reference(program)
82
+
83
+
84
+ def test_matches_reference_on_arm64(arm64: ArchContext):
85
+ program = make_program_from_asm(
86
+ """
87
+ loop:
88
+ csel x0, x1, x2, eq
89
+ add w1, w1, w0
90
+ cbz x0, done
91
+ subs x2, x2, #1
92
+ b.ne loop
93
+ done:
94
+ ret
95
+ """,
96
+ arm64,
97
+ )
98
+ check_against_reference(program)
@@ -0,0 +1,65 @@
1
+ import random
2
+
3
+ from pcode_graph.analysis.alias_analysis import (
4
+ DefinitionSet,
5
+ MemoryAccess,
6
+ MemoryByte,
7
+ MemoryState,
8
+ UnknownWriteIndex,
9
+ )
10
+ from pcode_graph.analysis.interning import Interner
11
+
12
+ ALL_BYTES: list[MemoryByte] = [
13
+ (in_stack, offset) for in_stack in (True, False) for offset in range(8)
14
+ ]
15
+
16
+
17
+ def random_state(
18
+ generator: random.Random, intern: Interner[DefinitionSet]
19
+ ) -> MemoryState:
20
+ def random_definitions() -> DefinitionSet:
21
+ return intern(frozenset(generator.sample(range(6), generator.randint(0, 3))))
22
+
23
+ tracked = {
24
+ (generator.random() < 0.5, generator.randint(0, 5)): random_definitions()
25
+ for _ in range(generator.randint(0, 6))
26
+ }
27
+ return MemoryState(tracked, random_definitions())
28
+
29
+
30
+ def definitions_of(state: MemoryState) -> dict[MemoryByte, DefinitionSet]:
31
+ return {byte: state.tracked.get(byte, state.default) for byte in ALL_BYTES}
32
+
33
+
34
+ def test_merge_matches_union_of_definitions():
35
+ generator = random.Random(0)
36
+ intern: Interner[DefinitionSet] = Interner()
37
+ for _ in range(20000):
38
+ state = random_state(generator, intern)
39
+ other = random_state(generator, intern)
40
+ before = definitions_of(state)
41
+ other_before = definitions_of(other)
42
+ expected = {
43
+ byte: definitions | other_before[byte]
44
+ for byte, definitions in before.items()
45
+ }
46
+
47
+ changed = state.merge(other, intern)
48
+
49
+ assert definitions_of(state) == expected
50
+ assert definitions_of(other) == other_before
51
+ assert changed == (before != expected)
52
+
53
+
54
+ def test_write_and_clobber():
55
+ intern: Interner[DefinitionSet] = Interner()
56
+ state = MemoryState({}, intern(frozenset({-1})))
57
+ access = MemoryAccess(True, 2, 4)
58
+ state.write(access, 7, intern)
59
+ copy = state.copy()
60
+ copy.clobber(intern)
61
+
62
+ assert state.read(access) == {7}
63
+ assert state.read(MemoryAccess(True, 0, 4)) == {-1, 7}
64
+ assert copy.read(access) == {7, UnknownWriteIndex}
65
+ assert copy.read(MemoryAccess(False, 0, 1)) == {-1, UnknownWriteIndex}
@@ -1,116 +0,0 @@
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
File without changes
File without changes
File without changes
File without changes