pcode-graph 2.0.2__tar.gz → 3.0.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 (50) hide show
  1. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/.github/workflows/release.yml +2 -0
  2. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/CHANGELOG +4 -0
  3. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/PKG-INFO +7 -1
  4. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/README.md +6 -0
  5. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/cli.py +6 -4
  6. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/lief_importer.py +11 -4
  7. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/maker.py +50 -14
  8. pcode_graph-3.0.0/pcode_graph/memory.py +271 -0
  9. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pyproject.toml +5 -2
  10. pcode_graph-3.0.0/tests/cli_test.py +29 -0
  11. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/fixtures.py +15 -0
  12. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/maker_test.py +4 -2
  13. pcode_graph-3.0.0/tests/memory_test.py +285 -0
  14. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/.github/workflows/test.yml +0 -0
  15. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/.gitignore +0 -0
  16. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/LICENSE +0 -0
  17. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/__init__.py +0 -0
  18. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/__main__.py +0 -0
  19. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/analysis.py +0 -0
  20. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/arch.py +0 -0
  21. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/asm.py +0 -0
  22. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/basic_blocks.py +0 -0
  23. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/bit_utils.py +0 -0
  24. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/characterization.py +0 -0
  25. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/checker.py +0 -0
  26. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/emulator.py +0 -0
  27. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/gnn_exporter.py +0 -0
  28. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/graph.py +0 -0
  29. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/log.py +0 -0
  30. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/nx_exporter.py +0 -0
  31. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/pcode.py +0 -0
  32. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/registers.py +0 -0
  33. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/simplifier.py +0 -0
  34. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/torch_utils.py +0 -0
  35. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/translator.py +0 -0
  36. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/view.py +0 -0
  37. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/pcode_graph/visitor.py +0 -0
  38. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/requirements.txt +0 -0
  39. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/__init__.py +0 -0
  40. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/analysis_test.py +0 -0
  41. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/basic_block_test.py +0 -0
  42. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/callother_test.py +0 -0
  43. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/charac_test.py +0 -0
  44. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/conftest.py +0 -0
  45. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/emulator_test.py +0 -0
  46. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/exporter_test.py +0 -0
  47. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/helpers.py +0 -0
  48. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/translator_test.py +0 -0
  49. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/tests/utils_test.py +0 -0
  50. {pcode_graph-2.0.2 → pcode_graph-3.0.0}/todo.md +0 -0
@@ -8,6 +8,8 @@ jobs:
8
8
  runs-on: ubuntu-latest
9
9
  steps:
10
10
  - uses: actions/checkout@v4
11
+ with:
12
+ fetch-depth: 0
11
13
  - uses: actions/setup-python@v5
12
14
  with:
13
15
  python-version: "3.12"
@@ -1,3 +1,7 @@
1
+ # 3.0.0
2
+
3
+ - Add stack memory analysis to resolve loads whenever it possible, mainly for code compiled with -O0.
4
+
1
5
  # 2.0.0
2
6
 
3
7
  - Add basic blocks node in the graph, to make the graph invariant by instruction reordering, while reducing its diameter. The previous format is still available by setting maker flags. Because of new "membership" edge kind, the number of egde features changed.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pcode_graph
3
- Version: 2.0.2
3
+ Version: 3.0.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
@@ -140,6 +140,12 @@ mul x1, x0, x0
140
140
  graph = make_graph_from_asm(assembler, translator, asm)
141
141
  ```
142
142
 
143
+ ### Pointer alias analysis
144
+
145
+ Addresses are resolved relatively to the stack pointer at entry, to link each stack LOAD to the STOREs it actually reads. This mainly helps with code compiled without optimization, where variables are spilled.
146
+
147
+ A part from this, no advanced alias analysis is performed and no assumption is made about the used ABI.
148
+
143
149
  ### View the graph
144
150
 
145
151
  You can unparse the graph into markdown using the mermaid syntax:
@@ -113,6 +113,12 @@ mul x1, x0, x0
113
113
  graph = make_graph_from_asm(assembler, translator, asm)
114
114
  ```
115
115
 
116
+ ### Pointer alias analysis
117
+
118
+ Addresses are resolved relatively to the stack pointer at entry, to link each stack LOAD to the STOREs it actually reads. This mainly helps with code compiled without optimization, where variables are spilled.
119
+
120
+ A part from this, no advanced alias analysis is performed and no assumption is made about the used ABI.
121
+
116
122
  ### View the graph
117
123
 
118
124
  You can unparse the graph into markdown using the mermaid syntax:
@@ -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
+ -M, --no-memory-analysis Disable stack memory analysis and keep all LOADs in the graph.
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.
@@ -43,7 +44,7 @@ from pcode_graph.lief_importer import (
43
44
  iter_functions,
44
45
  get_architecture,
45
46
  lookup_chunk,
46
- parse_binary,
47
+ try_parse_binary,
47
48
  )
48
49
  from pcode_graph.log import setup_logger
49
50
  from pcode_graph.translator import Translator
@@ -64,10 +65,10 @@ def main():
64
65
  setup_logger()
65
66
 
66
67
  input_path = Path(args["<input_path>"])
67
- assert input_path.exists()
68
+ assert input_path.exists(), f"{input_path} does not exist"
68
69
 
69
70
  assert input_path.stat().st_size > 0, "Input file is empty"
70
- binary: Binary | None = parse_binary(input_path)
71
+ binary: Binary | None = try_parse_binary(input_path)
71
72
 
72
73
  if args["--arch"] != "auto":
73
74
  arch: Arch = Arch(args["--arch"])
@@ -165,6 +166,7 @@ def main():
165
166
  flags = MakerFlags(
166
167
  build_cfg=not args["--dataflow-only"],
167
168
  basic_blocks=not args["--flat-cfg"],
169
+ memory_analysis=not args["--no-memory-analysis"],
168
170
  )
169
171
  cdg = make_graph(rpl, flags)
170
172
 
@@ -190,5 +192,5 @@ def main():
190
192
  except Exception as e:
191
193
  if args["--debug"]:
192
194
  raise
193
- print(str(e), file=sys.stderr)
195
+ print(str(e) or type(e).__name__, file=sys.stderr)
194
196
  sys.exit(1)
@@ -28,12 +28,19 @@ class FunctionOps(ChunkOps):
28
28
  function_name: str
29
29
 
30
30
 
31
- def parse_binary(binary_path: Path) -> lief.Binary:
31
+ def try_parse_binary(binary_path: Path) -> lief.Binary | None:
32
+ """Parses the given file, or returns None if LIEF does not recognize its format."""
33
+
32
34
  assert binary_path.is_file(), f"{binary_path} is not a file"
33
35
  logger.debug(f"Parse {binary_path}")
34
- b = lief.parse(binary_path.as_posix())
35
- assert isinstance(b, lief.Binary)
36
- return b
36
+ binary = lief.parse(binary_path.as_posix())
37
+ return binary if isinstance(binary, lief.Binary) else None
38
+
39
+
40
+ def parse_binary(binary_path: Path) -> lief.Binary:
41
+ binary = try_parse_binary(binary_path)
42
+ assert binary is not None, f"{binary_path} is not a supported binary"
43
+ return binary
37
44
 
38
45
 
39
46
  def get_architecture(binary: Path | lief.Binary) -> Arch:
@@ -1,18 +1,21 @@
1
- from dataclasses import dataclass, field
1
+ from dataclasses import dataclass
2
2
 
3
3
  from pcode_graph.analysis import (
4
4
  EntryIndex,
5
5
  OpIndex,
6
6
  RichPcodeList,
7
+ MEMORY,
7
8
  UnknownCodeIndex,
8
9
  ExitIndex,
9
10
  Var,
10
11
  VarKinds,
12
+ wrap,
11
13
  )
12
14
  from pcode_graph.asm import Assembler
13
15
  from pcode_graph.basic_blocks import make_basic_blocks
14
16
  from pcode_graph.checker import check_graph
15
17
  from pcode_graph.graph import CDG, Edge, EdgeKinds, NodeIndex, NodeKinds, Node
18
+ from pcode_graph.memory import StackMemory, analyze_stack_memory
16
19
  from pcode_graph.pcode import from_native_opcode
17
20
  from pcode_graph.registers import SPECIAL_REGISTERS
18
21
  from pcode_graph.simplifier import GraphSimplifier
@@ -25,10 +28,10 @@ from loguru import logger
25
28
  @dataclass
26
29
  class MakerFlags:
27
30
  build_cfg: bool = True
28
- """Add control flow links in addition to the data flow. Defaults to True."""
31
+ """Adds control flow links in addition to the data flow. Defaults to True."""
29
32
 
30
33
  reg_outputs_black_list: set[str] | None = None
31
- """Do not consider the given registers as graph outputs to simplify the graphs.
34
+ """Does not consider the given registers as graph outputs to simplify the graphs.
32
35
  Arch-dependent register names.
33
36
  If white-list is not None, the value of black-list is ignored.
34
37
  If both black-list and white-list are None, the content of SPECIAL_REGISTERS is used
@@ -36,17 +39,23 @@ class MakerFlags:
36
39
  """
37
40
 
38
41
  reg_outputs_white_list: set[str] | None = None
39
- """Consider only the given registers as graph outputs to simplify the graphs.
42
+ """Considers only the given registers as graph outputs to simplify the graphs.
40
43
  Arch-dependent register names.
41
44
  If white-list is not None, the value of black-list is ignored.
42
45
  """
43
46
 
44
47
  basic_blocks: bool = True
45
- """Group operations by basic block in the graph. Make it invariant
48
+ """Groups operations by basic block in the graph. Make it invariant
46
49
  by instruction reordering and to reduce its diameter.
47
50
  Requires build_cfg. Defaults to True.
48
51
  """
49
52
 
53
+ memory_analysis: bool = True
54
+ """Resolves stack accesses to link LOADs to the STORE they read, and forwards
55
+ stored values to the users of LOADs when possible.
56
+ Mainly useful for code compiled without optimization. Defaults to True.
57
+ """
58
+
50
59
 
51
60
  def make_graph(prg: RichPcodeList, flags: MakerFlags | None = None) -> CDG:
52
61
  """Makes a graph from a list of P-Code operations.
@@ -66,6 +75,8 @@ def make_graph(prg: RichPcodeList, flags: MakerFlags | None = None) -> CDG:
66
75
  if black_list is None and white_list is None:
67
76
  black_list = SPECIAL_REGISTERS[prg.arch]
68
77
 
78
+ memory = analyze_stack_memory(prg) if flags.memory_analysis else StackMemory()
79
+
69
80
  # Already created input nodes, by related input variable
70
81
  input_node_indexes: dict[Var, NodeIndex] = {}
71
82
 
@@ -74,7 +85,7 @@ def make_graph(prg: RichPcodeList, flags: MakerFlags | None = None) -> CDG:
74
85
 
75
86
  # Already created phi nodes, by (sorted) possible alternatives
76
87
  # to avoid duplicate phi nodes
77
- phi_node_indexes: dict[tuple[NodeIndex, NodeIndex], NodeIndex] = {}
88
+ phi_node_indexes: dict[tuple[NodeIndex, ...], NodeIndex] = {}
78
89
 
79
90
  # Created nodes of all kinds
80
91
  nodes: list[Node] = []
@@ -169,6 +180,35 @@ def make_graph(prg: RichPcodeList, flags: MakerFlags | None = None) -> CDG:
169
180
  ):
170
181
  edges.append(Edge(from_node, to_node, EdgeKinds.Data, operand_number))
171
182
 
183
+ def get_pred_nodes(var: Var, def_op_indexes: set[OpIndex]) -> list[NodeIndex]:
184
+ """Returns the nodes defining the given variable,
185
+ replacing forwarded loads by the definitions of the stored values."""
186
+
187
+ pred_node_indexes: list[NodeIndex] = []
188
+ seen_loads: set[OpIndex] = set()
189
+ pending = [(var, def_op_indexes)]
190
+ while pending:
191
+ var, def_op_indexes = pending.pop()
192
+ # Sort defs to remain determinist
193
+ for def_op_index in sorted(def_op_indexes):
194
+ store_indexes = memory.forwarded_loads.get(def_op_index)
195
+ if store_indexes is not None:
196
+ if def_op_index not in seen_loads:
197
+ seen_loads.add(def_op_index)
198
+ for store_index in store_indexes:
199
+ value = wrap(prg.operations[store_index].inputs[2])
200
+ value_defs = prg.get_defs(store_index, value)
201
+ pending.append((value, value_defs or {EntryIndex}))
202
+ continue
203
+ if def_op_index == EntryIndex:
204
+ # Input variable
205
+ pred_node_index = get_or_create_input(var)
206
+ else:
207
+ pred_node_index = get_or_create_operation(def_op_index)
208
+ if pred_node_index not in pred_node_indexes:
209
+ pred_node_indexes.append(pred_node_index)
210
+ return pred_node_indexes
211
+
172
212
  def link_defs(
173
213
  var: Var,
174
214
  def_op_indexes: set[OpIndex],
@@ -177,14 +217,7 @@ def make_graph(prg: RichPcodeList, flags: MakerFlags | None = None) -> CDG:
177
217
  ):
178
218
 
179
219
  # Collect data preds to see if we need a phi node
180
- # Sort defs to remain determinist
181
- pred_node_indexes = []
182
- for def_op_index in sorted(list(def_op_indexes)):
183
- if def_op_index == EntryIndex:
184
- # Input variable
185
- pred_node_indexes.append(get_or_create_input(var))
186
- else:
187
- pred_node_indexes.append(get_or_create_operation(def_op_index))
220
+ pred_node_indexes = get_pred_nodes(var, def_op_indexes)
188
221
 
189
222
  if len(pred_node_indexes) == 1:
190
223
  # Simple def, direct link
@@ -264,6 +297,9 @@ def make_graph(prg: RichPcodeList, flags: MakerFlags | None = None) -> CDG:
264
297
 
265
298
  for number, (var, defs) in enumerate(prg.iter_input_defs(op_index)):
266
299
 
300
+ if var == MEMORY and op_index in memory.load_defs:
301
+ defs = memory.load_defs[op_index]
302
+
267
303
  if not defs:
268
304
  # No definition means this is a constant
269
305
  pred_node_index = get_or_create_input(var)
@@ -0,0 +1,271 @@
1
+ """Summary analysis of stack memory accesses.
2
+
3
+ LOAD and STORE addresses are resolved relatively to the stack pointer value at the entry
4
+ of the code, so that loads can be linked to the stores they read. This mainly targets
5
+ spilled variables, as found in code compiled without optimization (-O0).
6
+
7
+ No assumption is made on the use of the stack: calls to unknown code and stores to
8
+ unresolved addresses may write anywhere, so the loads they reach keep the coarse single MEMORY model.
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ import heapq
13
+
14
+ from pypcode import OpCode, PcodeOp
15
+
16
+ from pcode_graph.arch import Arch
17
+ from pcode_graph.analysis import (
18
+ EntryIndex,
19
+ OpIndex,
20
+ RichPcodeList,
21
+ UnknownCodeIndex,
22
+ Var,
23
+ VarKinds,
24
+ wrap,
25
+ )
26
+ from pcode_graph.bit_utils import unsigned_to_signed
27
+
28
+ # Stack pointer register of each architecture, as identified by pypcode
29
+ STACK_POINTERS: dict[Arch, Var] = {
30
+ Arch.x86_64: Var(VarKinds.Register, 8, 0x20, "RSP"),
31
+ Arch.x86_32: Var(VarKinds.Register, 4, 0x10, "ESP"),
32
+ Arch.arm_64: Var(VarKinds.Register, 8, 0x8, "sp"),
33
+ Arch.arm_32: Var(VarKinds.Register, 4, 0x54, "sp"),
34
+ Arch.mips_64: Var(VarKinds.Register, 8, 0xE8, "sp"),
35
+ Arch.mips_32: Var(VarKinds.Register, 4, 0x74, "sp"),
36
+ }
37
+
38
+ # Pseudo definition of memory written by not analyzed code or an unresolved store
39
+ UnknownWriteIndex = -4
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class StackAddress:
44
+ """Address relative to the stack pointer value at entry."""
45
+
46
+ offset: int
47
+
48
+
49
+ # Known constant, stack address or unknown value
50
+ AbstractValue = int | StackAddress | None
51
+
52
+
53
+ @dataclass(frozen=True, slots=True)
54
+ class StackAccess:
55
+ offset: int
56
+ size: int
57
+
58
+ @property
59
+ def offsets(self) -> range:
60
+ return range(self.offset, self.offset + self.size)
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class StackState:
65
+ # Definitions of tracked bytes by offset
66
+ tracked: dict[int, frozenset[OpIndex]]
67
+
68
+ # Definitions of untracked bytes
69
+ default: frozenset[OpIndex]
70
+
71
+ def read(self, access: StackAccess) -> frozenset[OpIndex]:
72
+ return frozenset().union(
73
+ *(self.tracked.get(offset, self.default) for offset in access.offsets)
74
+ )
75
+
76
+ def write(self, access: StackAccess, index: OpIndex) -> "StackState":
77
+ written = frozenset({index})
78
+ tracked = dict(self.tracked)
79
+ for offset in access.offsets:
80
+ tracked[offset] = written
81
+ return StackState(tracked, self.default)
82
+
83
+ def clobber(self) -> "StackState":
84
+ unknown = {UnknownWriteIndex}
85
+ return StackState(
86
+ {offset: defs | unknown for offset, defs in self.tracked.items()},
87
+ self.default | unknown,
88
+ )
89
+
90
+ def merge(self, other: "StackState") -> "StackState":
91
+ return StackState(
92
+ {
93
+ offset: self.tracked.get(offset, self.default)
94
+ | other.tracked.get(offset, other.default)
95
+ for offset in self.tracked.keys() | other.tracked.keys()
96
+ },
97
+ self.default | other.default,
98
+ )
99
+
100
+
101
+ ADDRESS_OPCODES = {OpCode.COPY, OpCode.INT_ADD, OpCode.INT_SUB, OpCode.INT_OR}
102
+ CALL_OPCODES = {OpCode.CALL, OpCode.CALLIND, OpCode.CALLOTHER}
103
+
104
+
105
+ @dataclass
106
+ class StackMemory:
107
+ """Results of the stack memory analysis."""
108
+
109
+ # Maps a stack-reading LOAD to possible STORE definitions
110
+ load_defs: dict[OpIndex, set[OpIndex]] = field(default_factory=dict)
111
+
112
+ # Maps a load to defining stores if reading exactly the values written by them
113
+ forwarded_loads: dict[OpIndex, list[OpIndex]] = field(default_factory=dict)
114
+
115
+
116
+ def analyze_stack_memory(program: RichPcodeList) -> StackMemory:
117
+ return StackMemoryAnalyzer(program)()
118
+
119
+
120
+ class StackMemoryAnalyzer:
121
+
122
+ def __init__(self, program: RichPcodeList) -> None:
123
+ self.program = program
124
+ self.stack_pointer = STACK_POINTERS.get(program.arch)
125
+ self.result = StackMemory()
126
+ self._output_values: dict[OpIndex, AbstractValue] = {}
127
+ self._loads: dict[OpIndex, StackAccess] = {}
128
+ self._stores: dict[OpIndex, StackAccess | None] = {}
129
+
130
+ def __call__(self) -> StackMemory:
131
+ if self.stack_pointer is None or not self.program.basic_blocks:
132
+ return self.result
133
+
134
+ for index, op in enumerate(self.program.operations):
135
+ if not self.program.reachable(index):
136
+ continue
137
+ if op.output is not None:
138
+ # Evaluating in program order bounds the recursion depth
139
+ self._output_value(index, wrap(op.output))
140
+ if op.opcode == OpCode.LOAD:
141
+ access = self._compute_access(index, op.output.size)
142
+ if access is not None:
143
+ self._loads[index] = access
144
+ elif op.opcode == OpCode.STORE:
145
+ self._stores[index] = self._compute_access(index, op.inputs[2].size)
146
+
147
+ self._collect_load_defs(self._compute_reads())
148
+ return self.result
149
+
150
+ def value_of(self, index: OpIndex, var: Var) -> AbstractValue:
151
+ """Evaluates the given variable when read by the given operation."""
152
+
153
+ match var.kind:
154
+ case VarKinds.Constant:
155
+ return unsigned_to_signed(var.value, var.size)
156
+ case VarKinds.Register | VarKinds.Unique:
157
+ pass
158
+ case _:
159
+ return None
160
+
161
+ definitions = self.program.get_defs(index, var)
162
+ if definitions == {EntryIndex}:
163
+ return StackAddress(0) if var == self.stack_pointer else None
164
+ if not definitions or EntryIndex in definitions:
165
+ return None
166
+ values = {self._output_value(definition, var) for definition in definitions}
167
+ return values.pop() if len(values) == 1 else None
168
+
169
+ def _output_value(self, index: OpIndex, var: Var) -> AbstractValue:
170
+ op = self.program.operations[index]
171
+ if op.output is None or wrap(op.output) != var:
172
+ return None
173
+ if index not in self._output_values:
174
+ # Breaks cycles in loops
175
+ self._output_values[index] = None
176
+ self._output_values[index] = self._evaluate(index, op)
177
+ return self._output_values[index]
178
+
179
+ def _evaluate(self, index: OpIndex, op: PcodeOp) -> AbstractValue:
180
+ if op.opcode not in ADDRESS_OPCODES:
181
+ return None
182
+ assert op.output is not None
183
+ operands = [self.value_of(index, wrap(varnode)) for varnode in op.inputs]
184
+ size = op.output.size
185
+ match op.opcode, operands:
186
+ case OpCode.COPY, [value]:
187
+ return value
188
+ case OpCode.INT_ADD, [StackAddress(offset), int(constant)] | [
189
+ int(constant),
190
+ StackAddress(offset),
191
+ ]:
192
+ return StackAddress(truncate(offset + constant, size))
193
+ case OpCode.INT_ADD, [int(left), int(right)]:
194
+ return truncate(left + right, size)
195
+ case OpCode.INT_SUB, [StackAddress(offset), int(constant)]:
196
+ return StackAddress(truncate(offset - constant, size))
197
+ case OpCode.INT_SUB, [StackAddress(left), StackAddress(right)]:
198
+ return truncate(left - right, size)
199
+ case OpCode.INT_SUB, [int(left), int(right)]:
200
+ return truncate(left - right, size)
201
+ case OpCode.INT_OR, [value, 0] | [0, value]:
202
+ return value
203
+ return None
204
+
205
+ def _compute_access(self, index: OpIndex, size: int) -> StackAccess | None:
206
+ address = self.value_of(index, wrap(self.program.operations[index].inputs[1]))
207
+ if isinstance(address, StackAddress):
208
+ return StackAccess(address.offset, size)
209
+ return None
210
+
211
+ def _apply(self, index: OpIndex, state: StackState) -> StackState:
212
+ """Returns the stack state after the given operation."""
213
+
214
+ op = self.program.operations[index]
215
+ if op.opcode == OpCode.STORE:
216
+ access = self._stores[index]
217
+ return state.clobber() if access is None else state.write(access, index)
218
+ if op.opcode in CALL_OPCODES and UnknownCodeIndex in self.program.succ_ops(
219
+ index
220
+ ):
221
+ return state.clobber()
222
+ return state
223
+
224
+ def _compute_reads(self) -> dict[OpIndex, frozenset[OpIndex]]:
225
+ """Computes the definitions of the bytes read by each resolved load."""
226
+
227
+ blocks = self.program.basic_blocks
228
+ block_inputs: list[StackState | None] = [None] * len(blocks)
229
+ block_inputs[0] = StackState({}, frozenset({EntryIndex}))
230
+ reads: dict[OpIndex, frozenset[OpIndex]] = {}
231
+ pending = [0]
232
+ queued = {0}
233
+
234
+ while pending:
235
+ block_index = heapq.heappop(pending)
236
+ queued.remove(block_index)
237
+ state = block_inputs[block_index]
238
+ assert state is not None
239
+ for index in blocks[block_index].op_indexes:
240
+ if index in self._loads:
241
+ reads[index] = state.read(self._loads[index])
242
+ state = self._apply(index, state)
243
+
244
+ for successor in blocks[block_index].succ_blocks:
245
+ if successor < 0:
246
+ continue
247
+ previous = block_inputs[successor]
248
+ merged = state if previous is None else previous.merge(state)
249
+ if merged != previous:
250
+ block_inputs[successor] = merged
251
+ if successor not in queued:
252
+ heapq.heappush(pending, successor)
253
+ queued.add(successor)
254
+ return reads
255
+
256
+ def _collect_load_defs(self, reads: dict[OpIndex, frozenset[OpIndex]]) -> None:
257
+ for index, definitions in reads.items():
258
+ if UnknownWriteIndex in definitions:
259
+ continue
260
+ self.result.load_defs[index] = set(definitions)
261
+ if EntryIndex not in definitions and all(
262
+ self._stores[definition] == self._loads[index]
263
+ for definition in definitions
264
+ ):
265
+ self.result.forwarded_loads[index] = sorted(definitions)
266
+
267
+
268
+ def truncate(value: int, size: int) -> int:
269
+ """Wraps the given value as a signed integer of the given size in bytes."""
270
+
271
+ return unsigned_to_signed(value & ((1 << (size * 8)) - 1), size)
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["hatchling"]
2
+ requires = ["hatchling", "hatch-vcs"]
3
3
  build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pcode_graph"
7
- version = "2.0.2"
7
+ dynamic = ["version"]
8
8
  authors = [
9
9
  { name="Samuel Hangouët", email="samuel.hangouet@quarkslab.com" },
10
10
  ]
@@ -43,5 +43,8 @@ test = ["pytest", "pytest-timeout"]
43
43
  [tool.hatch.build.targets.wheel]
44
44
  packages = ["pcode_graph"]
45
45
 
46
+ [tool.hatch.version]
47
+ source = "vcs"
48
+
46
49
  [project.scripts]
47
50
  cdg = "pcode_graph.cli:main"
@@ -0,0 +1,29 @@
1
+ from pathlib import Path
2
+ import subprocess
3
+ import sys
4
+ from .fixtures import outdir
5
+
6
+ def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
7
+ return subprocess.run(
8
+ [sys.executable, "-m", "pcode_graph", *args], capture_output=True, text=True
9
+ )
10
+
11
+
12
+ def test_assembly_file(outdir: Path):
13
+ assembly_path = outdir / "input.asm"
14
+ assembly_path.write_text("mov rax, qword ptr [rsp]\nret\n")
15
+
16
+ result = run_cli("pcode", str(assembly_path), "--arch", "x86_64")
17
+
18
+ assert result.returncode == 0, result.stderr
19
+ assert "load" in result.stdout
20
+
21
+
22
+ def test_assembly_file_requires_arch(outdir: Path):
23
+ assembly_path = outdir / "input.asm"
24
+ assembly_path.write_text("ret\n")
25
+
26
+ result = run_cli("pcode", str(assembly_path))
27
+
28
+ assert result.returncode == 1
29
+ assert "requires --arch" in result.stderr
@@ -34,6 +34,21 @@ def mips_64() -> ArchContext:
34
34
  return ArchContext(Arch.mips_64)
35
35
 
36
36
 
37
+ @fixture(scope="session")
38
+ def arm32() -> ArchContext:
39
+ return ArchContext(Arch.arm_32)
40
+
41
+
42
+ @fixture(scope="session")
43
+ def x86_32() -> ArchContext:
44
+ return ArchContext(Arch.x86_32)
45
+
46
+
47
+ @fixture(scope="session")
48
+ def mips_32() -> ArchContext:
49
+ return ArchContext(Arch.mips_32)
50
+
51
+
37
52
  @fixture
38
53
  def outdir(request) -> Path:
39
54
  """Creates a fresh test unique directory for generated files,
@@ -102,6 +102,7 @@ def test_load_store(outdir: Path, arm64: ArchContext, log):
102
102
 
103
103
  special_regs = SPECIAL_REGISTERS[arm64.arch] - {"sp"}
104
104
 
105
+ # We treat memory as a single space, not making aliasing analysis
105
106
  g = make_graph_from_asm(
106
107
  """
107
108
  str x0, [sp, #0x40]
@@ -109,13 +110,13 @@ ldp x29, x30, [sp], #0x10
109
110
  """,
110
111
  arm64,
111
112
  outdir,
112
- flags=MakerFlags(reg_outputs_black_list=special_regs),
113
+ flags=MakerFlags(reg_outputs_black_list=special_regs, memory_analysis=False),
113
114
  )
114
115
 
115
116
  load1, load2 = [n for n, node in enumerate(g.nodes) if node.opcode == OpCodes.LOAD]
116
117
  (store,) = [n for n, node in enumerate(g.nodes) if node.opcode == OpCodes.STORE]
117
118
 
118
- # So far, we treat memory as a single space, not maxing aliasing analysis at all
119
+
119
120
  proxy = g.compute_edge_proxy()
120
121
  common_preds = set(proxy[load1].get_data_predecessors()).intersection(
121
122
  proxy[load2].get_data_predecessors()
@@ -140,6 +141,7 @@ ldr x2, [sp, 0x10]
140
141
  """,
141
142
  arm64,
142
143
  outdir,
144
+ flags=MakerFlags(memory_analysis=False),
143
145
  )
144
146
 
145
147
  (load_index,) = [n for n, node in enumerate(g.nodes) if node.opcode == OpCodes.LOAD]
@@ -0,0 +1,285 @@
1
+ from pathlib import Path
2
+
3
+ import pytest
4
+
5
+
6
+ from pcode_graph.graph import CDG, NodeIndex, NodeKinds
7
+ from pcode_graph.maker import MakerFlags
8
+ from pcode_graph.analysis import wrap
9
+ from pcode_graph.memory import STACK_POINTERS, analyze_stack_memory
10
+ from pcode_graph.pcode import OpCodes
11
+ from .helpers import make_graph_from_asm, make_program_from_asm
12
+ from .fixtures import *
13
+
14
+ MEMORY_FLAGS = MakerFlags(memory_analysis=True)
15
+
16
+ X86_ADD_O0 = """
17
+ push rbp
18
+ mov rbp, rsp
19
+ mov dword ptr [rbp-0x14], edi
20
+ mov dword ptr [rbp-0x18], esi
21
+ mov eax, dword ptr [rbp-0x14]
22
+ add eax, dword ptr [rbp-0x18]
23
+ mov dword ptr [rbp-4], eax
24
+ mov eax, dword ptr [rbp-4]
25
+ pop rbp
26
+ ret
27
+ """
28
+
29
+
30
+ def find_nodes(graph: CDG, opcode: OpCodes) -> list[NodeIndex]:
31
+ return [index for index, node in enumerate(graph.nodes) if node.opcode == opcode]
32
+
33
+
34
+ def data_predecessor_names(graph: CDG, index: NodeIndex) -> set[str]:
35
+ proxy = graph.compute_edge_proxy()
36
+ return {str(graph.nodes[pred]) for pred in proxy[index].get_data_predecessors()}
37
+
38
+
39
+ def test_spilled_arguments_x86(outdir: Path, x86_64: ArchContext, log):
40
+ graph = make_graph_from_asm(X86_ADD_O0, x86_64, outdir, flags=MEMORY_FLAGS)
41
+
42
+ # Only the return address is still loaded
43
+ (load,) = find_nodes(graph, OpCodes.LOAD)
44
+ assert data_predecessor_names(graph, load) == {"MEMORY", "INT_ADD"}
45
+ check_outputs(graph, "RAX", "RBP", "MEMORY")
46
+
47
+ (output_rax,) = [i for i, n in enumerate(graph.nodes) if str(n) == "RAX"]
48
+ (add,) = graph.compute_edge_proxy()[output_rax].get_data_predecessors()
49
+ assert data_predecessor_names(graph, add) == {"EDI", "ESI"}
50
+
51
+
52
+ def test_spilled_arguments_arm64(outdir: Path, arm64: ArchContext, log):
53
+ graph = make_graph_from_asm(
54
+ """
55
+ sub sp, sp, #0x10
56
+ str w0, [sp, #0xc]
57
+ str w1, [sp, #8]
58
+ ldr w8, [sp, #0xc]
59
+ ldr w9, [sp, #8]
60
+ add w0, w8, w9
61
+ add sp, sp, #0x10
62
+ ret
63
+ """,
64
+ arm64,
65
+ outdir,
66
+ flags=MEMORY_FLAGS,
67
+ )
68
+
69
+ assert not find_nodes(graph, OpCodes.LOAD)
70
+ (output_w0,) = [i for i, n in enumerate(graph.nodes) if str(n) == "x0"]
71
+ (add,) = graph.compute_edge_proxy()[output_w0].get_data_predecessors()
72
+ assert data_predecessor_names(graph, add) == {"w0", "w1"}
73
+
74
+
75
+ def test_enabled_by_default(outdir: Path, x86_64: ArchContext, log):
76
+ graph = make_graph_from_asm(X86_ADD_O0, x86_64, outdir)
77
+
78
+ assert len(find_nodes(graph, OpCodes.LOAD)) == 1
79
+
80
+
81
+ def test_disabled(outdir: Path, x86_64: ArchContext, log):
82
+ graph = make_graph_from_asm(
83
+ X86_ADD_O0, x86_64, outdir, flags=MakerFlags(memory_analysis=False)
84
+ )
85
+
86
+ assert len(find_nodes(graph, OpCodes.LOAD)) == 5
87
+
88
+
89
+ def test_loop_counter(outdir: Path, x86_64: ArchContext, log):
90
+ graph = make_graph_from_asm(
91
+ """
92
+ push rbp
93
+ mov rbp, rsp
94
+ mov dword ptr [rbp-4], 0
95
+ mov dword ptr [rbp-8], 0
96
+ jmp cond
97
+ body:
98
+ mov eax, dword ptr [rbp-4]
99
+ add dword ptr [rbp-8], eax
100
+ add dword ptr [rbp-4], 1
101
+ cond:
102
+ cmp dword ptr [rbp-4], edi
103
+ jl body
104
+ mov eax, dword ptr [rbp-8]
105
+ pop rbp
106
+ ret
107
+ """,
108
+ x86_64,
109
+ outdir,
110
+ flags=MEMORY_FLAGS,
111
+ )
112
+
113
+ assert len(find_nodes(graph, OpCodes.LOAD)) == 1
114
+
115
+ # Counter and sum are merged with their initial value
116
+ value_phis = [
117
+ index
118
+ for index, node in enumerate(graph.nodes)
119
+ if node.kind == NodeKinds.Phi
120
+ and data_predecessor_names(graph, index) == {"#0x0", "INT_ADD"}
121
+ ]
122
+ assert len(value_phis) == 2
123
+
124
+
125
+ def test_partial_overlap(outdir: Path, arm64: ArchContext, log):
126
+ graph = make_graph_from_asm(
127
+ """
128
+ str x0, [sp, #-0x10]
129
+ ldr w1, [sp, #-0xc]
130
+ """,
131
+ arm64,
132
+ outdir,
133
+ flags=MEMORY_FLAGS,
134
+ )
135
+
136
+ # Not forwarded, but directly linked to the store instead of a phi with MEMORY
137
+ (load,) = find_nodes(graph, OpCodes.LOAD)
138
+ assert data_predecessor_names(graph, load) == {"STORE", "INT_ADD"}
139
+
140
+
141
+ def test_no_alias(outdir: Path, arm64: ArchContext, log):
142
+ graph = make_graph_from_asm(
143
+ """
144
+ str x0, [sp, #0x40]
145
+ ldp x29, x30, [sp], #0x10
146
+ """,
147
+ arm64,
148
+ outdir,
149
+ flags=MEMORY_FLAGS,
150
+ )
151
+
152
+ for load in find_nodes(graph, OpCodes.LOAD):
153
+ assert data_predecessor_names(graph, load) & {"MEMORY", "STORE"} == {"MEMORY"}
154
+
155
+
156
+ def test_unresolved_store_may_alias(outdir: Path, x86_64: ArchContext, log):
157
+ # RDI may point to RSP-8, as in a ROP gadget
158
+ graph = make_graph_from_asm(
159
+ """
160
+ mov qword ptr [rsp-8], rax
161
+ mov qword ptr [rdi], rcx
162
+ mov rbx, qword ptr [rsp-8]
163
+ ret
164
+ """,
165
+ x86_64,
166
+ outdir,
167
+ flags=MEMORY_FLAGS,
168
+ )
169
+
170
+ rbx_load = [
171
+ load
172
+ for load in find_nodes(graph, OpCodes.LOAD)
173
+ if any(
174
+ str(graph.nodes[s]) == "RBX"
175
+ for s in graph.compute_edge_proxy()[load].get_data_successors()
176
+ )
177
+ ]
178
+ assert len(rbx_load) == 1
179
+
180
+
181
+ def test_store_below_stack_pointer_is_kept(outdir: Path, x86_64: ArchContext, log):
182
+ # The next gadget of a chain may read it
183
+ graph = make_graph_from_asm(
184
+ "mov qword ptr [rsp-0x10], rax; ret", x86_64, outdir, flags=MEMORY_FLAGS
185
+ )
186
+
187
+ assert len(find_nodes(graph, OpCodes.STORE)) == 1
188
+ check_outputs(graph, "MEMORY")
189
+
190
+
191
+ def test_unresolved_load_keeps_all_stores(outdir: Path, arm64: ArchContext, log):
192
+ graph = make_graph_from_asm(
193
+ """
194
+ str x0, [sp, #-0x10]
195
+ ldr x1, [x2]
196
+ """,
197
+ arm64,
198
+ outdir,
199
+ flags=MEMORY_FLAGS,
200
+ )
201
+
202
+ (load,) = find_nodes(graph, OpCodes.LOAD)
203
+ (phi,) = [
204
+ pred
205
+ for pred in graph.compute_edge_proxy()[load].get_data_predecessors()
206
+ if graph.nodes[pred].kind == NodeKinds.Phi
207
+ ]
208
+ assert data_predecessor_names(graph, phi) == {"MEMORY", "STORE"}
209
+
210
+
211
+ def test_call_clobbers_stack(outdir: Path, x86_64: ArchContext, log):
212
+ program = make_program_from_asm(
213
+ """
214
+ mov qword ptr [rsp-0x10], rdi
215
+ mov rax, qword ptr [rsp-0x10]
216
+ call 0x1000
217
+ mov rbx, qword ptr [rsp-0x10]
218
+ """,
219
+ x86_64,
220
+ outdir,
221
+ )
222
+ memory = analyze_stack_memory(program)
223
+
224
+ # Only the load before the call is resolved
225
+ (call,) = [i for i, op in enumerate(program.operations) if op.opcode.name == "CALL"]
226
+ (forwarded_load,) = memory.forwarded_loads
227
+ assert forwarded_load < call
228
+ assert list(memory.load_defs) == [forwarded_load]
229
+
230
+
231
+ def test_internal_call_does_not_clobber(outdir: Path, x86_64: ArchContext, log):
232
+ # Call used as push + jump, as in obfuscated code
233
+ graph = make_graph_from_asm(
234
+ "call target; nop; target: pop rax; ret", x86_64, outdir, flags=MEMORY_FLAGS
235
+ )
236
+
237
+ # Only the return address of ret is still loaded
238
+ assert len(find_nodes(graph, OpCodes.LOAD)) == 1
239
+
240
+
241
+ def test_address_wraps_around(outdir: Path, x86_64: ArchContext, log):
242
+ # RAX = RSP + 2^64, so the second store overwrites the first one
243
+ program = make_program_from_asm(
244
+ """
245
+ mov qword ptr [rsp-8], rcx
246
+ mov rax, 0x4000000000000000
247
+ add rax, rax
248
+ add rax, rax
249
+ add rax, rsp
250
+ mov qword ptr [rax-8], rdx
251
+ mov rbx, qword ptr [rsp-8]
252
+ """,
253
+ x86_64,
254
+ outdir,
255
+ )
256
+ memory = analyze_stack_memory(program)
257
+
258
+ stores = [
259
+ index
260
+ for index, op in enumerate(program.operations)
261
+ if op.opcode.name == "STORE"
262
+ ]
263
+ assert list(memory.forwarded_loads.values()) == [[stores[1]]]
264
+
265
+
266
+ def test_long_stack_pointer_chain(outdir: Path, x86_64: ArchContext, log):
267
+ program = make_program_from_asm(
268
+ "mov qword ptr [rsp], rax\n" + "add rsp, 8\n" * 600 + "mov rbx, [rsp - 4800]",
269
+ x86_64,
270
+ outdir,
271
+ )
272
+
273
+ assert len(analyze_stack_memory(program).forwarded_loads) == 1
274
+
275
+
276
+ @pytest.mark.parametrize(
277
+ "arch_fixture", ["x86_64", "x86_32", "arm64", "arm32", "mips_64", "mips_32"]
278
+ )
279
+ def test_stack_pointers_match_pypcode(
280
+ arch_fixture: str, request: pytest.FixtureRequest
281
+ ):
282
+ arch: ArchContext = request.getfixturevalue(arch_fixture)
283
+ stack_pointer = STACK_POINTERS[arch.arch]
284
+ registers = arch.translator.context.registers
285
+ assert wrap(registers[stack_pointer.pretty_name]) == stack_pointer
File without changes
File without changes
File without changes